Search in sources :

Example 21 with MessageHandlingException

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")));
}
Also used : WebServiceMessageFactory(org.springframework.ws.WebServiceMessageFactory) SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) Attachment(org.springframework.ws.mime.Attachment) SaajSoapMessageFactory(org.springframework.ws.soap.saaj.SaajSoapMessageFactory) ByteArrayResource(org.springframework.core.io.ByteArrayResource) ClientInterceptorAdapter(org.springframework.ws.client.support.interceptor.ClientInterceptorAdapter) MessageHandlingException(org.springframework.messaging.MessageHandlingException) WebServiceMessage(org.springframework.ws.WebServiceMessage) MimeMessage(org.springframework.ws.mime.MimeMessage) BeanFactory(org.springframework.beans.factory.BeanFactory) MessageContext(org.springframework.ws.context.MessageContext) StringSource(org.springframework.xml.transform.StringSource) StringResult(org.springframework.xml.transform.StringResult) Test(org.junit.Test)

Example 22 with MessageHandlingException

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);
}
Also used : WebServiceConnection(org.springframework.ws.transport.WebServiceConnection) XMPPConnection(org.jivesoftware.smack.XMPPConnection) Connection(javax.jms.Connection) MailSenderConnection(org.springframework.ws.transport.mail.MailSenderConnection) BytesMessage(javax.jms.BytesMessage) MessageProducer(javax.jms.MessageProducer) WebServiceIOException(org.springframework.ws.client.WebServiceIOException) Queue(javax.jms.Queue) URI(java.net.URI) MessageHandlingException(org.springframework.messaging.MessageHandlingException) Session(javax.jms.Session) Test(org.junit.Test)

Example 23 with MessageHandlingException

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());
}
Also used : WebServiceMessageCallback(org.springframework.ws.client.core.WebServiceMessageCallback) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) AtomicReference(java.util.concurrent.atomic.AtomicReference) WebServiceIOException(org.springframework.ws.client.WebServiceIOException) WebServiceTemplate(org.springframework.ws.client.core.WebServiceTemplate) MessageHandlingException(org.springframework.messaging.MessageHandlingException) Test(org.junit.Test)

Example 24 with MessageHandlingException

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());
}
Also used : WebServiceConnection(org.springframework.ws.transport.WebServiceConnection) MessageHandlingException(org.springframework.messaging.MessageHandlingException) Test(org.junit.Test)

Example 25 with MessageHandlingException

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;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) File(java.io.File) MessageHandlingException(org.springframework.messaging.MessageHandlingException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Aggregations

MessageHandlingException (org.springframework.messaging.MessageHandlingException)66 Test (org.junit.Test)34 ErrorMessage (org.springframework.messaging.support.ErrorMessage)14 IOException (java.io.IOException)12 GenericMessage (org.springframework.messaging.support.GenericMessage)12 Message (org.springframework.messaging.Message)10 MessagingException (org.springframework.messaging.MessagingException)10 File (java.io.File)9 Matchers.containsString (org.hamcrest.Matchers.containsString)6 BeanFactory (org.springframework.beans.factory.BeanFactory)6 FileNotFoundException (java.io.FileNotFoundException)4 ArrayList (java.util.ArrayList)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 ClassPathXmlApplicationContext (org.springframework.context.support.ClassPathXmlApplicationContext)4 MessageRejectedException (org.springframework.integration.MessageRejectedException)4 QueueChannel (org.springframework.integration.channel.QueueChannel)4 AbstractReplyProducingMessageHandler (org.springframework.integration.handler.AbstractReplyProducingMessageHandler)4 FileOutputStream (java.io.FileOutputStream)3 OutputStream (java.io.OutputStream)3 IntegrationMessageHeaderAccessor (org.springframework.integration.IntegrationMessageHeaderAccessor)3