Spring Integration Chain Exception Handling with Header enricher inside chain - spring-integration

I have a common flow that will be reused multiple times. So, I defined a SI Chain for it like below.
<int:chain id="addInfo" input-channel="addInfoChannel">
<int:header-enricher>
<int:header name="outgoingService" value="Retrieve" />
</int:header-enricher>
<int:gateway request-channel="common_Retrieve_Channel" />
<int-xml:xslt-transformer xsl-templates="addInfoXslTemplate">
<int-xml:xslt-param name="param1" expression="headers.param1" />
<int-xml:xslt-param name="param2" expression="headers.param2" />
</int-xml:xslt-transformer>
<int:header-enricher>
<int:header name="outgoingService" value="Add" overwrite="true" />
</int:header-enricher>
<int:gateway request-channel="common_Add_Channel" />
</int:chain>
If the common_Retrieve_Channel channel fails with a SOAP fault, the header value (outgoingService) is lost.
If I have the header-enricher outside the chain, then header value is available on payload.failedMessage.headers.
I don't want to add this value outside chain, Since this value will be changing inside the chain to call another service.
This chain will be called multiple times by setting up the header values (param1 and param2) differently.
Please let me know if there is any better solution other than extracting the gateway into it's own chain. Thanks for your help.

You must have some compensation flow on the error-channel of your <gateway>.
Since you say that you have SOAP error and you already are familiar with the payload.failedMessage.headers you just need to write something like this there:
<int:transformer input-channel="gatewayErrorChannel" expression="payload.failedMessage"/>
And looks like you further <chain> flow should be the same. Only difference that you will get deal there with requestMessage only, but lose error information from the external SOAP request.

Related

AWS Async Response routing to success-channel for sqs-outbound-channel-adapter

I have registered an AsyncHandler and also added a success-channel to an SQS outbound flow. The success-channel has a int:logging-channel-adapter endpoint. However I am not able to see any logs from this adapter. The AsyncHandler is able to receive the call-backs but nothing on the success-channel.
In the SqsMessageHandler I see that we are setting an output channel in the obtainAsyncHandler method, but I did not see the success-channel set anywhere. Am I missing something?
I would prefer using the success and failure channels and not AsyncHandler call-back Impl to avoid having AWS specific code in my classes.
Also my <int-aws:sqs-outbound-channel-adapter> is inside a <int:chain> which has no output channel, since the flow ends when the message is sent.
EDIT - Added Config
This is the only way I can get it to log the callback.
<int:channel id="chainChannel" />
<int:channel id="successChannel" />
<bean class="ServiceTransformer" id="serviceTransformer" />
<int:chain input-channel="serviceChannel" id="sendToServiceSqsChain" output-channel="chainChannel">
<int:transformer ref="serviceTransformer" method="transform" />
<int:header-filter header-names="config" />
<int-aws:sqs-outbound-channel-adapter sqs="amazonSQS" queue="some-queue" async-handler="sqsPublishCallbackHandler" success-channel="successChannel"/>
</int:chain>
<int:logging-channel-adapter log-full-message="true" channel="chainChannel" />
Here I can just use the same channel in both chain (outbound channel) and sqs-outbound (success-channel)
Unable to get it to work like below:
<int:channel id="successChannel" />
<bean class="ServiceTransformer" id="serviceTransformer" />
<int:chain input-channel="serviceChannel" id="sendToServiceSqsChain" >
<int:transformer ref="serviceTransformer" method="transform" />
<int:header-filter header-names="config" />
<int-aws:sqs-outbound-channel-adapter sqs="amazonSQS" queue="some-queue" async-handler="sqsPublishCallbackHandler" success-channel="successChannel"/>
</int:chain>
<int:logging-channel-adapter log-full-message="true" channel="successChannel" />
The <int-aws:sqs-outbound-channel-adapter> component is one-way, therefore there is no outputChannel option expose. However the target class is AbstractMessageProducingHandler. To avoid code duplication we reuse an existing outputChannel internally for that AsyncHandler.
In the XML parser we just remap one to another:
IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "success-channel", "outputChannel");
You probably don't see anything in logs because you need to adjust logging config respectively for the appropriate category and level.
UPDATE
According my testing this is definitely not possible to configure such a component with XML DSL within the <chain>. That <int-aws:sqs-outbound-channel-adapter> has to be presented outside of the <chain>.
Consider to more your configuration to Java DSL instead: https://docs.spring.io/spring-integration/docs/5.3.2.RELEASE/reference/html/dsl.html#java-dsl.

How to define an exception router in chain after aggregator

I using Spring integration to aggregate messages into one and then send by FTP out bound adapter, I want to move the aggregated messages in a specific folder when outbound FTP server is not available(org.springframework.messaging.MessageDeliveryException), other exceptions will log by console.
Here is my Configuration
<int:chain id="transformChain" input-channel="inboundChannel">
<int:header-enricher>
<int:header name="file_name" expression="payload.name"/>
<int:header name="correlationId" expression="${header.enricher.correlationId}"/>
<int:header name="sum" expression="${header.enricher.sum}"/>
</int:header-enricher>
<int:transformer ref="fileNameToContentTransformer"/>
<int:aggregator send-partial-result-on-expiry="true"
release-strategy-expression="#this.size() == new Integer([0].headers.sum)"
group-timeout="${aggregator.group-timeout}"
message-store="messageStore"
expire-groups-upon-completion="true"
correlation-strategy-expression="headers.correlationId"/>
<int:transformer ref="xmlToJsonTransformer"/>
<ftp:outbound-channel-adapter remote-directory="${ftp.out.remote.directory}"
session-factory="ftpOutClientSessionFactory" auto-create-directory="true"
remote-filename-generator="fileNameGenerator" charset="UTF-8"
temporary-file-suffix=".writing">
</ftp:outbound-channel-adapter>
<int:exception-type-router >
<int:mapping exception-type="org.springframework.messaging.MessageDeliveryException" channel="undeliveredChannel"/>
<int:mapping exception-type="java.lang.Exception" channel="myErrorChannel"/>
</int:exception-type-router>
</int:chain>
However I met such exception when try to start.
Caused by: java.lang.IllegalArgumentException: All handlers except for the last one in the chain must implement the MessageProducer interface. Object of class [org.springframework.integration.ftp.outbound.FtpMessageHandler] must be an instance of interface org.springframework.integration.core.MessageProducer
at org.springframework.util.Assert.instanceCheckFailed(Assert.java:389)
at org.springframework.util.Assert.isInstanceOf(Assert.java:327)
at org.springframework.integration.handler.MessageHandlerChain.configureChain(MessageHandlerChain.java:119)
at org.springframework.integration.handler.MessageHandlerChain.onInit(MessageHandlerChain.java:99)
at org.springframework.integration.context.IntegrationObjectSupport.afterPropertiesSet(IntegrationObjectSupport.java:176)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
Anyone can tell me how to achieve this?
thanks in advance.
You can't add a component to the chain after the ftp:outbound-channel-adapter because it produces no result.
See the retry-and-more sample for an example of how to handle exceptions by adding an ExpressionEvaluatingRequestHandlerAdvice to the outbound adapter.

How to filter Spring Integration flow using jdbc-outbound-channel-adapter?

I have a requirement wherein I have to FTP read XML files from a remote server and dump them in a local directory. After that I have to fire a SQL query against the database using values from the incoming payload and then - based on the outcome of the query - decide if I want to continue the flow or not.
<int-ftp:inbound-channel-adapter id="ftpInbound1"
channel="inboundFTPFileChannel" session-factory="ftpSessionFactory"
local-filter="compositeFilter" filename-pattern="*.xml"
preserve-timestamp="true" charset="UTF-8" remote-directory="${remote.request.cdr.circle.dir}"
remote-file-separator="/" local-directory="${local.request.dir}">
<int:poller fixed-rate="${ftp.file.poller.interval}"
time-unit="SECONDS" max-messages-per-poll="-1" />
</int-ftp:inbound-channel-adapter>
<int:filter input-channel="inboundFTPFileChannel"
output-channel="jdbcChannel" discard-channel="discardChannel"
expression="payload.isFile()" />
<int-jdbc:outbound-channel-adapter
channel="jdbcChannel" query="SELECT COUNT(1) FROM some_table WHERE some_col = some_value"
data-source="myDataSource" />
At this stage I want to continue the flow if the query returns a non-zero output. Else the flow for this message should end. Also, if the flow should continue, the output to next channel should be the same Spring Integration Message which came on 'jdbcChannel'. Please advice.
What I can definitely do is write a <int:filter> which references a bean returning true or false. But I am just trying to avoid having to write this Java code!
Save off the original payload in a header and restore it later...
<int:header-enricher ...>
<int:header name="savedPayload" expression="payload" />
</int:header-enricher>
<int:jdbc-outbound-gateway... />
<int:filter ... expression="payload > 0" />
<int:transformer ... expression="headers['savedPayload']" />
...
Notice you need to use a gateway, not a channel adapter (JDBC).
You can put all this in a <chain/> if you wish.

Spring integration:Header value router not getting invoked everytime

We are using header-value-router. Configuration:
<int:header-value-router input-channel="accountSummeryRequest"
header-name="word"
default-output-channel="accountSummeryRequest"
resolution-required="false">
<int:mapping value="xx" channel="accountSummeryRequest" />
<int:mapping value="yy" channel="newRequestChannel" />
</int:header-value-router>
<int:service-activator id="accountServiceActivator"
input-channel="accountSummeryRequest"
output-channel="accountSummeryResponse"
ref="serviceGatewayAdapter"
method="requestHandler"
send-timeout="60000"/>
<int:service-activator id="caRequestActivator"
input-channel="newRequestChannel"
output-channel="accountSummeryResponse"
ref="caServiceGatewayAdapter"
method="requestHandler"
send-timeout="60000"/>
now if i give word as yy,first time header-value-router enter code hereis getting called and exact service activator,in this case is caRequestActivator ,is called. But i try again with word=yy header-value-router is not getting called and request goes through accountServiceActivator. Alternate requests works correctly.
I don't know what's the problem here.
Your issue is around a round-robin dispatcher for accountSummeryRequest channel and its two subscribers: <int:header-value-router> and accountServiceActivator.
To fix it you should change the input-channel of that <service-activator> to some different channel. And, of course, don't fogtet to change the <header-value-router>
accordingly.

Generalize http:outbound-gateway reply-channel

Given a gateway that handles service calls to a ws. My goal is to supply the http:outbound-gateway's reply-channel using header-enricher since I'll be adding multiple methods to gateway and I would like to make use of only 1 http:outbound-gateway
I can currently receive the response up to groovy script (2) BUT it doesn't seem to want to return the results to the actual method that calls the service
Any help would be appreciated. Thanks!
<gateway id="registryService" service-interface="RegistryService">
<method name="create" request-channel="create-request-channel"
reply-channel="create-reply-channel" />
</gateway>
<chain input-channel="create-request-channel" output-channel="create-request-fulfillment-channel">
<transformer>
// groovy script that contains the method to be called in the ws (1)
</transformer>
<object-to-json-transformer/>
<header-enricher>
<reply-channel overwrite="true" ref="create-reply-fulfillment-channel" />
</header-enricher>
</chain>
<http:outbound-gateway request-channel="create-request-fulfillment-channel"
extract-request-payload="true"
expected-response-type="java.lang.String"
url="http://localhost:4567" http-method="POST" />
<chain input-channel="create-reply-fulfillment-channel"
output-channel="create-reply-channel">
<json-to-object-transformer type="JsonRpcResponse"/>
<transformer>
//groovy script to manipulate response (2)
</transformer>
</chain>
Do the following:
Each method of your gateway should enrich message with some unique 'routing' header value:
<gateway id="registryService" service-interface="RegistryService">
<method name="create" request-channel="http-request-channel"
reply-channel="registryService-create-responseChannel">
<header name="routingHeader" value="registryService-create" />
</method>
</gateway>
And then send message straight forward to outbound gateway:
<http:outbound-gateway request-channel="http-request-channel"
response-channel="http-response-channel"
extract-request-payload="true"
expected-response-type="java.lang.String"
url="http://localhost:4567" http-method="POST" />
Http outbound gateway sends request to the remote server and then forward response to http-response-channel. To this channel is attached header value router, which basis on the value of routing header, sends (routes) message to the appropriate channel:
<header-value-router input-channel="http-response-channel" header-name="routingHeader">
<mapping value="registryService-create" channel="registryService-create-responseChannel" />
<mapping value="someOtherService-otherMethod" channel="someOtherService-otherMethod-responseChannel" />
</header-value-router>
Of course you don't need to send it back directly to the gateway - you can add some additional processing between those components, and all the time you can route message basis on the header value.
It's simpler than hacks with groovy and I use it myself - proven that works ;)

Resources