Camel Rest DSL Response Codes - java

I have a route builder that looks as follows:
.post("/myEndpoint")
.type(MyObject.class)
.to("bean:myListener?method=create")
I would like this to return a 201 Created HTTP Response Code, at present its returns a 200 OK.
Is there a way to do this in the RouteBuilder without having to forward any results onto a separate service class and then manually set the code on the Exchange?

We managed to get it to work by doing the following -
.post("/myEndpoint")
.type(MyObject.class)
.route()
.setHeader(Exchange.HTTP_RESPONSE_CODE,simple(HTTP_CREATED))
.to("bean:myListener?method=create")
.endRest()

See the header section here http://camel.apache.org/constant.html for setting headers.. You should be able to set the http response code and body directly.

Related

How do I modify the HTTP response code and message in java

My goal is to modify the http response status code and the content that comes with it (not using spring by the way). The current response I'm getting is an HTTP 501 and I would like to modify that response to return an HTTP 200 instead with a custom message.
I've tried using javax.servlet.Filter and found out that that won't work (as far as I know) since I can't modify the response after the filterChain.doFilter() call. I tried redirecting a response using httpResponse.sendError() but didn't work since I'm getting an IllegalStateException telling me about the reponse was already committed or something like that.
I've also tried adding an <error-page>...</error-page> block in my web.xml using a web servlet as the location but apparently that does not work for unsupported methods and invalid headers (tried using a random string as request method; also tried Transfer-Encoding: random as an invalid header); works for invalid uri paths though.
Is there a way to create a general "filter" mechanism where I can modify the response code and message when there's a HTTP error code response?

To call two toD in apache camel spring dsl xml

I'm going to create one rest services in rest dsl xml. On that I have created one routes. For the route I am going to call my own microservices (this is created other project) for using toD uri. Once I get response I am going to take the values from the body (response json). After that again I am going to call other services in the same route based on the response values (we are taking one field in the response).
My question is
how we can take the values from the response in first service
And how to set headers in that respected values in first values..
How to call 2 services in route. Is it possible to call tod uri two times?
Sample code
<toD uri=http://localhost >
<log message =${body} >
(this response is going to set 2nd service query parameter value )
<toD uri=http://localhost? 1 services response values a>
Not sure if I fully understand your case, but here are my answers to your questions:
1) You can select any value from a JSON response with JsonPath. To use it later, you probably want to save it on the Message header
.setHeader("myHeader", jsonpath("$.your.json.path"))
2) Sorry, I don't understand this question :-)
3) Yes, you can make as many .to() or .toD() as you like
However, if you want to call REST services and you use the Camel REST component, you can profit from built-in URI templating. That means perhaps you don't need .toD()
For example
.to("rest:get:hello/{myHeader}")
would insert the value extracted from the JSON response above because the placeholder name is looked up in the message headers and if found replaced with the value of the corresponding message header
.setHeader("myHeader", jsonpath("$.your.json.path")) // assume jsonpath result is "world"
.to("rest:get:hello/{myHeader}") // URI "hello/world" is called

How to log request payload when using Camel Rest?

I'd like to log the original 'raw' request body (e.g. JSON) while using Camel Rest endpoints. What's the proper way to do this?
My setup (RouteBuilder) looks like this:
restConfiguration().component("jetty")
.host(this.host)
.port(this.port)
.contextPath(this.contextPath)
.bindingMode(RestBindingMode.json);
rest("myService/").post()
.produces("application/json; charset=UTF-8")
.type(MyServiceRequest.class)
.outType(MyServiceResponse.class)
.to(SERVICE_CONTEXT_IN);
from(SERVICE_CONTEXT_IN).process(this.serviceProcessor);
My problem here is that the mechanics such as storing the request as an Exchange property are 'too late' in terms of using this approach, any processors are too late in the route, i.e., the binding already took place and consumed the Request. Also the CamelHttpServletRequest's InputStream has already been read and contains no data.
The first place to use the log EIP is directly before the single processor:
from(SERVICE_CONTEXT_IN).log(LoggingLevel.INFO, "Request: ${in.body}")
.process(this.serviceProcessor);
but at that point the ${in.body} is already an instance of MyServiceRequest. The added log above simply yields Request: x.y.z.MyServiceRequest#12345678. What I'd like to log is the original JSON prior to being bound to a POJO.
There seems to be no built-in way of enabling logging of the 'raw' request in RestConfigurationDefinition nor RestDefinition.
I could get rid of the automatic JSON binding and manually read the HTTP Post request's InputStream, log and perform manual unmarshalling etc. in a dedicated processor but I would like to keep the built-in binding.
I agree there is no way to log the raw request (I assume you mean the payload going through the wire before any automatic binding) using Camel Rest endpoints.
But taking Roman Vottner into account, you may change your restConfiguration() as follows:
restConfiguration().component("jetty")
.host(this.host)
.port(this.port)
.componentProperty("handlers", "#yourLoggingHandler")
.contextPath(this.contextPath)
.bindingMode(RestBindingMode.json);
where your #yourLoggingHandler needs to be registered in your registry and implement org.eclipse.jetty.server.Handler. Please take a look at writing custom handlers at Jetty documentation http://www.eclipse.org/jetty/documentation/current/jetty-handlers.html#writing-custom-handlers.
In the end I 'solved' this by not using the REST DSL binding with a highly sophisticated processor for logging the payload:
restConfiguration().component("jetty")
.host(this.host)
.port(this.port)
.contextPath(this.contextPath);
rest("myService/").post()
.produces("application/json; charset=UTF-8")
.to(SERVICE_CONTEXT_IN);
from(SERVICE_CONTEXT_IN).process(this.requestLogProcessor)
.unmarshal()
.json(JsonLibrary.Jackson, MyServiceRequest.class)
.process(this.serviceProcessor)
.marshal()
.json(JsonLibrary.Jackson);
All the requestLogProcessor does is to read the in body as InputStream, get and log the String, and eventually pass it on.
You can solve this by:
Turning the RestBindingMode to off on your specific route and logging the incoming request string as is.
After which you can convert the JSON string to your IN type object using ObjectMapper.
At the end of the route convert the java object to JSON and put it in the exchange out body, as we turned off the RestBindingMode.
rest("myService/").post()
.bindingMode(RestBindingMode.off)
.to(SERVICE_CONTEXT_IN);
In my case, streamCaching did the trick because the Stream was readable only once. Thefore I was able log but was not able to forward the body any more. I hope this might be of help to someone

Spring RestTemplate forward large file to another service

I am trying to forward a large file pulled as an input stream to another service using spring's resttemplate. I have followed the answer given by #artbristol in this topic: How to forward large files with RestTemplate?
And it looks like it is setting the body of the request properly (grabbing the request with charlesproxy). The problem is that I have not set the headers correctly since I believe I need to set the content-type as multipart/formdata which I tried by adding this in the callback:
request.getHeaders().setContentType(
new MediaType("multipart", "form-data"));
But in the http headers I am still missing the boundary, not sure how to set that and I am sure I am probably missing some other settings.
So I was able to figure this out. Basically I needed to create a Spring message converter that will take in the input stream and write out to the body. I also basically have to use the Form Message Converter to write out the response body as well.
So in the restTemplate I call an add message converter to add new input stream message converter. In the call back I create a multivaluemap that takes in a string and inputstream and wrap that around an HttpEntity. Then I create a new instance of the Form Message converter and call write, passing in request, and the mutlivaluemap.
It looks like the issue is that I did not include the path to htrace-core.jar in the spark class path:
spark-shell --driver-class-path /opt/cloudera/parcels/CDH/lib/hbase/hbase-server.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-protocol.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop2-compat.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-client.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-common.jar:/opt/cloudera/parcels/CDH/lib/hbase/lib/htrace-core.jar:/etc/hbase/conf
Seems like this is new for spark 1.x

Restlet response to POST request

First off, I'm using an older version of Restlet (1.1).
Secondly, I'm not sure I'm doing the correct thing. Here's what I'm trying to do...
I'm creating a reporting service (resource). I'd like my service to listen for POST requests. The body of the request will contain the report definition. I'd like the response to be the CSV file generated by the service (the report). Is responding to a POST request in this manner OK from a REST standpoint (if not, then how to refine this resource)?
I can't seem to figure out how the acceptRepresentation() generates the response. I've tried setting the Representation parameter passed into the method to a new FileRepresentation. I've also tried to utilize the represent() method, but it doesn't seem like that method is called as part of the POST processing.
How can I accomplish this seeming easy task?
Calling the getResponse().setEntity() method from acceptRepresentation() will accept the new FileRepresentation and accomplish what I'd like to.

Categories