1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.jetty.client.util;
20
21 import java.io.UnsupportedEncodingException;
22 import java.nio.ByteBuffer;
23 import java.nio.charset.UnsupportedCharsetException;
24 import java.util.Locale;
25
26 import org.eclipse.jetty.client.api.Response;
27 import org.eclipse.jetty.client.api.Result;
28 import org.eclipse.jetty.http.HttpFields;
29 import org.eclipse.jetty.http.HttpHeader;
30
31
32
33
34
35
36
37 public abstract class BufferingResponseListener extends Response.Listener.Empty
38 {
39 private final int maxLength;
40 private volatile byte[] buffer = new byte[0];
41 private volatile String encoding;
42
43
44
45
46 public BufferingResponseListener()
47 {
48 this(2 * 1024 * 1024);
49 }
50
51
52
53
54
55
56 public BufferingResponseListener(int maxLength)
57 {
58 this.maxLength = maxLength;
59 }
60
61 @Override
62 public void onHeaders(Response response)
63 {
64 HttpFields headers = response.getHeaders();
65 long length = headers.getLongField(HttpHeader.CONTENT_LENGTH.asString());
66 if (length > maxLength)
67 response.abort(new IllegalArgumentException("Buffering capacity exceeded"));
68
69 String contentType = headers.get(HttpHeader.CONTENT_TYPE);
70 if (contentType != null)
71 {
72 String charset = "charset=";
73 int index = contentType.toLowerCase(Locale.ENGLISH).indexOf(charset);
74 if (index > 0)
75 {
76 String encoding = contentType.substring(index + charset.length());
77
78 index = encoding.indexOf(';');
79 if (index > 0)
80 encoding = encoding.substring(0, index);
81 this.encoding = encoding;
82 }
83 }
84 }
85
86 @Override
87 public void onContent(Response response, ByteBuffer content)
88 {
89 long newLength = buffer.length + content.remaining();
90 if (newLength > maxLength)
91 response.abort(new IllegalArgumentException("Buffering capacity exceeded"));
92
93 byte[] newBuffer = new byte[(int)newLength];
94 System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
95 content.get(newBuffer, buffer.length, content.remaining());
96 buffer = newBuffer;
97 }
98
99 @Override
100 public abstract void onComplete(Result result);
101
102 public String getEncoding()
103 {
104 return encoding;
105 }
106
107
108
109
110
111 public byte[] getContent()
112 {
113 return buffer;
114 }
115
116
117
118
119
120
121 public String getContentAsString()
122 {
123 String encoding = this.encoding;
124 if (encoding == null)
125 encoding = "UTF-8";
126 return getContentAsString(encoding);
127 }
128
129
130
131
132
133
134 public String getContentAsString(String encoding)
135 {
136 try
137 {
138 return new String(getContent(), encoding);
139 }
140 catch (UnsupportedEncodingException x)
141 {
142 throw new UnsupportedCharsetException(encoding);
143 }
144 }
145 }