CamelHttpResponseCode is null on service error - java

I'm new to camel and writing a small POC to implement in an existing application. Application takes a xml request as input which contains the requested services and relevant data. It then calls those services one by one.
When a service is called successfully then I retrieve the http response code in a processor like below and do further logic:
Object code = exchange.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE);
if(null!=code && code instanceof Integer)
{
responseCode = (Integer) code;
}
In success case, responseCode received = 201
Based on the responseCode, I know if the service call is successful and then proceed with the next one.
However, I tried to produce the negative scenario by making the service url incorrect and can't see the http response code anymore:
Original service url - http://xxx:0000/.../.../.../.../...
Modified service url - http://xxx:0000/.../.../.../.../abc/...
In failure case, responseCode received = null
In postman, I get the below error:
org.apache.camel.http.common.HttpOperationFailedException: HTTP
operation failed invoking http://xxx:0000/.../.../.../.../abc/...
with statusCode: 404 at
org.apache.camel.component.http.HttpProducer.populateHttpOperationFailedException(HttpProducer.java:274)
at
org.apache.camel.component.http.HttpProducer.process(HttpProducer.java:183)
I don't know why exchange doesn't contain the http response code when it's present in the error message in the postman.
I'm using onException to handle any exceptions and then calling a processor to process the flow further:
<camel:onException>
<camel:exception>java.lang.Exception</camel:exception>
<camel:process ref="xxxProcessor" />
</camel:onException>
I think I can consider responseCode=null as failure and proceed with my logic but want to understand why response code is being returned as null.
Thanks in advance!

I figured it out. It seems that in case of service exception, an instance of org.apache.camel.http.common.HttpOperationFailedException is thrown and the http status code is present in it. It can be retrieved in the processor like below:
Exception e = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
if(null!=e && e instanceof HttpOperationFailedException)
{
HttpOperationFailedException httpOperationFailedException = (HttpOperationFailedException)e;
responseCode=httpOperationFailedException.getStatusCode();
}

The accepted answer helped me and it might have been valid! In the camel version I'm usin (2.20.1), getting the exception via the property does not seem to work. The following does
HttpOperationFailedException httpOperationFailedException = exchange.getException(HttpOperationFailedException.class);
if(null!=e) {
responseCode = httpOperationFailedException.getStatusCode());
}

Related

Spring Rest Template - Post Request String Body to azure gives 500 error

I'm able call 4-5 rest apis, prior to coming to this block of code. But I'm not able to execute this block of code.
I am using spring 4.0.4 core, mvc jars.
I am trying to call a azure ucwa web service using rest template, its a post method with string as body. I m getting a 500 internal error. I have searched all over internet and yet did not find solution, Please guide me. Thank you.
link : https://learn.microsoft.com/en-us/skype-sdk/ucwa/sendanim
step 9
RestTemplate restTemplate = new RestTemplate();
System.out.println(" jsonLinksObj : 4a "+jsonLinksObj);
org.json.JSONObject jsonSendMessageObj = jsonLinksObj.getJSONObject("sendMessage");
String sendMsgFullUrl = poolUrl.concat(jsonSendMessageObj.getString("href")).concat("?OperationContext=4322131");
headers.clear();
headers.setContentType(MediaType.TEXT_PLAIN);
headers.set("Authorization", "Bearer " + jwtToken);
String body = "My Send Message Here";
HttpEntity<Object> entityJsonSendMsg4 = new HttpEntity<Object>(body, headers);
ResponseEntity<Object> sbSendMsgObj = null;
try{
sbSendMsgObj = restTemplate.exchange(
new URI(sendMsgFullUrl),
HttpMethod.POST,
entityJsonSendMsg4,
Object.class);
} catch(Exception e){
e.printStackTrace();
}
WARN : org.springframework.web.client.RestTemplate - POST request for "https://webpoolpnqin102.infra.lync.com/ucwa/oauth/v1/applications/102086376449/communication/conversations/46db8085-8ad0-4186-a4f0-9a521b256b9b/messaging/messages?OperationContext=4322131" resulted in 500 (Internal Server Error); invoking error handler
org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:589)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:547)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:518)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:463)
at com.test.example.employee.test.EmployeeTest.sendMessage(EmployeeTest.java:266)
at com.test.example.employee.test.EmployeeTest.main(EmployeeTest.java:337)
Exception in thread "main" java.lang.NullPointerException
at com.test.example.employee.test.EmployeeTest.sendMessage(EmployeeTest.java:331)
at com.test.example.employee.test.EmployeeTest.main(EmployeeTest.java:337)
It is hard to say what is the reason behind the 500 you got in response - you probably have to debug it yourself but it should not be very hard.
Since you created RestTemplate using default constructor you have got a deafault error handling. Run your application in debug mode and place a breakpoint in DefaultResponseErrorHandler::handleError. There you get the access to response represented by ClientHttpResponse class and can actually look into body you got back.
When you know the reason behind the error you can correct the request accordingly.
I have clean and build the project. And run the code again. Its working fine, anybody want to send string in body, can use the above rest template code. Thank you.

Camel REST service throws Exception when returning null

I have a simple REST service. There are clients and I can get a client by its ID. In case there is no client with the requested ID, a 404 not found should be returned.
Here's the relevant part:
rest("/client")
.consumes("application/json").produces("application/json")
.get("{id}")
.to("direct:getClient");
from("direct:getClient")
.bean(clientService, "getClient(${header.id})")
.choice()
.when(simple("${body} == null"))
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(404));
Everything is fine when clients can be found, however, when the client is not found and clientService returns null, I get the following stack trace:
org.apache.camel.RuntimeCamelException: java.io.IOException: Stream closed
at org.apache.camel.http.common.HttpMessage.createBody(HttpMessage.java:74)
at org.apache.camel.impl.MessageSupport.getBody(MessageSupport.java:47)
at org.apache.camel.processor.CamelInternalProcessor$StreamCachingAdvice.after(CamelInternalProcessor.java:799)
at org.apache.camel.processor.CamelInternalProcessor$StreamCachingAdvice.after(CamelInternalProcessor.java:767)
at org.apache.camel.processor.CamelInternalProcessor$InternalCallback.done(CamelInternalProcessor.java:246)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:573)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:120)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:83)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197)
at org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:62)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:145)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:542)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:120)
I can't figure this one out. Returning null from a bean method call should be possible, right?
Try as a workaround to use
.setBody().method(clientService, "getClient(${header.id})")
I suspect its the .bean() that has a little bug when you return a null value as the new message body, which fools the underlying HttpMessage into thinking the message body hasn't been initialized yet, and thus you get that stream error reading the stream again.
I think that main idea that you can throw new exception SomeClassException if the clientid not found in your bean and handle in rest route
public class SomeClassException extends Exception {
private static final long serialVersionUID = 2542653496302641967L;
public SomeClassException() {
}
public SomeClassException(String arg0) {
super(arg0);
}
}
your route:
rest("/client/")
.consumes("application/json").produces("application/json")
.get("{id}")
.to("direct:getClient");
onException(SomeClassException.class) .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(404)).handled(true);
from("direct:getClient")
.bean(clientService, "getClient(${header.id})")
;
I experienced a similar issue when returning NO_CONTENT on the route on a method that had the option to return an object or not depending on if anything was queued. The code was structured like so:
rest("/foo")
.get("/bar").route().to("direct:foo").endRest()
;
from("direct:bar")
.process(exchange -> {
// ... service calls that eventually resulted in this ...
// (status code of 204 and a body of null)
ResponseEntity responseEntity =
exchange.getIn().getBody(ResponseEntity.class);
exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, responseEntity.getStatusCodeValue());
exchange.getIn().setBody(responseEntity.getBody());
})
.marshal().json(JsonLibrary.Jackson)
;
I was experiencing the same error, org.apache.camel.RuntimeCamelException: java.io.IOException: Stream closed, even though I was stepping through my code and seeing everything process as expected. Like you, everything worked fine when the method returned an object, but only threw this exception when the body was set to null.
At this point, I figured there was some complicated series of events in Camel that goes wrong when the response body is set to null. Stepping through the code wasn't as helpful as I would have hoped, so I just looked up what the standard practice for a response entity was in the case of NO_CONTENT or NOT_FOUND and stumbled across this post. I believe Camel works in the same way with converters and requires some type of object, so I just modified my code like so:
exchange.getIn().setBody(responseEntity.getBody() == null ? "" : responseEntity.getBody());
As a result, there is still no body in the message returned to clients, and there is no more IOException: Stream closed error.
Just to add a specific scenario when the similar error is thrown where the root cause is the invalid Json.
Considering this specific example:
String tempDate = yourExchangeObject.getIn().getBody(String.class);
JSONObject inputJson = new JSONObject(tempDate); //Exception

How to return custom error codes in Cloud Endpoints?

As described here https://cloud.google.com/appengine/docs/java/endpoints/exceptions Google Cloud Endpoints only returns a very limited range of http status codes, namely:
HTTP 400 BadRequestException
HTTP 401 UnauthorizedException
HTTP 403 ForbiddenException
HTTP 404 NotFoundException (also: Timeout)
HTTP 405
HTTP 408
HTTP 409 ConflictException
HTTP 410
HTTP 412
HTTP 413
Google suggests to use the existing status codes to return custom errors:
"In many situations, you may want to use common HTTP status codes to indicate the success or failure of a user's API request. For example, if a user is attempting to retrieve an entity which does not exist, you may want to send an HTTP 404 status code saying No entity exists with ID: entityId.
You can send such common HTTP status codes by throwing an exception provided by the endpoints library as follows:
String message = "No entity exists with ID: " + entityId;
throw new NotFoundException(message);
"
Further down in the same document, Google states:
"Any other HTTP 4xx codes will be returned as error 404"
What's the problem with that? I throw 404 if my entity cannot be found, but Google also throws 404 for almost anything else that goes wrong.
With the exception of 401, 403, and 409, which I can use to tell my client what the exact error was (authorization, forbidden or conflict), I need to fall back to 400 and 404 for all my other status codes, with the result that my client never knows exactly what the problem was.
Sure I can include a human readable error message, but that is meant for RuntimeException(s) that occured in the server code, not to tell my client there was a problem with the data it sent.
Sure, I can also use the first few digits of the error description to send an application specific error code and send the generic 400 Bad Request, but I guess that's not how this should be done.
Any input appreciated. How do you return application specific error codes which your client can use to resolve an application-specific problem?
Having read the following and other posts
http://archive.oreilly.com/pub/post/restful_error_handling.html
Standard JSON API response format?
I would almost say what Google suggests is wrong, because there is no clear differentiation between http status codes and application codes. Both happen on different layers, and the client has no way to tell if it made a bad request, such as violating a contract (e.g. calling a non-existing endpoint, essentially a runtime error), or passing a wrong id (an application layer error).
Articles suggest the following solutions:
use http error codes: not always possible as discussed above
add the application error as custom response header: I would not choose this because it won't appear in the log, which will make debugging tough.
always return 200 and wrap the result in a JSON (as sockets.io does): not viable with endpoints
I came up with another solution which I admit is a compromise (a violation of the error message, in fact), but which I believe is the best suitable integration of individual application error codes into Cloud Endpoints:
I extended 400 BadRequestException, so that any error message is returned as JSON. The client still receives receives http status code 400, but instead of a String error message, it receives a JSON string like this:
{
"code": 400,
"message": "This is a human readable error message."
}
And here I have two options: Either I return code 400, which means this is a BadRequestException where the client actually violated a contract, or I return any other application specific code, which the client can easily parse and process.
My ApplicationException looks like this (it uses a custom JSONizer so it won't work for you like this but you could use JSONObject, GSON, Jackson, whatever):
import com.google.api.server.spi.response.BadRequestException;
public class ApplicationException extends BadRequestException {
private static final int DEFAULT_APPLICATION_CODE = 400; // use this code for all requests without explicit code
public ApplicationException(int code, String message) {
super(JsonResponse.build()
.add("code", code)
.add("message", message)
.toString());
}
public ApplicationException(String message) {
super(JsonResponse.build()
.add("code", DEFAULT_APPLICATION_CODE)
.add("message", message)
.toString());
}
public ApplicationException(String message, Throwable cause) {
super(JsonResponse.build()
.add("code", DEFAULT_APPLICATION_CODE)
.add("message", message)
.toString());
}
}
I haven't marked my answer as correct as I want you to keep posting further suggestions and comments if you believe there are better ways to do this.

Spring REST tutorial [duplicate]

I'm building a REST API, but I've encountered a problem.
It seems that accepted practice in designing a REST API is that if the resource requested doesn't exist, a 404 is returned.
However, to me, this adds unnecessary ambiguity. HTTP 404 is more traditionally associated with a bad URI. So in effect we're saying "Either you got to the right place, but that specific record does not exist, or there's no such location on the Internets! I'm really not sure which one..."
Consider the following URI:
http://mywebsite/api/user/13
If I get a 404 back, is that because User 13 does not exist? Or is it because my URL should have been:
http://mywebsite/restapi/user/13
In the past, I've just returned a NULL result with an HTTP 200 OK response code if the record doesn't exist. It's simple, and in my opinion very clean, even if it's not necessarily accepted practice. But is there a better way to do this?
404 is just the HTTP response code. On top of that, you can provide a response body and/or other headers with a more meaningful error message that developers will see.
Use 404 if the resource does not exist. Don't return 200 with an empty body.
This is akin to undefined vs empty string (e.g. "") in programming. While very similar, there is definitely a difference.
404 means that nothing exists at that URI (like an undefined variable in programming). Returning 200 with an empty body means that something does exist there and that something is just empty right now (like an empty string in programming).
404 doesn't mean it was a "bad URI". There are special HTTP codes that are intended for URI errors (e.g. 414 Request-URI Too Long).
As with most things, "it depends". But to me, your practice is not bad and is not going against the HTTP spec per se. However, let's clear some things up.
First, URI's should be opaque. Even if they're not opaque to people, they are opaque to machines. In other words, the difference between http://mywebsite/api/user/13, http://mywebsite/restapi/user/13 is the same as the difference between http://mywebsite/api/user/13 and http://mywebsite/api/user/14 i.e. not the same is not the same period. So a 404 would be completely appropriate for http://mywebsite/api/user/14 (if there is no such user) but not necessarily the only appropriate response.
You could also return an empty 200 response or more explicitly a 204 (No Content) response. This would convey something else to the client. It would imply that the resource identified by http://mywebsite/api/user/14 has no content or is essentially nothing. It does mean that there is such a resource. However, it does not necessarily mean that you are claiming there is some user persisted in a data store with id 14. That's your private concern, not the concern of the client making the request. So, if it makes sense to model your resources that way, go ahead.
There are some security implications to giving your clients information that would make it easier for them to guess legitimate URI's. Returning a 200 on misses instead of a 404 may give the client a clue that at least the http://mywebsite/api/user part is correct. A malicious client could just keep trying different integers. But to me, a malicious client would be able to guess the http://mywebsite/api/user part anyway. A better remedy would be to use UUID's. i.e. http://mywebsite/api/user/3dd5b770-79ea-11e1-b0c4-0800200c9a66 is better than http://mywebsite/api/user/14. Doing that, you could use your technique of returning 200's without giving much away.
That is an very old post but I faced to a similar problem and I would like to share my experience with you guys.
I am building microservice architecture with rest APIs. I have some rest GET services, they collect data from back-end system based on the request parameters.
I followed the rest API design documents and I sent back HTTP 404 with a perfect JSON error message to client when there was no data which align to the query conditions (for example zero record was selected).
When there was no data to sent back to the client I prepared an perfect JSON message with internal error code, etc. to inform the client about the reason of the "Not Found" and it was sent back to the client with HTTP 404. That works fine.
Later I have created a rest API client class which is an easy helper to hide the HTTP communication related code and I used this helper all the time when I called my rest APIs from my code.
BUT I needed to write confusing extra code just because HTTP 404 had two different functions:
the real HTTP 404 when the rest API is not available in the given url, it is thrown by the application server or web-server where the rest API application runs
client get back HTTP 404 as well when there is no data in database based on the where condition of the query.
Important: My rest API error handler catches all the exceptions appears in the back-end service which means in case of any error my rest API always returns with a perfect JSON message with the message details.
This is the 1st version of my client helper method which handles the two different HTTP 404 response:
public static String getSomething(final String uuid) {
String serviceUrl = getServiceUrl();
String path = "user/" + , uuid);
String requestUrl = serviceUrl + path;
String httpMethod = "GET";
Response response = client
.target(serviceUrl)
.path(path)
.request(ExtendedMediaType.APPLICATION_UTF8)
.get();
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
// HTTP 200
return response.readEntity(String.class);
} else {
// confusing code comes here just because
// I need to decide the type of HTTP 404...
// trying to parse response body
try {
String responseBody = response.readEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
ErrorInfo errorInfo = mapper.readValue(responseBody, ErrorInfo.class);
// re-throw the original exception
throw new MyException(errorInfo);
} catch (IOException e) {
// this is a real HTTP 404
throw new ServiceUnavailableError(response, requestUrl, httpMethod);
}
// this exception will never be thrown
throw new Exception("UNEXPECTED ERRORS, BETTER IF YOU DO NOT SEE IT IN THE LOG");
}
BUT, because my Java or JavaScript client can receive two kind of HTTP 404 somehow I need to check the body of the response in case of HTTP 404. If I can parse the response body then I am sure I got back a response where there was no data to send back to the client.
If I am not able to parse the response that means I got back a real HTTP 404 from the web server (not from the rest API application).
It is so confusing and the client application always needs to do extra parsing to check the real reason of HTTP 404.
Honestly I do not like this solution. It is confusing, needs to add extra bullshit code to clients all the time.
So instead of using HTTP 404 in this two different scenarios I decided that I will do the following:
I am not using HTTP 404 as a response HTTP code in my rest application anymore.
I am going to use HTTP 204 (No Content) instead of HTTP 404.
In that case client code can be more elegant:
public static String getString(final String processId, final String key) {
String serviceUrl = getServiceUrl();
String path = String.format("key/%s", key);
String requestUrl = serviceUrl + path;
String httpMethod = "GET";
log(requestUrl);
Response response = client
.target(serviceUrl)
.path(path)
.request(ExtendedMediaType.APPLICATION_JSON_UTF8)
.header(CustomHttpHeader.PROCESS_ID, processId)
.get();
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
return response.readEntity(String.class);
} else {
String body = response.readEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
ErrorInfo errorInfo = mapper.readValue(body, ErrorInfo.class);
throw new MyException(errorInfo);
}
throw new AnyServerError(response, requestUrl, httpMethod);
}
I think this handles that issue better.
If you have any better solution please share it with us.
404 Not Found technically means that uri does not currently map to a resource. In your example, I interpret a request to http://mywebsite/api/user/13 that returns a 404 to imply that this url was never mapped to a resource. To the client, that should be the end of conversation.
To address concerns with ambiguity, you can enhance your API by providing other response codes. For example, suppose you want to allow clients to issue GET requests the url http://mywebsite/api/user/13, you want to communicate that clients should use the canonical url http://mywebsite/restapi/user/13. In that case, you may want to consider issuing a permanent redirect by returning a 301 Moved Permanently and supply the canonical url in the Location header of the response. This tells the client that for future requests they should use the canonical url.
So in essence, it sounds like the answer could depend on how the request is formed.
If the requested resource forms part of the URI as per a request to http://mywebsite/restapi/user/13 and user 13 does not exist, then a 404 is probably appropriate and intuitive because the URI is representative of a non-existent user/entity/document/etc. The same would hold for the more secure technique using a GUID http://mywebsite/api/user/3dd5b770-79ea-11e1-b0c4-0800200c9a66 and the api/restapi argument above.
However, if the requested resource ID was included in the request header [include your own example], or indeed, in the URI as a parameter, eg http://mywebsite/restapi/user/?UID=13 then the URI would still be correct (because the concept of a USER does exits at http://mywebsite/restapi/user/); and therefore the response could reasonable be expected to be a 200 (with an appropriately verbose message) because the specific user known as 13 does not exist but the URI does. This way we are saying the URI is good, but the request for data has no content.
Personally a 200 still doesn't feel right (though I have previously argued it does). A 200 response code (without a verbose response) could cause an issue not to be investigated when an incorrect ID is sent for example.
A better approach would be to send a 204 - No Contentresponse. This is compliant with w3c's description *The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation.*1 The confusion, in my opinion is caused by the Wikipedia entry stating 204 No Content - The server successfully processed the request, but is not returning any content. Usually used as a response to a successful delete request. The last sentence is highly debateable. Consider the situation without that sentence and the solution is easy - just send a 204 if the entity does not exist. There is even an argument for returning a 204 instead of a 404, the request has been processed and no content has been returned! Please be aware though, 204's do not allow content in the response body
Sources
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
1. http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
This old but excellent article... http://www.infoq.com/articles/webber-rest-workflow says this about it...
404 Not Found - The service is far too lazy (or secure) to give us a real reason why our request failed, but whatever the reason, we need to deal with it.
This recently came up with our team.
We use both 404 Not found with a message body and 204 No Content based on the following rational.
If the request URI indicates the location of a single resource, we use 404 Not found. When the request queries a URI, we use 204 No Content
http://mywebsite/api/user/13 would return 404 when user 13 does not exist
http://mywebsite/api/users?id=13 would return 204 no content
http://mywebsite/api/users?firstname=test would return 204 no content
The idea here being, 'query routes' are expected to be able to return 1, many or no content.
Whatever pattern you choose, the most important things is to be consistent - so get buy in from your team.
The Uniform Resource Identifier is a unique pointer to the resource. A poorly form URI doesn't point to the resource and therefore performing a GET on it will not return a resource. 404 means The server has not found anything matching the Request-URI. If you put in the wrong URI or bad URI that is your problem and the reason you didn't get to a resource whether a HTML page or IMG.
Since this discussion seems to be able to survive the end of time I'll throw in the JSON:API Specifications
404 Not Found
A server MUST respond with 404 Not Found when processing a request to fetch a single resource that does not exist, except when the request warrants a 200 OK response with null as the primary data (as described above).
HTTP/1.1 200 OK
Content-Type: application/vnd.api+json
{
"links": {
"self": "http://example.com/articles/1/author"
},
"data": null
}
Also please see this Stackoverflow question
For this scenario HTTP 404 is response code for the response from the REST API
Like 400, 401, 404 , 422 unprocessable entity
use the Exception handling to check the full exception message.
try{
// call the rest api
} catch(RestClientException e) {
//process exception
if(e instanceof HttpStatusCodeException){
String responseText=((HttpStatusCodeException)e).getResponseBodyAsString();
//now you have the response, construct json from it, and extract the errors
System.out.println("Exception :" +responseText);
}
}
This exception block give you the proper message thrown by the REST API

camel cxf proxy doesnt work with http endpoint

My requirement is to have a proxy web service which will receive the request from clients and then route through camel,enrich it and forward it to real webservice at other clients place ,get response and send it back to the original requestor.
i basically looked at camel-cxf-proxy example (http://camel.apache.org/cxf-proxy-example.html) and camel-cxf-example in camel distribution.Its exactly similar to camel-cxf-proxyand came up with this route
<from uri="cxf:bean:soapMessageEndpoint?dataFormat=MESSAGE" />
<camel:convertBodyTo type="java.lang.String"></camel:convertBodyTo>
<to ref="XService"></to>
where endpoints are
<endpoint id="XService" uri="http://xx.xx.xxx.xx:8080/X_Service" />
<cxf:cxfEndpoint id="soapMessageEndpoint" address="http://localhost:8181/ProviderInformationDirectoryService" wsdlURL="wsdl/HPD_ProviderInformationDirectory.wsdl" endpointName="s:ProviderInformationDirectory_Port_Soap" serviceName="s:ProviderInformationDirectory_Service" xmlns:s="urn:ihe:iti:hpd:2010"/>
As you can see the second service is http endpoint.And first is the camel-cxf proxy.I just have the wsdl and at this point there is no need for impl.the dataformat is MESSAGE as i need the entire soap envelope to be sent to second web service and there are some useful headers in request from client.But when i run this route with a sample soap envelope it always comes up with 500 response.I am thinking that message sent to real webservice is not what it expects.
I tried trace on camel route but it didnt show much.I was hoping it will show real request to http endpoint.i tried to configure interceptor but that didnt work either.Trace only shows following
Failed delivery for (MessageId: ID-ALHCAN0437-63941-1354828653539-45-2 on ExchangeId: ID-ALHCAN0437-63941-1354828653539-45-1). Exhausted after delivery attempt: 1 caught: org.apache.camel.component.http.HttpOperationFailedException: HTTP operation failed invoking http://X:8080/X_Service with statusCode: 500
I also tried the following which seems to be working.
<from uri="cxf:bean:soapMessageEndpoint?dataFormat=MESSAGE" />
<camel:convertBodyTo type="java.lang.String"></camel:convertBodyTo>
<to uri="bean:callRemoteWS"></to>
callRemoteWS (callRemoteMethod) gets the soapenvelope as string and makes a HTTPPost request to above endpoint , returns back the response.
public String callRemoteMethod(String request) throws Exception{
HttpClient client = new HttpClient();
BufferedReader br = null;
PostMethod method = new PostMethod("http://x.x.x.x:8080/X_Service");
RequestEntity entity =new StringRequestEntity(request);
method.setRequestEntity(entity);
try{
int returnCode = client.executeMethod(method);
if (returnCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
return "Error";
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
System.out.println(new String(responseBody));
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
return new String(responseBody);
} finally {
method.releaseConnection();
if(br != null) try { br.close(); } catch (Exception fe) {}
}
}
I am confused why the simple camel-cxf proxy with http webservice didnt work and the second one works (it should and it does :P).Is the code i have ok.It doesnt seem right to me.I am pretty sure some exchange property is set wrong or content sent to real webservice is wrong.The content got from the proxy is used to make the Httppost call in second route.so the content from proxy cannot be wrong.when it is got from exchange and send to real webservice something goes wrong. Can anybody throw some light on it.
I think it was a silly mistake on my part .Soap action header had a different operation and the payload was for a different method.I was invoking the wrong operation with the payload

Categories