Trouble filtering in Camel - spring

I am attempting to filter out the null bodies from my route. The route polls from the function every half second or so. So, I get this error in my console also every half-second.
Here is the stack trace:
Message History
---------------------------------------------------------------------------------------------------------------------------------------
RouteId ProcessorId Processor Elapsed (ms)
[route1 ] [route1 ] [browserBean ] [ 0]
[route1 ] [filter1 ] [filter[simple{(${body} == null)}] ] [ 0]
Exchange
--------------------------------------------------------------------------------------- ------------------------------------------------
Exchange[
Id ID-CO183LTCS06-54352-1403798372606-0-1058
ExchangePattern InOnly
Headers {breadcrumbId=ID-CO183LTCS06-54352-1403798372606-0-1057, CamelRedelivered=false, CamelRedeliveryCounter=0}
BodyType null
Body [Body is null]
]
Stacktrace
---------------------------------------------------------------------------------------------------------------------------------------
java.lang.NullPointerException: null
at com.hello.integration.GreetingController.greeting(GreetingController.java:15)
at sun.reflect.GeneratedMethodAccessor22.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.camel.component.bean.MethodInfo.invoke(MethodInfo.java:407)
at org.apache.camel.component.bean.MethodInfo$1.doProceed(MethodInfo.java:278)
at org.apache.camel.component.bean.MethodInfo$1.proceed(MethodInfo.java:251)
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:166)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:105)
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:67)
at org.apache.camel.impl.ProcessorPollingConsumer.receive(ProcessorPollingConsumer.java:58)
at org.apache.camel.impl.ProcessorPollingConsumer.receiveNoWait(ProcessorPollingConsumer.java: 66)
at org.apache.camel.impl.DefaultScheduledPollConsumer.poll(DefaultScheduledPollConsumer.java:48)
at org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:187)
at org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:114)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Any Ideas? I feel like it's simple but I've been looking all over the web for solutions and can't find anything that solves my problem.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:camel="http://camel.apache.org/schema/spring"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/osgi
http://camel.apache.org/schema/osgi/camel-osgi.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://camel.apache.org/schema/spring
http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="browserBean"/>
<filter>
<simple>${body} == null</simple>
<stop/>
</filter>
<to uri="jms:queue:testQSource"/>
<to uri="myBean"/>
<log message="Routing message from testQSource to testQDestination queue with data ${body}"/>
<to uri="jms:queue:testQDestination"/>
<to uri="finalBean"/>
<log message="message: ${body}"/>
</route>
</camelContext>
<camel:camelContext id="camel-client">
<camel:template id="camelTemplate" />
</camel:camelContext>
<bean id="jms" class="org.apache.activemq.camel.component.ActiveMQComponent">
<property name="brokerURL" value="tcp://localhost:61616" />
</bean>\
<bean id="myBean" class="com.example.integration.modifier"/>
<bean id="finalBean" class="com.example.integration.ActionApp"/>
<bean id="browserBean" class="com.hello.integration.GreetingController"/>
</beans>
EDIT: The null body is coming from the following function:
package com.hello.integration;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
#Controller
public class GreetingController {
#MessageMapping("/hello")
#SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
//Thread.sleep(3000); // simulated delay
return new Greeting("Hello, " + message.getName() + "!");
}
}
Even though I attempt filter out the null bodies, I am still getting the error. Am I filtering them out too late?

You cannot put the filter inside of from tag. The below route should work :)
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="browserBean"/>
<filter>
<simple>${body} == null</simple>
<stop/>
</filter>
<to uri="jms:queue:testQSource"/>
<to uri="myBean"/>
<log message="Routing message from testQSource to testQDestination queue with data ${body}"/>
<to uri="jms:queue:testQDestination"/>
<to uri="finalBean"/>
<log message="message: ${body}"/>
</route>

You can also use a choice clause, as another way to do it. Here is an example:
<route>
<from uri="direct:routePublishedResponse"/>
<bean ref="caseHearingHandler"/>
<choice>
<when>
<simple>${body} != null</simple>
<to uri="direct:resultSubRoute">
</when>
<otherwise>
<log message="skipping due to NULL body" loggingLevel="DEBUG" />
</otherwise>
</choice>
</route>

Related

camel sql-stored ends in "java.sql.SQLException: Non supported SQL92 token at position" with Oracle datasource

When I run the following simple route with a stored-procdure, it results in an exception: "java.sql.SQLException: Non supported SQL92 token at position"
The same route with embedded Derby datasources works as expected.
Question
Any ideas? Is something wrong with my "implementation" or is it a problem of the underlying jar files?
Stack:
camel 2.23.2
ojdbc7.jar
Spring XML
Route:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<!-- In Memory Database
<jdbc:embedded-database id="myDataSource" type="DERBY">
<jdbc:script location="classpath:/sql/createAndPopulateDatabase.sql"/>
</jdbc:embedded-database>
-->
<bean id="oracleDataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#..."/>
<property name="username" value="xx"/>
<property name="password" value="yy"/>
</bean>
<bean id="sql-stored" class="org.apache.camel.component.sql.SqlComponent">
<property name="dataSource" ref="oracleDataSource"/>
</bean>
<camelContext id="camel"
xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:start"/>
<setHeader headerName="in1">
<constant>1</constant>
</setHeader>
<setHeader headerName="in2">
<constant>1</constant>
</setHeader>
<to uri="sql-stored:INOUTDEMO(INTEGER ${headers.in1},INOUT INTEGER ${headers.in2} out1,OUT INTEGER out2)"/>
<log message="Result: ${body}" loggingLevel="INFO" />
</route>
</camelContext>
</beans>
Stored-Procedure:
I know that the procedure would not work in an oracle db, but the exception is thrown "long" before the involved classes / methods would recognize, that the procedure doesn't work / even exist.
CREATE PROCEDURE INOUTDEMO(IN1 INTEGER, INOUT IN2 INTEGER, OUT OUT1 INTEGER)
PARAMETER STYLE JAVA
LANGUAGE JAVA
EXTERNAL NAME
'org.apache.camel.component.sql.stored.TestStoredProcedure.inoutdemo';
Stacktrace:
Caused by: org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException; SQL state [99999]; error code [17034]; Nicht unterstütztes SQL92-Token in Position: 20; nested exception is java.sql.SQLException: Nicht unterstütztes SQL92-Token in Position: 20
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:89)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1414)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:632)
at org.apache.camel.component.sql.SqlProducer.process(SqlProducer.java:116)
at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:148)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:548)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:138)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:101)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201)
at org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:76)
at org.apache.camel.processor.SharedCamelInternalProcessor.process(SharedCamelInternalProcessor.java:186)
at org.apache.camel.processor.SharedCamelInternalProcessor.process(SharedCamelInternalProcessor.java:86)
at org.apache.camel.impl.ProducerCache$1.doInProducer(ProducerCache.java:541)
at org.apache.camel.impl.ProducerCache$1.doInProducer(ProducerCache.java:506)
at org.apache.camel.impl.ProducerCache.doInProducer(ProducerCache.java:369)
at org.apache.camel.impl.ProducerCache.sendExchange(ProducerCache.java:506)
at org.apache.camel.impl.ProducerCache.send(ProducerCache.java:229)
at org.apache.camel.impl.DefaultProducerTemplate.send(DefaultProducerTemplate.java:144)
at org.apache.camel.impl.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:161)
... 30 more
Caused by: java.sql.SQLException: Nicht unterstütztes SQL92-Token in Position: 20
at oracle.jdbc.driver.OracleSql.handleODBC(OracleSql.java:1306)
at oracle.jdbc.driver.OracleSql.parse(OracleSql.java:1192)
at oracle.jdbc.driver.OracleSql.getSql(OracleSql.java:326)
at oracle.jdbc.driver.OracleParameterMetaData.getParameterMetaData(OracleParameterMetaData.java:46)
at oracle.jdbc.driver.OraclePreparedStatement.getParameterMetaData(OraclePreparedStatement.java:11621)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.getParameterMetaData(OraclePreparedStatementWrapper.java:1552)
at org.apache.commons.dbcp2.DelegatingPreparedStatement.getParameterMetaData(DelegatingPreparedStatement.java:162)
at org.apache.commons.dbcp2.DelegatingPreparedStatement.getParameterMetaData(DelegatingPreparedStatement.java:162)
at org.apache.camel.component.sql.SqlProducer$2.doInPreparedStatement(SqlProducer.java:120)
at org.apache.camel.component.sql.SqlProducer$2.doInPreparedStatement(SqlProducer.java:1)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:617)
... 48 more
For oracle procedure/function parameters it should be variable name followed by in/out followed by data type.
E.g "out1 out integer"
The only way I made it "work" was like that:
<to uri="sql-stored: CALL HELLOWORLD(:#testValue,:#result)"/-->
With that - no IN, INOUT, OUT or type argument and "CALL" - it is at least possible to execute the stored procedure in the oracle db.
Unfortunately, I am still struggeling to map the return value op the stored procedure back to camel header oder body variable.

apache-camel apache-cxf IllegalStateException: Could not register object under bean name 'cxf': there is already object bound

Camel Version: 2.12.2,
CXF Version: 2.7,
Apache Tomcat: 7
I have the following camel-cxf.xml :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:s0="http://www.huawei.com/bme/cbsinterface/cbs/businessmgr"
xmlns:s1="http://www.huawei.com/bme/cbsinterface/cbs/accountmgr"
xmlns:cxf="http://camel.apache.org/schema/cxf"
xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd
http://camel.apache.org/schema/cxf http://camel.apache.org/schema/cxf/camel-cxf.xsd">
<bean id="loggingInInterceptor" class="org.apache.cxf.interceptor.LoggingInInterceptor" />
<bean id="loggingOutInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
<cxf:cxfEndpoint id="oneEndpoint"
address="${endpoint.address}"
serviceName="s1:WebService"
serviceClass="WebserviceClass"
endpointName="s1:WebSericePort_http"
wsdlURL="classpath:wsdl/WebService.wsdl">
<cxf:inInterceptors>
<ref bean="loggingInInterceptor" />
<ref bean="setSoapVersionInterceptor"/>
</cxf:inInterceptors>
<cxf:inFaultInterceptors>
<ref bean="loggingInInterceptor" />
<ref bean="setSoapVersionInterceptor"/>
</cxf:inFaultInterceptors>
<cxf:outInterceptors>
<ref bean="loggingOutInterceptor" />
</cxf:outInterceptors>
<cxf:outFaultInterceptors>
<ref bean="loggingOutInterceptor" />
</cxf:outFaultInterceptors>
</cxf:cxfEndpoint>
<http-conf:conduit name="*.http-conduit">
<http-conf:client
Connection="Keep-Alive"
ConnectionTimeout="60000"
ReceiveTimeout="90000"/>
</http-conf:conduit>
</beans>
In my camel-context I have two processors that use the cxf endpoint to invoke two different operations. To do that I use a producerTemplate which uses "cxf:bean:oneEndpoint" as a uri.
The project is a web application deployed in Tomcat 7.
The processors consume from two different queues. After deployment both queues are propagated with a message. The problem is that one of the processors will throw an exception upon invoking the send method on the producer template. The other will work fine. The exception is:
org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint:
cxf://bean:oneEndpoint due to: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'oneEndpoint': Initialization of bean failed;
nested exception is java.lang.IllegalStateException: Could not register object [org.apache.cxf.bus.spring.SpringBus#4b0af74c] under bean name 'cxf':
there is already object [org.apache.cxf.bus.spring.SpringBus#24c0fe59] bound
Full stacktrace can be found here: http://pastebin.com/cDsQZ9r3
The second time the queues receive a message at the same time, everything works fine.
Any ideas?
PS. My web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/META-INF/spring/*.xml</param-value>
</context-param>
</web-app>
Routes & Processors:
<route id="route1" errorHandlerRef="eh1">
<from uri="{{queue1}}" />
<setHeader headerName="operationName">
<constant>Operation_1</constant>
</setHeader>
<process ref="FirstProcessor" />
<choice>
<when>
<simple>${in.headers.STATUS} == 'OK'</simple>
<inOnly uri="{{result_queue}}" />
</when>
<otherwise>
<inOnly uri="{{nok_result_queue}}" />
</otherwise>
</choice>
</route>
<route id="route2" errorHandlerRef="eh2">
<from uri="{{queue2}}" />
<setHeader headerName="operationName">
<constant>Operation_2</constant>
</setHeader>
<process ref="SecondProcessor" />
<choice>
<when>
<simple>${in.headers.STATUS} == 'OK'</simple>
<inOnly uri="{{result_queue}}" />
</when>
<otherwise>
<inOnly uri="{{nok_result_queue}}" />
</otherwise>
</choice>
</route>
<property name="producerTemplate" ref="firstProcessorTemplate" />
<property name="producerTemplateUri"
value="cxf:bean:oneEndpoint?headerFilterStrategy=#headerFilterStrategy" />
<property name="producerTemplate" ref="secondProcessorTemplate" />
<property name="producerTemplateUri"
value="cxf:bean:oneEndpoint?headerFilterStrategy=#headerFilterStrategy" />
The problem is that both queues are getting a message at the same time so both of them are trying to initialise the SpringBus at the same time.
The problem is that in BusWiringBeanFactoryPostProcessor it this code:
if (!context.containsBean(name) && (create || Bus.DEFAULT_BUS_ID.equals(name))) {
SpringBus b = new SpringBus();
ConfigurableApplicationContext cctx = (ConfigurableApplicationContext)context;
cctx.getBeanFactory().registerSingleton(name, b);
b.setApplicationContext(context);
}
So when two beans both try and initialise the SpringBus in two different threads, they can both enter the if statement at the same time leading to the exception.
The solution is to define a SpringBus in the application context so neither bean will try create a new SpringBus as one already exists.
Please share the routes definition which consumes messages from two different queues. Also you can look for option of using multicasting to have parallel processing in consuming messages from both queues and proceed with further opertion.<route>
<from uri="cxf:bean:oneEndpoint"></from>
<recipientList>
<simple>direct:${header.operationName}</simple>
<log message="Got ${header.operationName}" />
</recipientList>
</route>
Your routes (route1 and route) can be renamed as same as webservice operation name. Our code is also something similar to yours. We haven't faced problem with this approach.

Using camel to route from webapp

I am trying to use camel to route a message from my web app to a queue and I am using a bean reference to grab the message from a function that is run whenever an input is given to the browser. However, camel creates a Null exception when it continues to poll because there isn't always an input every half second. How can I make the camel only pick up the message when there is one to pick up? Browserbean is the function that returns the message from the browser.
Here is my camel route:
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="browserBean"/>
<to uri="jms:queue:testQSource"/>
<to uri="myBean"/>
<log message="Routing message from testQSource to testQDestination queue with data ${body}"/>
<to uri="jms:queue:testQDestination"/>
<to uri="finalBean"/>
<log message="message: ${body}"/>
</route>
</camelContext>
<camel:camelContext id="camel-client">
<camel:template id="camelTemplate" />
</camel:camelContext>
<bean id="jms" class="org.apache.activemq.camel.component.ActiveMQComponent">
<property name="brokerURL" value="tcp://localhost:61616" />
</bean>
<bean id="myBean" class="com.example.integration.modifier"/>
<bean id="finalBean" class="com.example.integration.ActionApp"/>
<bean id="browserBean" class="com.hello.integration.GreetingController"/>
</beans>
Here is the stack trace I get every second or so:
Message History
--------------------------------------------------------------------------------------- ------------------------------------------------
RouteId ProcessorId Processor Elapsed (ms)
[route1 ] [route1 ] [browserBean ] [ 0]
[route1 ] [to1 ] [jms:queue:testQSource ] [ 0]
Exchange
---------------------------------------------------------------------------------------------------------------------------------------
Exchange[
Id ID-CO183LTCS06-59664-1403735006145-0-16
ExchangePattern InOnly
Headers {breadcrumbId=ID-CO183LTCS06-59664-1403735006145-0-15, CamelRedelivered=false, CamelRedeliveryCounter=0}
BodyType null
Body [Body is null]
]
Stacktrace
--------------------------------------------------------------------------------------- ------------------------------------------------
java.lang.NullPointerException: null
at com.hello.integration.GreetingController.greeting(GreetingController.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.camel.component.bean.MethodInfo.invoke(MethodInfo.java:407)
at org.apache.camel.component.bean.MethodInfo$1.doProceed(MethodInfo.java:278)
at org.apache.camel.component.bean.MethodInfo$1.proceed(MethodInfo.java:251)
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:166)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:105)
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:67)
at org.apache.camel.impl.ProcessorPollingConsumer.receive(ProcessorPollingConsumer.java:58)
at org.apache.camel.impl.ProcessorPollingConsumer.receiveNoWait(ProcessorPollingConsumer.java: 66)
at org.apache.camel.impl.DefaultScheduledPollConsumer.poll(DefaultScheduledPollConsumer.java:4 8)
at org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:187)
at org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:114)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

Message splitting in Camel

I am trying to write a camel route which would send different elements of a list to different queues.
The message body would be a list with 2 xml's. For example:
<Cat>
<Name>Cat1</Name>
</Cat>,
<Dog>
<Name>Dog1</Name>
</Dog>
Now, I need to send the 'Cat' part of the message i.e. Cat1 part to queue1 and the 'Dog' part of xml i.e. Dog1 to a different queue?
This is the route that I have, but is not working:
<route>
<from uri="jms:queue:InQueue" />
<choice>
<when>
<simple>${in.body} regex 'Cat'</simple>
<to uri="jms:queue:CatQueue" />
</when>
<when>
<simple>${in.body} regex 'Dog'</simple>
<to uri="jms:queue:DogQueue" />
</when>
</choice>
</route>
Any ideas on what am i doing wrong here?
First, you have to split the list using the , token. Second, you have to parse the XML parts using XPath expressions and send the messages to the appropriate JMS queues:
<route>
<from uri="jms:queue:InQueue" />
<split>
<tokenize token=","/>
<log message="Working on split: ${body}" />
<choice>
<when>
<xpath>/Cat</xpath>
<to uri="jms:queue:CatQueue" />
</when>
<when>
<xpath>/Dog</xpath>
<to uri="jms:queue:DogQueue" />
</when>
</choice>
</split>
</route>

Having trouble with content based routing in Camel with a CXFRS endpoint and xPath

I am trying to create a route that is determined by the content in the REST payload using xPath. I have been successful in using routing based on the message header:
<when>
<simple>${headers.operationName} == 'createContainerOutput'</simple>
<bean ref="containerOutputProcessor"/>
</when>
which properly invokes the containerOutputProcessor...
but for this xPath route:
<when>
<xpath>/*[local-name()='order-request']/#type='TrayOutput'</xpath>
<bean ref="containerOutputProcessor"/>
</when>
I get the the exception:
org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: org.apache.cxf.message.MessageContentsList to the required type: org.w3c.dom.Document with value [com.mmi.ws.ContainerOutputOrderRequest#6290dc]
for this payload
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<order-request type="TrayOutput">
<parameter name="orderName">Example Tray Output Order</parameter>
<parameter name="enableScan">true</parameter>
<parameter name="autoStart">false</parameter>
<parameter name="priority">3</parameter>
<item barcode="23990001"/>
<item barcode="23990002"/>
</order-request>
Is this type of routing a good idea? Is there a better way to route based on what type of order-request is being submitted?
Thanks for any help/guidance you may have for me!
Here is the complete context
<?xml version='1.0' encoding='UTF-8'?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:cxf="http://camel.apache.org/schema/cxf"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
http://camel.apache.org/schema/cxf http://camel.apache.org/schema/cxf/camel-cxf.xsd">
<!-- enable Spring #Component scan -->
<context:component-scan base-package="com.mmi.ws"/>
<!-- web service beans -->
<bean id="containerOutputWS" class="com.mmi.ws.service.impl.ContainerOutputWSImpl" />
<bean id="containerTypesWS" class="com.mmi.ws.service.impl.ContainerTypesWSImpl" />
<!-- processor beans -->
<bean id="containerOutputProcessor" class="com.mmi.ws.service.ContainerOutputProcessor" />
<bean id="containerTypesProcessor" class="com.mmi.ws.service.ContainerTypesProcessor" />
<bean id="unsupportedPathProcessor" class="com.mmi.ws.service.UnsupportedPathProcessor" />
<!-- Define the real JAXRS back end service -->
<jaxrs:server id="restService"
address="http://localhost:9998/sc"
staticSubresourceResolution="true">
<jaxrs:serviceBeans>
<ref bean="containerOutputWS"/>
<ref bean="containerTypesWS"/>
</jaxrs:serviceBeans>
</jaxrs:server>
<!-- define the restful server and client endpoints -->
<cxf:rsServer id="rsServer" address="http://localhost:9999/sc" loggingFeatureEnabled="true" loggingSizeLimit="20">
<cxf:serviceBeans >
<ref bean="containerOutputWS"/>
<ref bean="containerTypesWS"/>
</cxf:serviceBeans>
</cxf:rsServer>
<cxf:rsServer id="rsClient" address="http://localhost:9998/sc" loggingFeatureEnabled="true" loggingSizeLimit="20">
<cxf:serviceBeans >
<ref bean="containerOutputWS"/>
<ref bean="containerTypesWS"/>
</cxf:serviceBeans>
</cxf:rsServer>
<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
<!--
any classes in the below 'packageScan'packages that extends RouteBuilder
will be added as a camel route. At least one route is required to start the cxf web service
-->
<packageScan>
<package>com.mmi.ws</package>
</packageScan>
<dataFormats>
<xstream id="xstream-utf8" encoding="UTF-8"/>
<xstream id="xstream-default"/>
</dataFormats>
<!-- route starts from the cxf webservice -->
<route streamCache="true">
<from uri="cxfrs://bean://rsServer"/>
<log message="XML payload to send to REST WS:${body}" />
<setHeader headerName="CamelCxfRsUsingHttpAPI"><constant>True</constant> </setHeader>
<choice>
<when>
<simple>${headers.operationName} == 'getContainers'</simple>
<bean ref="containerTypesProcessor"/>
</when>
<when>
<xpath>/*[local-name()='order-request']/#type='TrayOutput'</xpath>
<bean ref="containerOutputProcessor"/>
</when>
<otherwise>
<bean ref="unsupportedPathProcessor"/>
<to uri="cxfrs://bean://rsClient"/>
</otherwise>
</choice>
</route>
</camelContext>
</beans>
and the web service class:
#Path("/container/output/")
public class ContainerOutputWSImpl
{
#POST
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
#Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public ContainerOutputView createContainerOutput(ContainerOutputOrderRequest containerOutput) {
// TODO Auto-generated method stub
return new ContainerOutputView();
}
}
and finally, the xml payload and error stack:
Address: http://localhost:9999/sc/container/output/
Encoding: ISO-8859-1
Http-Method: POST
Content-Type: application/xml
Headers: {accept-encoding=[gzip,deflate], connection=[keep-alive], Content-Length=[384], content-type=[application/xml], Host=[localhost:9999], User-Agent=[Apache-HttpClient/4.1.1 (java 1.5)]}
Payload: <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<order-request type="TrayOutput">
<parameter name="orderName">Example Tray Output Order</parameter>
<parameter name="enableScan">true</parameter>
<parameter name="autoStart">false</parameter>
<parameter name="priority">3</parameter>
<item barcode="23990001"/>
<item barcode="23990002"/>
</order-request>
--------------------------------------
[ERROR] 2013-02-07 17:53:37.059 [qtp27633254-28: DefaultErrorHandler] Failed delivery for (MessageId: ID-PWY-EHANSEN-3070-1360288389778-0-2 on ExchangeId: ID-PWY-EHANSEN-3070-1360288389778-0-1). Exhausted after delivery attempt: 1 caught: org.apache.camel.RuntimeCamelException: org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: org.apache.cxf.message.MessageContentsList to the required type: org.w3c.dom.Document with value [com.mmi.ws.ContainerOutputOrderRequest#9fbbe5]
org.apache.camel.RuntimeCamelException: org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: org.apache.cxf.message.MessageContentsList to the required type: org.w3c.dom.Document with value [com.mmi.ws.ContainerOutputOrderRequest#9fbbe5]
at org.apache.camel.util.ObjectHelper.wrapRuntimeCamelException(ObjectHelper.java:1271)
at org.apache.camel.builder.xml.XPathBuilder.getDocument(XPathBuilder.java:1027)
at org.apache.camel.builder.xml.XPathBuilder.doInEvaluateAs(XPathBuilder.java:850)
at org.apache.camel.builder.xml.XPathBuilder.evaluateAs(XPathBuilder.java:757)
at org.apache.camel.builder.xml.XPathBuilder.matches(XPathBuilder.java:145)
at org.apache.camel.processor.ChoiceProcessor.process(ChoiceProcessor.java:66)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)
at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:73)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)
at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.processor.interceptor.TraceInterceptor.process(TraceInterceptor.java:91)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)
at org.apache.camel.processor.RedeliveryErrorHandler.processErrorHandler(RedeliveryErrorHandler.java:334)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:220)
at org.apache.camel.processor.interceptor.StreamCachingInterceptor.process(StreamCachingInterceptor.java:52)
at org.apache.camel.processor.RouteContextProcessor.processNext(RouteContextProcessor.java:45)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.processor.interceptor.DefaultChannel.process(DefaultChannel.java:303)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:117)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:80)
at org.apache.camel.processor.RouteContextProcessor.processNext(RouteContextProcessor.java:45)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.processor.UnitOfWorkProcessor.processAsync(UnitOfWorkProcessor.java:150)
at org.apache.camel.processor.UnitOfWorkProcessor.process(UnitOfWorkProcessor.java:117)
at org.apache.camel.processor.RouteInflightRepositoryProcessor.processNext(RouteInflightRepositoryProcessor.java:48)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)
at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:73)
at org.apache.camel.component.cxf.jaxrs.CxfRsInvoker.asyncInvoke(CxfRsInvoker.java:87)
at org.apache.camel.component.cxf.jaxrs.CxfRsInvoker.performInvocation(CxfRsInvoker.java:57)
at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:201)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:102)
at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:58)
at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:94)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:271)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http_jetty.JettyHTTPDestination.serviceRequest(JettyHTTPDestination.java:355)
at org.apache.cxf.transport.http_jetty.JettyHTTPDestination.doService(JettyHTTPDestination.java:319)
at org.apache.cxf.transport.http_jetty.JettyHTTPHandler.handle(JettyHTTPHandler.java:72)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1074)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1010)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:255)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:365)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:485)
at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:937)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:998)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:856)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:240)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:627)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:51)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
at java.lang.Thread.run(Thread.java:722)
Before the content based router, you can convert the message to take out the payload from the internal CXF list. There is a trick with the simple language to grab the first index from the list:
<transform>
<simple>${body[0]}</simple>
</transform>
<choice>
...
Do you have camel-jaxb on the classpath. If so it may work out of the box without that trick. Not sure though, as CXF is a bit special. Also dependes on what version of Camel / CXF you use. You should really mention this when you ask questions!

Resources