View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.module.jersey;
8   
9   import org.mule.api.MuleEvent;
10  import org.mule.api.MuleMessage;
11  import org.mule.api.transport.OutputHandler;
12  import org.mule.module.jersey.JerseyResourcesComponent;
13  import org.mule.transport.http.HttpConnector;
14  
15  import com.sun.jersey.spi.container.ContainerResponse;
16  import com.sun.jersey.spi.container.ContainerResponseWriter;
17  
18  import java.io.ByteArrayOutputStream;
19  import java.io.IOException;
20  import java.io.OutputStream;
21  import java.util.HashMap;
22  import java.util.List;
23  import java.util.Map;
24  
25  public class MuleResponseWriter implements ContainerResponseWriter
26  {
27  
28      private ByteArrayOutputStream out;
29      private OutputHandler output;
30      private final MuleMessage message;
31  
32      public MuleResponseWriter(MuleMessage request)
33      {
34          super();
35          this.message = request;
36          this.out = new ByteArrayOutputStream();
37          this.output = new OutputHandler()
38          {
39  
40              public void write(MuleEvent arg0, OutputStream realOut) throws IOException
41              {
42                  realOut.write(out.toByteArray());
43                  realOut.flush();
44              }
45  
46          };
47      }
48  
49      public OutputStream writeStatusAndHeaders(long x, ContainerResponse response) throws IOException
50      {
51          Map<String, String> customHeaders = new HashMap<String, String>();
52          for (Map.Entry<String, List<Object>> e : response.getHttpHeaders().entrySet())
53          {
54                // TODO: is this correct?
55                message.setOutboundProperty(e.getKey(), getHeaderValue(e.getValue()));
56          }
57  
58          message.setInvocationProperty(JerseyResourcesComponent.JERSEY_RESPONSE, response);
59          message.setOutboundProperty(HttpConnector.HTTP_STATUS_PROPERTY, response.getStatus());
60  
61          return out;
62      }
63  
64      private String getHeaderValue(List<Object> values)
65      {
66          StringBuilder sb = new StringBuilder();
67          boolean first = true;
68          for (Object o : values)
69          {
70              if (!first)
71              {
72                  sb.append(", ");
73              }
74              else
75              {
76                  first = false;
77              }
78  
79              sb.append(ContainerResponse.getHeaderValue(o));
80          }
81          return sb.toString();
82      }
83  
84      public void finish() throws IOException
85      {
86      }
87  
88      public OutputHandler getResponse()
89      {
90          return output;
91      }
92  }