users@jersey.java.net

Re: [Jersey] How to find out content-length *before* unmarshalling?

From: Tatu Saloranta <tsaloranta_at_gmail.com>
Date: Sun, 27 Dec 2009 22:01:30 -0800

On Sun, Dec 27, 2009 at 2:22 AM, Markus Karg <markus.karg_at_gmx.net> wrote:
> I need to find out the byte size (content-length) of a JAXB object (i. e.
> which content-length *would* be set *if i would* return it as the result of
> a JAX-RS method). I know that I could obtain the unmarshaller manually via
> the Providers interface, marshal the object and check the resulting size.
> But I wonder if there is some smarter way to do that?

As far as I know, not in general case. There may be limited number
special cases (for trivial types), but the general problem of
calculating length faster than actually serializing (or equivalent,
without writes) is difficult one. And especially so for xml, what with
namespace binding, character quoting, and even underlying UTF-8
encoding.

So I think simplest way is about the best: reuse a context, create
marshaller with a bogus output stream (one that only calculates number
of bytes that it has been requested to write, but does not store any
of it -- assuming you don't actually need the serialization).

-+ Tatu +-