users@jersey.java.net

Re: [Jersey] StreamingOutput, multipart and boundary parameter

From: Jan Algermissen <algermissen1971_at_mac.com>
Date: Thu, 01 Oct 2009 12:35:41 +0200

Paul,


On Oct 1, 2009, at 12:22 PM, Paul Sandoz wrote:

> Hi Jan,
>
> On Oct 1, 2009, at 11:57 AM, Jan Algermissen wrote:
>
>> Hi,
>>
>> I have to produce streaming output using multipart/mixed media type
>> and I seem to be unable to find out how I set the boundary
>> parameter. I would not want to make it part of the @Produces
>> annotation, but rather generate it at run time and add it to the
>> stream.
>>
>> Can someone point me to the docs how to do that?
>>
>
> You will need to modify the Content-Type value.
>
> Are you using a message body writer? if so you can modify the
> Content-Type of the http headers before any bytes are written. This
> is what Jersey's support for multipart does, see code below (but i
> am not sure it will support your streaming requirements).

No - that's why I cannot use the multipart support.


>
> If you are not using a message body writer you can set the media
> type in a returned Response instance e.g. if you are using an
> instance of StreamingOutput for the entity.
>
> Paul.
>
> // Determine the boundary string to be used, creating one if
> needed
> MediaType entityMediaType = (MediaType)
> headers.getFirst("Content-Type");
> if (entityMediaType == null) {
> Map<String, String> parameters = new HashMap<String,
> String>();
> parameters.put("boundary", createBoundary());
> entityMediaType = new MediaType("multipart", "mixed",
> parameters);
> headers.putSingle("Content-Type", entityMediaType);
> }
> String boundaryString =
> entityMediaType.getParameters().get("boundary");
> if (boundaryString == null) {
> boundaryString = createBoundary();
> Map<String, String> parameters = new HashMap<String,
> String>();
> parameters.putAll(entityMediaType.getParameters());
> parameters.put("boundary", boundaryString);
> entityMediaType = new MediaType(entityMediaType.getType(),
> entityMediaType.getSubtype(),
> parameters);
> headers.putSingle("Content-Type", entityMediaType);
> }
>

I think I will use a MessageBodyWriter but anyway, if I don't - where
would I put the code you sent? at the beginning of the write method?

         public StreamingOutput getResource(
                        @PathParam("id") String id
                ) {
                return new StreamingOutput() {
                public void write(OutputStream outputStream) {
                        // PUT CODE HERE???
                        PrintWriter out = new PrintWriter(outputStream);
                        out.println("Foo");
                        out.close();
                } };
        }

Thank you!

Jan