-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathPollingXHR.java
More file actions
269 lines (230 loc) · 9.09 KB
/
PollingXHR.java
File metadata and controls
269 lines (230 loc) · 9.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package io.socket.engineio.client.transports;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import io.socket.emitter.Emitter;
import io.socket.engineio.client.Transport;
import io.socket.thread.EventThread;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class PollingXHR extends Polling {
private static final Logger logger = Logger.getLogger(PollingXHR.class.getName());
private static boolean LOGGABLE_FINE = logger.isLoggable(Level.FINE);
public PollingXHR(Transport.Options opts) {
super(opts);
}
protected Request request() {
return this.request(null);
}
protected Request request(Request.Options opts) {
if (opts == null) {
opts = new Request.Options();
}
opts.uri = this.uri();
opts.callFactory = this.callFactory;
opts.extraHeaders = this.extraHeaders;
Request req = new Request(opts);
final PollingXHR self = this;
req.on(Request.EVENT_REQUEST_HEADERS, new Emitter.Listener() {
@Override
public void call(Object... args) {
// Never execute asynchronously for support to modify headers.
self.emit(Transport.EVENT_REQUEST_HEADERS, args[0]);
}
}).on(Request.EVENT_RESPONSE_HEADERS, new Emitter.Listener() {
@Override
public void call(final Object... args) {
EventThread.exec(new Runnable() {
@Override
public void run() {
self.emit(Transport.EVENT_RESPONSE_HEADERS, args[0]);
}
});
}
});
return req;
}
@Override
protected void doWrite(String data, final Runnable fn) {
Request.Options opts = new Request.Options();
opts.method = "POST";
opts.data = data;
opts.extraHeaders = this.extraHeaders;
Request req = this.request(opts);
final PollingXHR self = this;
req.on(Request.EVENT_SUCCESS, new Emitter.Listener() {
@Override
public void call(Object... args) {
EventThread.exec(new Runnable() {
@Override
public void run() {
fn.run();
}
});
}
});
req.on(Request.EVENT_ERROR, new Emitter.Listener() {
@Override
public void call(final Object... args) {
EventThread.exec(new Runnable() {
@Override
public void run() {
Exception err = args.length > 0 && args[0] instanceof Exception ? (Exception)args[0] : null;
self.onError("xhr post error", err);
}
});
}
});
req.create();
}
@Override
protected void doPoll() {
logger.fine("xhr poll");
Request req = this.request();
final PollingXHR self = this;
req.on(Request.EVENT_DATA, new Emitter.Listener() {
@Override
public void call(final Object... args) {
EventThread.exec(new Runnable() {
@Override
public void run() {
Object arg = args.length > 0 ? args[0] : null;
self.onData((String)arg);
}
});
}
});
req.on(Request.EVENT_ERROR, new Emitter.Listener() {
@Override
public void call(final Object... args) {
EventThread.exec(new Runnable() {
@Override
public void run() {
Exception err = args.length > 0 && args[0] instanceof Exception ? (Exception) args[0] : null;
self.onError("xhr poll error", err);
}
});
}
});
req.create();
}
public static class Request extends Emitter {
public static final String EVENT_SUCCESS = "success";
public static final String EVENT_DATA = "data";
public static final String EVENT_ERROR = "error";
public static final String EVENT_REQUEST_HEADERS = "requestHeaders";
public static final String EVENT_RESPONSE_HEADERS = "responseHeaders";
private static final String TEXT_CONTENT_TYPE = "text/plain;charset=UTF-8";
private static final MediaType TEXT_MEDIA_TYPE = MediaType.parse(TEXT_CONTENT_TYPE);
private String method;
private String uri;
private String data;
private Call.Factory callFactory;
private Map<String, List<String>> extraHeaders;
private Response response;
private Call requestCall;
public Request(Options opts) {
this.method = opts.method != null ? opts.method : "GET";
this.uri = opts.uri;
this.data = opts.data;
this.callFactory = opts.callFactory;
this.extraHeaders = opts.extraHeaders;
}
public void create() {
final Request self = this;
if (LOGGABLE_FINE) logger.fine(String.format("xhr open %s: %s", this.method, this.uri));
Map<String, List<String>> headers = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
if (this.extraHeaders != null) {
headers.putAll(this.extraHeaders);
}
if ("POST".equals(this.method)) {
headers.put("Content-type", new LinkedList<String>(Collections.singletonList(TEXT_CONTENT_TYPE)));
}
headers.put("Accept", new LinkedList<String>(Collections.singletonList("*/*")));
this.onRequestHeaders(headers);
if (LOGGABLE_FINE) {
logger.fine(String.format("sending xhr with url %s | data %s", this.uri, this.data));
}
okhttp3.Request.Builder requestBuilder = new okhttp3.Request.Builder();
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
for (String v : header.getValue()){
requestBuilder.addHeader(header.getKey(), v);
}
}
RequestBody body = null;
if (this.data != null) {
body = RequestBody.create(TEXT_MEDIA_TYPE, this.data);
}
okhttp3.Request request = requestBuilder
.url(HttpUrl.parse(self.uri))
.method(self.method, body)
.build();
requestCall = callFactory.newCall(request);
requestCall.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
logger.severe("PollingXHR: HTTP request failed: " + e.getMessage());
self.onError(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
self.response = response;
self.onResponseHeaders(response.headers().toMultimap());
try {
if (response.isSuccessful()) {
self.onLoad();
} else {
logger.severe("PollingXHR: HTTP response failed: " + response.code() + " " + response.message());
self.onError(new IOException(Integer.toString(response.code())));
}
} finally {
response.close();
}
}
});
}
private void onSuccess() {
this.emit(EVENT_SUCCESS);
}
private void onData(String data) {
this.emit(EVENT_DATA, data);
this.onSuccess();
}
private void onError(Exception err) {
this.emit(EVENT_ERROR, err);
}
private void onRequestHeaders(Map<String, List<String>> headers) {
this.emit(EVENT_REQUEST_HEADERS, headers);
}
private void onResponseHeaders(Map<String, List<String>> headers) {
this.emit(EVENT_RESPONSE_HEADERS, headers);
}
private void onLoad() {
ResponseBody body = response.body();
try {
String responseData = body.string();
this.onData(responseData);
} catch (IOException e) {
logger.severe("PollingXHR: Error reading response body: " + e.getMessage());
this.onError(e);
}
}
public static class Options {
public String uri;
public String method;
public String data;
public Call.Factory callFactory;
public Map<String, List<String>> extraHeaders;
}
}
}