users@jersey.java.net

[Jersey] Re: content-length

From: Tatu Saloranta <tsaloranta_at_gmail.com>
Date: Wed, 9 May 2012 08:58:16 -0700

On Wed, May 9, 2012 at 12:59 AM, Pavel Bucek <pavel.bucek_at_oracle.com> wrote:
> Hello Matt,
>
> built in MessageBodyWriters for JAXB annotated types do not set content
> length. Why? There is no simple way how to get this info prior
> serialization, so all these providers are returning "-1" in getSize(...)
> method implementation.
>
> If you need this information in your response, you'll need to implement your
> own MessageBodyWriter which would perform serialization during getSize(...)
> call and cache result and use it in writeTo(...) method. This is not usable
> for streamed XML and not practical for types with large XML representation
> (well, depends on how much memory do you have) but might be ok for your
> case.

This is true in general case. I have been thinking about one thing, however:
given that in most cases it makes sense to add bit of buffering anyway
(for efficiency of underlying protocol etc), it should not be too hard
to implement something where 2 modes would be used:

(a) If all content fits in the buffer (of 8kB or 16kB), Content-Length
is available, and can be written as the last header before flushing
buffer
(b) Otherwise, length of -1 should be returned before flushing and
chunked operation.

This would obviously not guarantee length, but since many use cases
have rather short messages, would cover large amount of responses for
many use cases.

Not sure how useful it'd be, but I know that from client perspective
existence of Content-Length does allow some useful optimizations (I am
building a clustered service and it is one reason why I implement
something like above for my basic 'raw' GET operations)

-+ Tatu +-