1
2
3
4
5
6
7
8
9
10
11 package org.mule.providers.http.transformers;
12
13 import org.mule.providers.http.HttpConstants;
14 import org.mule.providers.http.HttpResponse;
15 import org.mule.providers.http.ResponseWriter;
16 import org.mule.transformers.AbstractTransformer;
17 import org.mule.umo.transformer.TransformerException;
18
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.OutputStream;
22 import java.io.UnsupportedEncodingException;
23 import java.util.Iterator;
24
25 import org.apache.commons.httpclient.ChunkedOutputStream;
26 import org.apache.commons.httpclient.Header;
27 import org.apache.commons.io.IOUtils;
28 import org.apache.commons.io.output.ByteArrayOutputStream;
29
30
31
32
33
34 public class HttpResponseToString extends AbstractTransformer
35 {
36
37 public HttpResponseToString()
38 {
39 registerSourceType(HttpResponse.class);
40 setReturnClass(String.class);
41 }
42
43
44
45
46 protected Object doTransform(Object src, String encoding) throws TransformerException
47 {
48 try
49 {
50 HttpResponse response = (HttpResponse)src;
51 ByteArrayOutputStream bos = new ByteArrayOutputStream(8192);
52 OutputStream outstream = bos;
53 ResponseWriter writer = new ResponseWriter(outstream, encoding);
54 writer.println(response.getStatusLine());
55 Iterator item = response.getHeaderIterator();
56 while (item.hasNext())
57 {
58 Header header = (Header)item.next();
59 writer.print(header.toExternalForm());
60 }
61 writer.println();
62 writer.flush();
63
64 InputStream content = response.getBody();
65 if (content != null)
66 {
67 Header transferenc = response.getFirstHeader(HttpConstants.HEADER_TRANSFER_ENCODING);
68 if (transferenc != null)
69 {
70 response.removeHeaders(HttpConstants.HEADER_CONTENT_LENGTH);
71 if (transferenc.getValue().indexOf(HttpConstants.TRANSFER_ENCODING_CHUNKED) != -1)
72 {
73 outstream = new ChunkedOutputStream(outstream);
74 }
75 }
76
77 IOUtils.copy(content, outstream);
78
79 if (outstream instanceof ChunkedOutputStream)
80 {
81 ((ChunkedOutputStream)outstream).finish();
82 }
83 }
84
85 outstream.flush();
86 bos.flush();
87 byte[] result = bos.toByteArray();
88 outstream.close();
89 writer.close();
90 bos.close();
91
92 String output = null;
93 try
94 {
95 output = new String(result, encoding);
96 }
97 catch (UnsupportedEncodingException uee)
98 {
99
100
101
102 output = new String(result);
103 }
104
105 return output;
106 }
107 catch (IOException e)
108 {
109 throw new TransformerException(this, e);
110 }
111 }
112 }