Overriding all JAX-RS responses with a constant response header - jax-rs

I'm writing a fairly generic webapp that I want to be JAX-RS "pure", though I'm developing using Jetty and CXF. I want to do something extremely simple, I want for ALL HTTP responses a header added (not just for the methods I'm writing code for, even auto-handled 415 responses).
Solutions for How do i modify HTTP headers for a JAX-WS response in CXF? seem overly complex (and specific for CXF's implementations of JAX-RS)for just needing to add:
MyServerVersion : 1.0
to every response.

The standard way to do this is with a ContainerResponseFilter. See Chapter 6: Filters and Interceptors of the JAX-RS specification.
You'll want to add your header to ContainerResponseContext#getHeaders(). See this question for an example.

Thanks for answer above, I summarized what I did in a blog post and it gives some background and context for the Accept-Post response header I was working with and code samples.

Related

Custom Response code and response message in restfull and SOAP services

I'm developing Web services restful and SOAP Services, I'm wondering what if I use custom response code and custom response message included in response body and the http response status code in most cases will be returned as (200 ok) so it will be easier to handle errors, I'm wondering if that way is acceptable
In HTTP, the definition of a status-line is found in RFC 7230
status-line = HTTP-version SP status-code SP reason-phrase CRLF
reason-phrase turns out to not be particularly important; clients are expected to ignore the reason phrase when processing an HTTP response.
The rest of the response message is to be interpreted in light of the semantics defined for that status code
The status code is an important piece of metadata in the transfer of documents over a network domain; general purpose clients use it to understand the nature of the HTTP response so that they can do intelligent things.
(Among the intelligent things: automatically following redirects, retrying requests with authentication credentials attached, cache invalidation).
There's a lot of code out on the internet that you don't control, that understands standardized HTTP semantics. When you fail to respect the standardized semantics, you introduce a risk that some other code will misunderstand your responses; when that happens, the blame lies squarely with your implementation, not the client.
Expressed another way: violating the standard doesn't make things "easier"; what it does is move around where the work needs to be done. Abiding the standard is doing your fair share of the work; offloading your share of the work onto your clients is rude.
That said, if you look carefully, there are plenty of spaces where you will find that people do deliberately violate the standards (I see this when working on health checks). The dreadful consequences of violating the standard are not guaranteed.
Use appropriate status codes for appropriate errors. Both SOAP and REST should use 4xx and 5xx where they make sense. If you are looking for a good standard response type for REST, go for application/problem+json, for SOAP use SOAP's standards.
Clients for each should still behave correctly if they get a HTTP error, but don't support/understand the response body.

Jaxrs multipart

I'm trying to perform a request to a jaxrs service which has media type set to multipart/form-data. This request contains a list of entities(xml) and an image(png, binary). I have created the request as described in this thread by BalusC.
The request seems ok after inspecting it in wireshark, except for the ip header checksum being wrong.(says something about "may be caused by IP checksum offload".)
My big issue here is how to handle the multipart request on the service side. I do not wish to include any libraries from apache.cxf, resteasy or anything of the sort. All I want to rely on is the jaxrs api.
The two parts in the request have names deliveries and signature, where the signature is a png image file sent as binary. The list of deliveries should be parsed from an xml(the entity has the xmlrootelement annotation and such, so this part works separately). I've attempted with this way of reading the different parts, but this was really a longshot;
#PUT
#Path("signOff")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public void signOffDeliveries(#FormParam("deliveries") List<Delivery> deliveries, #FormParam("signature")File signature) {
//do something with the signature(image) and the list of deliveries.
}
This does off course not work, and it gives me a 404 http status code if I run the request on Websphere, and a 415 when I run the request towards an embedded openejb (in our integration test framework). If I remove the FormParam annotations the request succeeds.
How can I read the different parts of the multipart request using only the jaxrs api?
EDIT
Ok, so I canged the PUT to POST, and added an #Encoding annotation to the params as so:
#POST
#Path("signOff")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public void signOffDeliveries(
#Encoded #FormParam("deliveries") String deliveries,
#Encoded #FormParam("signature") File signature) {
}
Now I get the xml as a text string, but I am not able to automatically unmarshal it to a list of deliveries even though the Content-Type of this part of the payload is set to application/xml. The other problem is that the file I receive has length==0, and I am not able to read any bytes from it.
Am I missing an essential point here?
Indeed I find it hard to understand why the JAX-RS spec doesn't standardize a support for this (I've just created https://java.net/jira/browse/JAX_RS_SPEC-413 to address this).
However it is nevertheless possible to support multi-part forms in an implementation independent fashion. Either you write your own MessageBodyReader for MultiPart form or you use a library like Apache Clerezza jaxrs.utils which provide a MultiPartBody object which respective MessageBodyReader. This library has no implementation specification dependency so your application will run on any jax-rs implementation.
For an example on how Clerezza jaxrs.utils is used see line 105 in http://svn.apache.org/viewvc/stanbol/trunk/development/archetypes/stateless-webmodule/src/main/resources/archetype-resources/src/main/java/MultiEnhancer.java?revision=1465777&view=markup. If you're not using OSGi (with white-board registration of resources) you will have to add to org.apache.clerezza.jaxrs.utils.form.MultiPartFormMessageBodyReader to your Application.
I have implemented this in Glassfish 4 without coupling with Jersey. #See this post for details
I do not wish to include any libraries from apache.cxf, resteasy or anything of the sort. All I want to rely on is the jaxrs api
You can't "rely on" the API, since it contains only interfaces. Classes that implement that interfaces come from RESTeasy, or Jersey, or CXF.
and a 415 when I run the request towards an embedded openejb
415 means "Method not supported", which happens when you send GET request to a PUT-expecting resource.
I would recommend to use POST instead of PUT in this case. I suspect that #FormParam is not suitable to work with PUT, in your particular case.

Coding an API: taking advantage of HTTP

I'm coding a json api over http (original, yes?), and I mostly ignore the http layer. Besides using POST and GET when applicable (rarely, another method), I do not use any kind of optimization the protocol may provide.
What am I missing? What headers could I be using, what could be simplified by tapping more into the http layer's capabilities?

WCF Rest - what are the best practices?

Just started my first WCF rest project and would like some help on what are the best practices for using REST.
I have seen a number of tutorials and there seems to be a number of ways to do things...for example if doing a POST, I have seen some tutorials which are setting HttpStatusCodes (OK/Errors etc), and other tutorials where they are just returning strings which contain result of the operation.
At the end of the day, there are 4 operations and surely there must be a guide that says if you are doing a GET, do it this way, etc and with a POST, do this...
Any help would be appreciated.
JD
UPDDATE
Use ASP.NET Web API.
OK I left the comment REST best practices: dont use WCF REST. Just avoid it like a plague and I feel like I have to explain it.
One of the fundamental flaws of the WCF is that it is concerned only with the Payload. For example Foo and Bar are the payloads here.
[OperationContract]
public Foo Do(Bar bar)
{
...
}
This is one of the tenants of WCF so that no matter what the transport is, we get the payload over to you.
But what it ignore is the context/envelope of the call which in many cases transport specific - so a lot of the context get's lost. In fact, HTTP's power lies in its context not payload and back in the earlier versions of WCF, there was no way to get the client's IP Address in netTcpBinding and WCF team were adamant that they cannot provide it. I cannot find the page now but remember reading the comments and the MS guys just said this is not supported.
Using WCF REST, you lose the flexibility of HTTP in expressing yourself clearly (and they had to budge it later) in terms of:
HTTP Status code
HTTP media types
ETag, ...
The new Web API, Glenn Block is working addresses this issue by encapsulating the payload in the context:
public HttpResponse<Foo> Do(HttpRequest<Bar> bar) // PSEUDOCODE
{
...
}
But to my test this is not perfect and I personally prefer to use frameworks such as Nancy or even plain ASP NET MVC to expose web API.
There are some basic rules when using the different HTTP verbs that come from the HTTP specification
GET: This is a pure read operation. Invocation must not cause state change in the service. The response to a GET may be delivered from cache (local, proxy, etc) depending on caching headers
DELETE: Used to delete a resource
There is sometimes some confusion around PUT and POST - which should be used when? To answer that you have to consider idempotency - whether the operation can be repeated without affecting service state - so for example setting a customer's name to a value can be repeated multiple times without further state change; however, if I am incrementing a customer's bank balance this cannot be safely be repeated without further state change on the service. The first is said to be idempotent the second is not
PUT: Non-delete state changes that are idempotent
POST: Non-delete state changes that are not idempotent
REST embraces HTTP - therefore failures should be communicated using HTTP status codes. 200 for success, 201 for creation and the service should return a URI for the new resource using the HTTP location header, 4xx are failures due to the nature of the client request (so can be fixed by the client changing what they are doing), 5xx are server errors that can only be resolved server side
There's something missing here that needs to be said.
WCF Rest may not be able to provide all functionality of REST protocol, but it is able to facilitate REST protocol for existing WCF services. So if you decide to provide some sort of REST support on top of the current SOAP/Named pipe protocol, it's the way to go if the ROI is low.
Hand rolling full blown REST protocol maybe ideal, but not always economical. In 90% of my projects, REST api is an afterthought. Wcf comes in quite handy in that regard.

Action mustUnderstand header someone please explain it

I've been trying to find a simple explanation on the web on this header.
What is its use?
When do we need it?
What does it do?
What does it mean?
and so on...
I know this is pretty simple but I've been looking for a well explained answer regarding this header online for more than an hour.
Action header describes what operation must be invoked on the service. MustUnderstand is general attribute for headers used in SOAP messages. Once header is marked with this attribute and either service or client doesn't have "handler" for that header (doesn't understand what to do with header) the processing should fail (should not must - for example intermediaries don't fail if they don't understand a header because the header doesn't have to be targeted to them). Once the Action header is used it is used together with MustUnderstand attribute.