Loop with apache camel - xpath

I am expecting multiple operation in one request. I need to to loop the xml to to do the following using Apache camel route.
1) get the total opertions in request xml and put in variable.
2) get total number of expression using xpath on xml and put in list
3) loop with (total number of operation ) times to evaluate the expression
First step would be list nodeList = /tractscation/operations
<loop>
<constant>nodeLIst.length</xpath>
compare and execute operation
</loop>
Above lines are just psuedo code, i want anybody help me with exact code using camel Xpath and loop. .
I am new to xpath and camel. we are using camelxpath spring DSL

if you want to loop through each node matching the xpath and process it individually, then use camel-splitter EIP...
<route>
<from uri="direct:a"/>
<split>
<xpath>/transaction/operations</xpath>
<to uri="direct:b"/>
</split>
</route>
otherwise, there is a camel-loop EIP that can be used to execute the same process a variable number of times...but the splitter is generally used for parsing/looping type of operations
from("direct:c").loop().xpath("/hello/#times").to("mock:result");

I hope it helps you =D
Inside route
<to uri="direct:WSCall" />
<split strategyRef="groupExchangeAggregationStrategy">
<xpath>//response/operation</xpath>
</split>
Velocity template
<tag>
#foreach( $exchangeItem in ${body} )
${exchangeItem.in.body}
#end
</tag>
Include
<beans>
<bean id="groupExchangeAggregationStrategy" class="org.apache.camel.processor.aggregate.GroupedExchangeAggregationStrategy" />
</beans>

Related

Parsing Error Response in Camel

New to Camel, and I'm trying to parse a response error xml. Within the camel-context I need to determine if a specific value exists in the error file, and handle it differently than other errors.
The other errors use a series of when statements:
<when>
<xpath>/abc:ErrorResponse/abc:Error/abc:Message/.</xpath>
<setHeader headerName="RESPONSE_STRING">
<xpath resultType="java.lang.String">/abc:ErrorResponse/abc:Error/abc:Message/.</xpath>
</setHeader>
<setHeader headerName="MY_DATA_FIELD"><constant>Error</constant></setHeader>
<to uri="def:doErrorStuff" pattern="InOnly"/>
</when>
<when>
<xpath>/ghi:ErrorResponse/ghi:Error/ghi:Message/.</xpath>
<setHeader headerName="RESPONSE_STRING">
<xpath resultType="java.lang.String">/ghi:ErrorResponse/ghi:Error/ghi:Message/.</xpath>
</setHeader>
<setHeader headerName="MY_DATA_FIELD"><constant>Error</constant></setHeader>
<to uri="def:doErrorStuff" pattern="InOnly"/>
</when>
My error XML file has an outer error element with child "Code" element. I need to parse the value of the code element
UPDATE: HERE IS THE XML I AM PARSING
<ErrorResponse xmlns="http://myhost/location1/">
<Error>
<Type>reserved</Type>
<Code>TEXT_I_NEED_TO_PARSE_IN_WHEN_STATEMENT</Code>
</Error>
<RequestId>some_id</RequestId>
</ErrorResponse>
I used a combination of xpath and 'simple' to make the check. Like this:
<when>
<xpath>/ghi:ErrorResponse/ghi:Error/ghi:Message/.</xpath>
<when>
<simple>${in.body.code} == 'StringIAmSearchingFor'</simple>
<!-- Do Stuff --!>
</when>
</when>
However, I am not getting the response I expect.
1. Is there something wrong with this approach or the syntax?
2. Is there a way to combine the double when layout so they are and-ed together. Otherwise, if I add my "when" statement just ahead of the existing two, the existing "ghi" when statement will never get executed (the xpath statements match).
You are using xpath on your input suggesting that it's XML, then simple (${in.body.code}) which in that case also would be XML. Simple is used to traverse java bodies and not other formats such as XML. Stick to XPATH all the way - your code above can easily be implemented in xpath. Another way, of course, would be to unmarshal the XML into java objects using xstream or jaxb, then you can use only simple/OGNL/groovy or whatnot.
Since I recommend you to solve this very case with xpath alone, you can of course use the xpath and operator to and several xpath expressions together. All logic and power in camel choice/when reside in the expression language you are using (be it simple or xpath), so if you want to mix expression languages, you have to build up sort of a decision tree. That could actually be something good if you are trying to implement very complex routing logic. For a single special case - it's, IMHO, just messy.

dynamic parameter to an endpoint

How to set a dynamic value as a parameter to an endpoint?
Payload :
<person>
<name>john</name>
<acno>9876543210</acno>
</person>
route :
<route>
<from uri="http://localhost:8092/test/"/>
<setProperty propertyName="acno">
<xpath resultType="java.lang.String">//person/acno</xpath>
</setProperty>
<setProperty propertyName="name">
<xpath resultType="java.lang.String">//person/name</xpath>
</setProperty>
<to uri="https://server/rest/services/test?accountno=${property.acno}&accountname=${property.name}"/>
</route>
The parameter value want to take from the payload by xpath.
Any help in resolving this issue or providing a workaround would be very appreciated.
You can't use dynamic content from headers inside endpoint URIs.
What you can do is to preconstruct the URI by using some xpath or whatever and put it into a header. Then you can use the Recipient List construct to use that dynamicly created URI.
You have some examples in the link
Update: see this link suggested by Claus Ibsen in comment

Re-marshalling protobuf within Camel route

I'm hoping someone can explain a bit more about how to configure Camel to marshal and unmarshal data. I have a route that calls a bean in order to determine a recipientList. This is based on the contents of the message (a protobuf).
The route config looks like:-
<route id="Splitter">
<from uri="activemq:notification.splitter" />
<unmarshal ref="notificationProto" />
<recipientList>
<method bean="NotificationSplitter" method="splitNotification" />
</recipientList>
</route>
The bean works fine, but the downstream routes complain that:-
org.apache.camel.RuntimeCamelException: java.lang.RuntimeException: Unable to find proto buffer class
The downstream routes have exactly the same protobuf dataFormat config as the route above. If I route directly to the downstream queues (i.e. bypass the bean and hardcode the "to" queues), which means I can also skip the unmarshalling step, it works fine.
I guess that I need to re-marshal the data before Camel puts the messages onto the destination queues but I don't know how to configure this within the XML. I've tried simply adding...
<marshal ref="notificationProto" />
...after the recipientList has been determined but it doesn't do it (I assume because Camel has already dispatched the messages by then).
An alternative could be to do the unmarshalling from within the bean as then the data on the exchange will presumably remain unaltered. I'm not quite sure how to do this. Would it work?
Thanks for any tips.
J.
Yeah the data formats are not an endpoint that's easy to send a message to, as otherwise you can use the Routing Slip EIP pattern instead, and send the message to the data format first, and then the destination. http://camel.apache.org/routing-slip.html
Though you could have a little route
<route>
<from uri="direct:marshalMe"/>
<marshal ref="notificationProto" />
</route>
And then use the routing slip, to set to "direct:marshalMe,whereYouWannaGoNext".
An alternative is to use an interceptor, and intercept sending to endpoints (you can filter by wildcards, or reg exps), and then do the marshal first. http://camel.apache.org/intercept
See that link for more details.

Apache Camel: how store variable for later use

while 'playing around' with Camel using Spring DSL, I came across the following problem. Suppose the expected message flow looks like this:
client sends HTTP POST message with XML body to CAMEL
CAMEL proxies HTTP POST message towards server, with the URI slightly adapted using
info from the received XML body (eg: use XPATH to filter out a certain parameter)
after CAMEL has received a reply, CAMEL sends HTTP PUT message towards server, using parameters out of the XML body received in 1
So something like:
<route>
<from uri="...">
<to uri="...">
<to uri="...">
</route>
Question: how do I store the parameters in Spring DSL in step 1, so that I can use them later in step 3 ?
So, I would like to extract XML parameters out of the XML body of the message received in step 1 and put them into variables, which I then later on can use to compose the message to be sent in step 3.
For extracting the parameters, I was thinking of using XPATH. That looks ok, but I just don't see how to put the output of the XPATH into a variable and then use that variable later on ... (syntax ??)
Note: as you can see, my development knowledge is rather limited ... sorry for that. But it would still be great if someone could help with this :).
you can set store data in the Exchange properties or message headers like this...
.setHeader("ID", XPathBuilder.xpath("/order/#id", String.class))
.setProperty("ID", XPathBuilder.xpath("/order/#id", String.class))
and then retrieve them in a bean/processor from the Exchange like this...
String propId = (String) exchange.getProperty("ID");
String headerId = (String) exchange.getIn().getHeader("ID"); }
I leave you some examples:
<setHeader headerName="token">
<constant>someValue</constant>
</setHeader>
<setHeader headerName="userName">
<simple>${properties:userName}</simple> //from config
</setHeader>
<setProperty propertyName="bodyBkp">
<simple>${in.body}</simple>
</setProperty>
<setProperty propertyName="orderNumber">
<xpath resultType="String">//item[1]/orderNumber/text()</xpath>
</setProperty>
Getter
${exchangeProperty[orderNumber]}
${in.headers.token}
Documentation
Check the simple expression language:
http://camel.apache.org/simple.html
Sometimes looking at the test cases of Camel can be helpful as well, in particular for Spring DSL:
setProperty with Spring DSL
setHeader using XPATH with Spring DSL
simple expression language test

Apache Camel: how extract parameter from incoming HTTP message (with XML body)

I am trying to use CAMEL as HTTP proxy and I would like to extract a parameter from an incoming HTTP message with a XML body. This parameter I would then like to add in the header of a HTTP POST message towards another endpoint (another server).
Example: the XML body contains a parameter called "subscriptionId". The value of this field "subscriptionId" is then to be used in the uri of the outgoing HTTP POST message.
So, if subscriptionId=1234567, I want the uri in the HTTP POST message to be like:
POST /webapp/createnewsubscription?subscriptionId=1234567
I am using Spring DSL to create my Camel routes.
Anyone an idea how to do this ?
Thanks,
Jan
I presume you want to POST to first URL with XML as payload.
First you would need to use XPath component to get value for your XML tag and then setBody to pass parameter to proxied request (optionally you could switch from POST to GET).
Something like this should work:
<route>
<from uri="jetty:http://127.0.0.1:8080/myapp"/>
<setHeader headerName="subscriptionId">
<xpath resultType="java.lang.String">//subscriptionId/text()</xpath>
</setHeader>
<!-- if you need to convert from POST to GET
<setHeader headerName="CamelHttpMethod">
<constant>GET</constant>
</setHeader>
-->
<setBody>
<simple>subscriptionId=${in.headers.subscriptionId}</simple>
</setBody>
<to uri="jetty:http://127.0.0.1:8090/myapp?bridgeEndpoint=true&throwExceptionOnFailure=false"/>
</route>
You should be able to test it from command line say with wget:
$ cat 1.txt
<a>
<subscriptionId>123</subscriptionId>
</a>
$ wget --post-file=1.txt --header="Content-Type:text/xml" http://127.0.0.1:8080/myapp
You could use second route to test responses like this:
<route>
<from uri="jetty:http://127.0.0.1:8090/myapp"/>
<to uri="log:mylog?level=INFO"/>
<setBody>
<simple>OK: ${in.headers.CamelHttpMethod}: ${in.headers.subscriptionId}</simple>
</setBody>
</route>
And if you set camelContext to 'trace' you should see lots of info in your log of what's going on on every step of the processing:
<camel:camelContext id="camel" trace="true" xmlns="http://camel.apache.org/schema/spring">

Resources