Apache Camel NotifyBuilder not working as expected - apache-camel

I am trying to test an error handling route. The NotificationBuilder does not work as expected (it always returns false).
Created a main route and a test route to test the main route. I used Spring Boot - all other tests work fine, so there is no problem with the setup I guess.
errorHandler(deadLetterChannel("seda:errorQueue").maximumRedeliveries(5).redeliveryDelay(1000));
from("file://{{inputFolder}}?delay=10s&noop=true")
.routeId("InputFolderToTestSedaRoute")
.setHeader("myHeader", constant("MY_HEADER_CONSTANT_VALUE"))
.to("seda://testSeda")
.log(LoggingLevel.DEBUG, "**** Input File Pushed To Output Folder *****");
There is an error route too.
from("seda:errorQueue")
.routeId("ErrorHandlingRoute")
.log("***** error body: ${body} *****")
.log("***** Exception Caught: ${exception} *****");
I then used adviceWith() to throw an Exception in the main route.
Then created the NotifyBuilder.
NotifyBuilder errorRouteNotifier = new NotifyBuilder(camelContext)
// .wereSentTo("seda:errorQueue")
.fromRoute("ErrorHandlingRoute*")
.whenReceived(1)
.create();
Then I sent message using ProducerTemplate. But when I test the match condition, it always fails.
boolean done = errorRouteNotifier.matches(5, TimeUnit.SECONDS);
assertTrue("Should have thrown Exception and caught at errorQueue", done);
But the message is routed to the ErrorHandlingRoute as I can see the messages (body and exception) I asked to print there.
Please let me know what is the issue here. Thanks in advance.

Related

Camel appears to ignore onException instruction - what am I doing wrong?

I have a Camel (2.21.2) route that gets an XML file via FTP and then splits it before processing further, somewhat like...
from("direct-vm:start")
.split()
.xtokenize("*/row", 'w', ns)
.streaming()
...
If an empty file is passed, I am getting a com.ctc.wstx.exc.WstxEOFException raised by the xtokenize step I presume, which seems perfectly reasonable.
However, when I try to put in an onException clause, it doesn't seem to be catching the exception.
I have:
onException(com.ctc.wstx.exc.WstxEOFException.class)
.handled(true)
.log(org.apache.camel.LoggingLevel.INFO,
"myLogger",
"File ${header.CamelFileName} is empty or invalid XML");
and yet the exception is resulting in the route failing with the exception, and my handler log message is never produced.
However, if I change the onException clause to java.lang.Exception.class, it does handle the exception.
I don't want this to handle any exception, just the one caused by an empty or incomplete file.
What I am doing wrong here? How do I get onException to handle only the exception I am interested in?
Thanks for looking!

Having access to entire soap:body when service call returns soap:fault

I'm building a route that sends a SOAP request to a webservice. For achieving that, I wrote this code.
.doTry()
.inOut(getEndpointDocumentWS())
.log("Response WHEN OKAY: ${body}")
.process(Document_WS_REPLY_PROCESSOR)
.endDoTry()
.doCatch(Exception.class)
.log(LoggingLevel.INFO, "SOAP REPLY WITH FAULTMESSAGE")
.log("Response ON ERROR FAULT: ${body}")
.process(Document_WS_REPLY_ERROR_PROCESSOR)
.end();
Everything goes as planned when the service response is "okay". Otherwise, when the service response is a soap:Fault, I'm not having access to all of the response (I am using soapUI to mock the soap:Fault response).
I can access a tiny fraction of the soap:fault by getting the EXCEPTION_CAUGHT property.
The instruction
.log("Response ON ERROR FAULT: ${body}")
Has no data at all.
What can I do differently to have access to all the instead of only the faultstring?
Exception exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT,
Exception.class);
According to this answer, Camel's CXF component not catching onException(Exception.class):
Camel's onException only triggeres if there is an exception. A SOAP
Fault is represented as a Message with the fault flag = true.
What you can do is to set handleFault=true on CamelContext, then it
will turn SOAP fault messages into an exception that the onException
can react upon.
Assuming you have not configured handleFault=true, then it's odd that your exception handler is running at all. It could be that some other exception, not the Fault you're looking for, is occurring which causes the exception handler to run.
If you have already configured handleFault=true, I don't have any advice except inspect the data objects in a debugger to see if you can find out what's going on. (If you don't know, to do this you can add a Processor to your exception handler and insert a break point inside the Processor. Break points don't work in route definition because route definitions are only run on initialization.)

Camel errorHandler / deadLetterChannel REST response

I have a Camel rest endpoint (Jetty) which validates and processes incoming requests. Besides specific Exception handlers (onException) it uses a DLQ error handler (errorHandler(deadLetterChannel...)) which is setup to retry 3 times - if unsuccessful the message is moved to the DLQ.
My question is, how do I still return a user friendly error message back to the client if an unexpected Exception occurs rather than the full Exception body? Is there some config I'm missing on the errorHandler?
I've tried to find some examples on the camel unit tests (DeadLetterChannelHandledExampleTest) and camel in action 2 (Chapter 11) but none seemed to have specific examples for this scenario.
Code is:
.from(ROUTE_URI)
.errorHandler(deadLetterChannel("{{activemq.webhook.dlq.queue}}")
.onPrepareFailure(new FailureProcessor())
.maximumRedeliveries(3)
.redeliveryDelay(1000))
.bean(ParcelProcessor.class, "process");
Thank you for your help!
Use a 2nd route as the DLQ, eg direct:dead and then send the message first to the real DLQ, and then do the message transformation afterwards to return a friendly response.
errorHandler(deadLetterChannel("direct:dead")
from("direct:dead")
.to("{{activemq.webhook.dlq.queue}}")
.transform(constant("Sorry something was wrong"));

Apache Camel: Unable to get the Exception Body

Whenever there is normal flow in my Camel Routes I am able to get the body in the next component. But whenever there is an exception(Http 401 or 500) I am unable to get the exception body. I just get a java exception in my server logs.
I have also tried onException().. Using that the flow goes into it on error, but still I do not get the error response body that was sent by the web service(which I get when using POSTMAN directly), I only get the request in the body that I had sent to the web service.
Also adding the route:
from("direct:contractUpdateAds")
.to("log:inside_direct:contractUpdateAds_route_CompleteLog?level=INFO&showAll=true&multiline=true")
.streamCaching()
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
.log("before calling ADS for ContractUpdate:\nBody:${body}")
.to("{{AdsContractUpdateEndpoint}}")
.log("after calling ADS for ContractUpdate:\nBody:${body}")
.convertBodyTo(String.class)
.end();
Option 1: handle failure status codes yourself
The throwExceptionOnFailure=false endpoint option (available at least for camel-http and camel-http4 endpoints) is probably what you want. With this option, camel-http will no longer consider an HTTP Status >= 300 as an error, and will let you decide what to do - including processing the response body however you see fit.
Something along those lines should work :
from("...")
.to("http://{{hostName}}?throwExceptionOnFailure=false")
.choice()
.when(header(Exchange.HTTP_RESPONSE_CODE).isLessThan(300))
// HTTP status < 300
.to("...")
.otherwise()
// HTTP status >= 300 : would throw an exception if we had "throwExceptionOnFailure=true"
.log("Error response: ${body}")
.to("...");
This is an interesting approach if you want to have special handling for certains status codes for example. Note that the logic can be reused in several routes by using direct endpoints, just like any other piece of Camel route logic.
Option 2 : Access the HttpOperationFailedException in the onException
If you want to keep the default error handling, but you want to access the response body in the exception handling code for some reason, you just need to access the responseBody property on the HttpOperationFailedException.
Here's an example:
onException(HttpOperationFailedException.class)
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
// e won't be null because we only catch HttpOperationFailedException;
// otherwise, we'd need to check for null.
final HttpOperationFailedException e =
exchange.getProperty(Exchange.EXCEPTION_CAUGHT, HttpOperationFailedException.class);
// Do something with the responseBody
final String responseBody = e.getResponseBody();
}
});

camel with netty4-http - EncoderException

I'm using camel 2.14.0 with netty4-http
and I get the following exception.
the scenario is this:
I have a route that sends a request, waits for the response (inOut) and then sends another request.
the first request works, and then the second one fails.
also, if I do it quickly enough after the failure - the first request will also fail.
while debugging a bit (HttpObjectEncoder) - I saw that in the working flow the state of the request is: state = ST_INIT (0)
and in the request that failed it is: ST_CONTENT_NON_CHUNK (1)
which causes the illegal state when the type of message is HttpMessage
is this a bug or is there anything I can configure to fix it?
Caused by: io.netty.handler.codec.EncoderException: java.lang.IllegalStateException: unexpected message type: DefaultFullHttpRequest
at io.netty.handler.codec.MessageToMessageEncoder.write(MessageToMessageEncoder.java:107)
at io.netty.channel.CombinedChannelDuplexHandler.write(CombinedChannelDuplexHandler.java:192)
at io.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:658)
at io.netty.channel.AbstractChannelHandlerContext.access$2000(AbstractChannelHandlerContext.java:32)
at io.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:939)
at io.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:991)
at io.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:924)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:380)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:357)
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: unexpected message type: DefaultFullHttpRequest
at io.netty.handler.codec.http.HttpObjectEncoder.encode(HttpObjectEncoder.java:63)
at io.netty.handler.codec.http.HttpClientCodec$Encoder.encode(HttpClientCodec.java:106)
at io.netty.handler.codec.MessageToMessageEncoder.write(MessageToMessageEncoder.java:89)
... 10 more
I managed to identify the problem:
the first request I sent was a GET request with null body.
in the class org.apache.camel.component.netty4.http.NettyHttpProducer -
the method getRequestBody(Exchange exchange) is creating the actual request object from the exchange.
in it - the method "toNettyRequest" in class org.apache.camel.component.netty4.http.DefaultNettyHttpBinding
checks if the body is null, and if so - it is creating a DefaultHttpRequest, and not DefaultHttpFullRequest
when the request reaches the encoder as a result of a writeAndFlush call - the encoder does not clean its state because of this part of the code:
if (msg instanceof LastHttpContent) {
state = ST_INIT;
}
the DefaultHttpRequest is not instanceof LastHttpContent, so the state remains ST_CONTENT_NON_CHUNK and the next request will get an IllegalStateException because the state is not ST_INIT
this bug did not exist in netty-http, it only happened when I moved to use netty4-http
the workaround is simple - use an empty String ("") as body

Resources