use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.
the class SimpleWebServiceOutboundGatewayTests method testAttachments.
@Test
public void testAttachments() throws Exception {
String uri = "http://www.example.org";
SimpleWebServiceOutboundGateway gateway = new SimpleWebServiceOutboundGateway(uri);
gateway.setBeanFactory(mock(BeanFactory.class));
final SettableListenableFuture<WebServiceMessage> requestFuture = new SettableListenableFuture<>();
ClientInterceptorAdapter interceptorAdapter = new ClientInterceptorAdapter() {
@Override
public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
requestFuture.set(messageContext.getRequest());
return super.handleRequest(messageContext);
}
};
gateway.setInterceptors(interceptorAdapter);
gateway.afterPropertiesSet();
WebServiceMessageFactory messageFactory = new SaajSoapMessageFactory(MessageFactory.newInstance());
MimeMessage webServiceMessage = (MimeMessage) messageFactory.createWebServiceMessage();
String request = "<test>foo</test>";
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new StringSource(request), webServiceMessage.getPayloadResult());
webServiceMessage.addAttachment("myAttachment", new ByteArrayResource("my_data".getBytes()), "text/plain");
try {
gateway.handleMessage(new GenericMessage<>(webServiceMessage));
fail("Expected MessageHandlingException");
} catch (MessageHandlingException e) {
// expected
}
WebServiceMessage requestMessage = requestFuture.get(10, TimeUnit.SECONDS);
assertNotNull(requestMessage);
assertThat(requestMessage, instanceOf(MimeMessage.class));
transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringResult stringResult = new StringResult();
transformer.transform(requestMessage.getPayloadSource(), stringResult);
assertEquals(request, stringResult.toString());
Attachment myAttachment = ((MimeMessage) requestMessage).getAttachment("myAttachment");
assertNotNull(myAttachment);
assertEquals("text/plain", myAttachment.getContentType());
assertEquals("my_data", StreamUtils.copyToString(myAttachment.getInputStream(), Charset.forName("UTF-8")));
}
use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.
the class UriVariableTests method testInt2720JmsUriVariables.
@Test
public void testInt2720JmsUriVariables() throws JMSException, IOException {
final String destinationName = "SPRING.INTEGRATION.QUEUE";
Queue queue = Mockito.mock(Queue.class);
// Need for 'QueueSession#createQueue()'
Mockito.when(queue.getQueueName()).thenReturn(destinationName);
Session session = Mockito.mock(Session.class);
Mockito.when(session.createQueue(Mockito.anyString())).thenReturn(queue);
Mockito.when(session.createBytesMessage()).thenReturn(Mockito.mock(BytesMessage.class));
MessageProducer producer = Mockito.mock(MessageProducer.class);
Mockito.when(session.createProducer(queue)).thenReturn(producer);
// For this test it's enough to not go ahead. Invoked in the 'JmsSenderConnection#onSendAfterWrite' on the
// 'WebServiceTemplate#sendRequest' after invocation of our 'TestClientInterceptor'
Mockito.when(session.createTemporaryQueue()).thenThrow(new WebServiceIOException("intentional"));
Connection connection = Mockito.mock(Connection.class);
Mockito.when(connection.createSession(Mockito.anyBoolean(), Mockito.anyInt())).thenReturn(session);
Mockito.when(this.jmsConnectionFactory.createConnection()).thenReturn(connection);
Message<?> message = MessageBuilder.withPayload("<spring/>").setHeader("jmsQueue", destinationName).setHeader("deliveryMode", "NON_PERSISTENT").setHeader("jms_priority", "5").build();
try {
this.inputJms.send(message);
} catch (MessageHandlingException e) {
// expected
Class<?> causeType = e.getCause().getClass();
// offline
assertTrue(WebServiceIOException.class.equals(causeType));
}
URI uri = URI.create("jms:SPRING.INTEGRATION.QUEUE?deliveryMode=NON_PERSISTENT&priority=5");
Mockito.verify(this.jmsMessageSender).createConnection(uri);
Mockito.verify(session).createQueue(destinationName);
assertEquals("jms:" + destinationName, this.interceptor.getLastUri().toString());
Mockito.verify(producer).setDeliveryMode(DeliveryMode.NON_PERSISTENT);
Mockito.verify(producer).setPriority(5);
}
use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.
the class UriVariableTests method testHttpUriVariables.
@Test
@SuppressWarnings("unchecked")
public void testHttpUriVariables() {
WebServiceTemplate webServiceTemplate = TestUtils.getPropertyValue(this.httpOutboundGateway, "webServiceTemplate", WebServiceTemplate.class);
webServiceTemplate = Mockito.spy(webServiceTemplate);
final AtomicReference<String> uri = new AtomicReference<>();
doAnswer(invocation -> {
uri.set(invocation.getArgument(0));
throw new WebServiceIOException("intentional");
}).when(webServiceTemplate).sendAndReceive(Mockito.anyString(), Mockito.any(WebServiceMessageCallback.class), (WebServiceMessageExtractor<Object>) Mockito.any(WebServiceMessageExtractor.class));
new DirectFieldAccessor(this.httpOutboundGateway).setPropertyValue("webServiceTemplate", webServiceTemplate);
Message<?> message = MessageBuilder.withPayload("<spring/>").setHeader("x", "integration").setHeader("param", "test1 & test2").build();
try {
this.inputHttp.send(message);
} catch (MessageHandlingException e) {
// expected
// offline
assertThat(e.getCause(), Matchers.is(Matchers.instanceOf(WebServiceIOException.class)));
}
assertEquals("http://localhost/spring-integration?param=test1%20&%20test2", uri.get());
}
use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.
the class UriVariableTests method testInt2720EmailUriVariables.
@Test
public void testInt2720EmailUriVariables() {
final String testEmailTo = "user@example.com";
final String testEmailSubject = "Test subject";
Message<?> message = MessageBuilder.withPayload("<spring/>").setHeader("to", testEmailTo).setHeader("subject", testEmailSubject).build();
try {
this.inputEmail.send(message);
} catch (MessageHandlingException e) {
// expected
Class<?> causeType = e.getCause().getClass();
// offline
assertTrue(WebServiceIOException.class.equals(causeType));
}
WebServiceConnection webServiceConnection = this.emailInterceptor.getLastWebServiceConnection();
assertEquals(testEmailTo, TestUtils.getPropertyValue(webServiceConnection, "to").toString());
assertEquals(testEmailSubject, TestUtils.getPropertyValue(webServiceConnection, "subject"));
assertEquals("mailto:user@example.com?subject=Test%20subject", this.emailInterceptor.getLastUri().toString());
}
use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.
the class FileWritingMessageHandler method handleRequestMessage.
@Override
protected Object handleRequestMessage(Message<?> requestMessage) {
Assert.notNull(requestMessage, "message must not be null");
Object payload = requestMessage.getPayload();
Assert.notNull(payload, "message payload must not be null");
String generatedFileName = this.fileNameGenerator.generateFileName(requestMessage);
File originalFileFromHeader = retrieveOriginalFileFromHeader(requestMessage);
final File destinationDirectoryToUse = evaluateDestinationDirectoryExpression(requestMessage);
File tempFile = new File(destinationDirectoryToUse, generatedFileName + this.temporaryFileSuffix);
File resultFile = new File(destinationDirectoryToUse, generatedFileName);
boolean exists = resultFile.exists();
if (exists && FileExistsMode.FAIL.equals(this.fileExistsMode)) {
throw new MessageHandlingException(requestMessage, "The destination file already exists at '" + resultFile.getAbsolutePath() + "'.");
}
Object timestamp = requestMessage.getHeaders().get(FileHeaders.SET_MODIFIED);
if (payload instanceof File) {
timestamp = ((File) payload).lastModified();
}
boolean ignore = (FileExistsMode.IGNORE.equals(this.fileExistsMode) && (exists || (StringUtils.hasText(this.temporaryFileSuffix) && tempFile.exists()))) || ((exists && FileExistsMode.REPLACE_IF_MODIFIED.equals(this.fileExistsMode)) && (timestamp instanceof Number && ((Number) timestamp).longValue() == resultFile.lastModified()));
if (!ignore) {
try {
if (!exists && generatedFileName.replaceAll("/", Matcher.quoteReplacement(File.separator)).contains(File.separator)) {
// NOSONAR - will fail on the writing below
resultFile.getParentFile().mkdirs();
}
if (payload instanceof File) {
resultFile = handleFileMessage((File) payload, tempFile, resultFile);
} else if (payload instanceof InputStream) {
resultFile = handleInputStreamMessage((InputStream) payload, originalFileFromHeader, tempFile, resultFile);
} else if (payload instanceof byte[]) {
resultFile = this.handleByteArrayMessage((byte[]) payload, originalFileFromHeader, tempFile, resultFile);
} else if (payload instanceof String) {
resultFile = this.handleStringMessage((String) payload, originalFileFromHeader, tempFile, resultFile);
} else {
throw new IllegalArgumentException("unsupported Message payload type [" + payload.getClass().getName() + "]");
}
if (this.preserveTimestamp) {
if (timestamp instanceof Number) {
resultFile.setLastModified(((Number) timestamp).longValue());
} else {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Could not set lastModified, header " + FileHeaders.SET_MODIFIED + " must be a Number, not " + (timestamp == null ? "null" : timestamp.getClass()));
}
}
}
} catch (Exception e) {
throw new MessageHandlingException(requestMessage, "failed to write Message payload to file", e);
}
}
if (!this.expectReply) {
return null;
}
if (resultFile != null) {
if (originalFileFromHeader == null && payload instanceof File) {
return this.getMessageBuilderFactory().withPayload(resultFile).setHeader(FileHeaders.ORIGINAL_FILE, payload);
}
}
return resultFile;
}
Aggregations