users@jersey.java.net

Re: [Jersey] StreamingOutput, multipart and boundary parameter

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Thu, 01 Oct 2009 12:44:51 +0200

On Oct 1, 2009, at 12:35 PM, Jan Algermissen wrote:
>
>
>>
>> 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();
> } };
> }
>

You could do:

  public Response getResource(...) {
     MediaType m = ... // create media type with boundary string

     StreamingOutput o = ...

     return Response.ok(o, m).build();
  }


Or:

        public StreamingOutput getResource(
                         final @Context HttpContext hc, // Jersey
specific class
                        @PathParam("id") String id
                ) {
                return new StreamingOutput() {
                public void write(OutputStream outputStream) {
                         // This will be null if there is no @Produces
                         MediaType ct = hc.getResponse().getMediaType();
                         // Set media type with boundary
                         MediaType ctWithBoundary = ...
                          
hc.getResponse().getHttpHeaders().put("Content-Type", ctWithBoundary);

                        PrintWriter out = new PrintWriter(outputStream);
                        out.println("Foo");
                        out.close();
                } };
        }

Paul.