Search in sources :

Example 26 with MessageHandlingException

use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.

the class StoredProcOutboundGatewayWithSpelIntegrationTests method testWithMissingMessageHeader.

@Test
@DirtiesContext
public void testWithMissingMessageHeader() throws Exception {
    User user1 = new User("First User", "my first password", "email1");
    Message<User> user1Message = MessageBuilder.withPayload(user1).build();
    this.channel.send(user1Message);
    Message<?> receive = this.startErrorsChannel.receive(10000);
    assertNotNull(receive);
    assertThat(receive, instanceOf(ErrorMessage.class));
    MessageHandlingException exception = (MessageHandlingException) receive.getPayload();
    String expectedMessage = "Unable to resolve Stored Procedure/Function name " + "for the provided Expression 'headers['my_stored_procedure']'.";
    String actualMessage = exception.getCause().getMessage();
    Assert.assertEquals(expectedMessage, actualMessage);
}
Also used : User(org.springframework.integration.jdbc.storedproc.User) ErrorMessage(org.springframework.messaging.support.ErrorMessage) MessageHandlingException(org.springframework.messaging.MessageHandlingException) Test(org.junit.Test) DirtiesContext(org.springframework.test.annotation.DirtiesContext)

Example 27 with MessageHandlingException

use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.

the class StoredProcOutboundGateway method handleRequestMessage.

@Override
protected Object handleRequestMessage(Message<?> requestMessage) {
    Map<String, Object> resultMap = this.executor.executeStoredProcedure(requestMessage);
    final Object payload;
    if (resultMap.isEmpty()) {
        return null;
    } else {
        if (this.expectSingleResult && resultMap.size() == 1) {
            payload = resultMap.values().iterator().next();
        } else if (this.expectSingleResult && resultMap.size() > 1) {
            throw new MessageHandlingException(requestMessage, "Stored Procedure/Function call returned more than " + "1 result object and expectSingleResult was 'true'. ");
        } else {
            payload = resultMap;
        }
    }
    return payload;
}
Also used : MessageHandlingException(org.springframework.messaging.MessageHandlingException)

Example 28 with MessageHandlingException

use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.

the class FileSplitter method splitMessage.

@Override
protected Object splitMessage(final Message<?> message) {
    Object payload = message.getPayload();
    Reader reader = null;
    final String filePath;
    if (payload instanceof String) {
        try {
            reader = new FileReader((String) payload);
            filePath = (String) payload;
        } catch (FileNotFoundException e) {
            throw new MessageHandlingException(message, "failed to read file [" + payload + "]", e);
        }
    } else if (payload instanceof File) {
        try {
            if (this.charset == null) {
                reader = new FileReader((File) payload);
            } else {
                reader = new InputStreamReader(new FileInputStream((File) payload), this.charset);
            }
            filePath = ((File) payload).getAbsolutePath();
        } catch (FileNotFoundException e) {
            throw new MessageHandlingException(message, "failed to read file [" + payload + "]", e);
        }
    } else if (payload instanceof InputStream) {
        if (this.charset == null) {
            reader = new InputStreamReader((InputStream) payload);
        } else {
            reader = new InputStreamReader((InputStream) payload, this.charset);
        }
        filePath = buildPathFromMessage(message, ":stream:");
    } else if (payload instanceof Reader) {
        reader = (Reader) payload;
        filePath = buildPathFromMessage(message, ":reader:");
    } else {
        return message;
    }
    final BufferedReader bufferedReader = new BufferedReader(reader) {

        @Override
        public void close() throws IOException {
            try {
                super.close();
            } finally {
                Closeable closeableResource = StaticMessageHeaderAccessor.getCloseableResource(message);
                if (closeableResource != null) {
                    closeableResource.close();
                }
            }
        }
    };
    String firstLineAsHeader;
    if (this.firstLineHeaderName != null) {
        try {
            firstLineAsHeader = bufferedReader.readLine();
        } catch (IOException e) {
            throw new MessageHandlingException(message, "IOException while reading first line", e);
        }
    } else {
        firstLineAsHeader = null;
    }
    Iterator<Object> iterator = new CloseableIterator<Object>() {

        boolean markers = FileSplitter.this.markers;

        boolean sof = this.markers;

        boolean eof;

        boolean done;

        String line;

        long lineCount;

        boolean hasNextCalled;

        @Override
        public boolean hasNext() {
            this.hasNextCalled = true;
            try {
                if (!this.done && this.line == null) {
                    this.line = bufferedReader.readLine();
                }
                boolean ready = !this.done && this.line != null;
                if (!ready) {
                    if (this.markers) {
                        this.eof = true;
                        if (this.sof) {
                            this.done = true;
                        }
                    }
                    bufferedReader.close();
                }
                return this.sof || ready || this.eof;
            } catch (IOException e) {
                try {
                    this.done = true;
                    bufferedReader.close();
                } catch (IOException e1) {
                // ignored
                }
                throw new MessageHandlingException(message, "IOException while iterating", e);
            }
        }

        @Override
        public Object next() {
            if (!this.hasNextCalled) {
                hasNext();
            }
            this.hasNextCalled = false;
            if (this.sof) {
                this.sof = false;
                return markerToReturn(new FileMarker(filePath, Mark.START, 0));
            }
            if (this.eof) {
                this.eof = false;
                this.markers = false;
                this.done = true;
                return markerToReturn(new FileMarker(filePath, Mark.END, this.lineCount));
            }
            if (this.line != null) {
                String line = this.line;
                this.line = null;
                this.lineCount++;
                AbstractIntegrationMessageBuilder<String> messageBuilder = getMessageBuilderFactory().withPayload(line);
                if (firstLineAsHeader != null) {
                    messageBuilder.setHeader(FileSplitter.this.firstLineHeaderName, firstLineAsHeader);
                }
                return messageBuilder;
            } else {
                this.done = true;
                throw new NoSuchElementException(filePath + " has been consumed");
            }
        }

        private AbstractIntegrationMessageBuilder<Object> markerToReturn(FileMarker fileMarker) {
            Object payload;
            if (FileSplitter.this.markersJson) {
                try {
                    payload = objectMapper.toJson(fileMarker);
                } catch (Exception e) {
                    throw new MessageHandlingException(message, "Failed to convert marker to JSON", e);
                }
            } else {
                payload = fileMarker;
            }
            return getMessageBuilderFactory().withPayload(payload).setHeader(FileHeaders.MARKER, fileMarker.mark.name());
        }

        @Override
        public void close() {
            try {
                this.done = true;
                bufferedReader.close();
            } catch (IOException e) {
            // ignored
            }
        }
    };
    if (this.iterator) {
        return iterator;
    } else {
        List<Object> lines = new ArrayList<Object>();
        while (iterator.hasNext()) {
            lines.add(iterator.next());
        }
        return lines;
    }
}
Also used : CloseableIterator(org.springframework.integration.util.CloseableIterator) InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Closeable(java.io.Closeable) FileNotFoundException(java.io.FileNotFoundException) ArrayList(java.util.ArrayList) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) IOException(java.io.IOException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) FileInputStream(java.io.FileInputStream) MessageHandlingException(org.springframework.messaging.MessageHandlingException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) File(java.io.File) NoSuchElementException(java.util.NoSuchElementException)

Example 29 with MessageHandlingException

use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.

the class OperationInvokingMessageHandler method handleRequestMessage.

@Override
protected Object handleRequestMessage(Message<?> requestMessage) {
    ObjectName objectName = this.resolveObjectName(requestMessage);
    String operationName = this.resolveOperationName(requestMessage);
    Map<String, Object> paramsFromMessage = this.resolveParameters(requestMessage);
    try {
        MBeanInfo mbeanInfo = this.server.getMBeanInfo(objectName);
        MBeanOperationInfo[] opInfoArray = mbeanInfo.getOperations();
        boolean hasNoArgOption = false;
        for (MBeanOperationInfo opInfo : opInfoArray) {
            if (operationName.equals(opInfo.getName())) {
                MBeanParameterInfo[] paramInfoArray = opInfo.getSignature();
                if (paramInfoArray.length == 0) {
                    hasNoArgOption = true;
                }
                if (paramInfoArray.length == paramsFromMessage.size()) {
                    int index = 0;
                    Object[] values = new Object[paramInfoArray.length];
                    String[] signature = new String[paramInfoArray.length];
                    for (MBeanParameterInfo paramInfo : paramInfoArray) {
                        Object value = paramsFromMessage.get(paramInfo.getName());
                        if (value == null) {
                            /*
								 * With Spring 3.2.3 and greater, the parameter names are
								 * registered instead of the JVM's default p1, p2 etc.
								 * Fall back to that naming style if not found.
								 */
                            value = paramsFromMessage.get("p" + (index + 1));
                        }
                        if (value != null && valueTypeMatchesParameterType(value, paramInfo)) {
                            values[index] = value;
                            signature[index] = paramInfo.getType();
                            index++;
                        }
                    }
                    if (index == paramInfoArray.length) {
                        return this.server.invoke(objectName, operationName, values, signature);
                    }
                }
            }
        }
        if (hasNoArgOption) {
            return this.server.invoke(objectName, operationName, null, null);
        }
        throw new MessagingException(requestMessage, "failed to find JMX operation '" + operationName + "' on MBean [" + objectName + "] of type [" + mbeanInfo.getClassName() + "] with " + paramsFromMessage.size() + " parameters: " + paramsFromMessage);
    } catch (JMException e) {
        throw new MessageHandlingException(requestMessage, "failed to invoke JMX operation '" + operationName + "' on MBean [" + objectName + "]" + " with " + paramsFromMessage.size() + " parameters: " + paramsFromMessage, e);
    } catch (IOException e) {
        throw new MessageHandlingException(requestMessage, "IOException on MBeanServerConnection", e);
    }
}
Also used : MBeanInfo(javax.management.MBeanInfo) MessagingException(org.springframework.messaging.MessagingException) MBeanOperationInfo(javax.management.MBeanOperationInfo) IOException(java.io.IOException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) ObjectName(javax.management.ObjectName) JMException(javax.management.JMException) MBeanParameterInfo(javax.management.MBeanParameterInfo)

Example 30 with MessageHandlingException

use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.

the class ChatMessageSendingMessageHandler method handleMessageInternal.

@Override
protected void handleMessageInternal(Message<?> message) throws Exception {
    Assert.isTrue(this.initialized, getComponentName() + "#" + this.getComponentType() + " must be initialized");
    Object payload = message.getPayload();
    org.jivesoftware.smack.packet.Message xmppMessage = null;
    if (payload instanceof org.jivesoftware.smack.packet.Message) {
        xmppMessage = (org.jivesoftware.smack.packet.Message) payload;
    } else {
        String to = message.getHeaders().get(XmppHeaders.TO, String.class);
        Assert.state(StringUtils.hasText(to), "The '" + XmppHeaders.TO + "' header must not be null");
        xmppMessage = new org.jivesoftware.smack.packet.Message(JidCreate.from(to));
        if (payload instanceof ExtensionElement) {
            xmppMessage.addExtension((ExtensionElement) payload);
        } else if (payload instanceof String) {
            if (this.extensionProvider != null) {
                String data = (String) payload;
                if (!XML_PATTERN.matcher(data.trim()).matches()) {
                    // Since XMPP Extension parsers deal only with XML content,
                    // add an arbitrary tag that is removed by the extension parser,
                    // if the target content isn't XML.
                    data = "<root>" + data + "</root>";
                }
                XmlPullParser xmlPullParser = PacketParserUtils.newXmppParser(new StringReader(data));
                xmlPullParser.next();
                ExtensionElement extension = this.extensionProvider.parse(xmlPullParser);
                xmppMessage.addExtension(extension);
            } else {
                xmppMessage.setBody((String) payload);
            }
        } else {
            throw new MessageHandlingException(message, "Only payloads of type java.lang.String, org.jivesoftware.smack.packet.Message " + "or org.jivesoftware.smack.packet.ExtensionElement " + "are supported. Received [" + payload.getClass().getName() + "]. Consider adding a Transformer prior to this adapter.");
        }
    }
    if (this.headerMapper != null) {
        this.headerMapper.fromHeadersToRequest(message.getHeaders(), xmppMessage);
    }
    if (!this.xmppConnection.isConnected() && this.xmppConnection instanceof AbstractXMPPConnection) {
        ((AbstractXMPPConnection) this.xmppConnection).connect();
    }
    this.xmppConnection.sendStanza(xmppMessage);
}
Also used : Message(org.springframework.messaging.Message) ExtensionElement(org.jivesoftware.smack.packet.ExtensionElement) XmlPullParser(org.xmlpull.v1.XmlPullParser) MessageHandlingException(org.springframework.messaging.MessageHandlingException) StringReader(java.io.StringReader) AbstractXMPPConnection(org.jivesoftware.smack.AbstractXMPPConnection)

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