/
DefaultSocket.java
346 lines (298 loc) · 12.3 KB
/
DefaultSocket.java
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*
* Copyright 2013 Jeanfrancois Arcand
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.wasync.impl;
import com.ning.http.client.AsyncHandler;
import com.ning.http.client.FluentStringsMap;
import com.ning.http.client.RequestBuilder;
import com.ning.http.client.websocket.WebSocket;
import org.atmosphere.wasync.Event;
import org.atmosphere.wasync.Function;
import org.atmosphere.wasync.FunctionWrapper;
import org.atmosphere.wasync.Future;
import org.atmosphere.wasync.Options;
import org.atmosphere.wasync.Request;
import org.atmosphere.wasync.Socket;
import org.atmosphere.wasync.Transport;
import org.atmosphere.wasync.transport.LongPollingTransport;
import org.atmosphere.wasync.transport.SSETransport;
import org.atmosphere.wasync.transport.StreamTransport;
import org.atmosphere.wasync.transport.TransportNotSupported;
import org.atmosphere.wasync.transport.WebSocketTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Default implementation of the {@link org.atmosphere.wasync.Socket}
*
* @author Jeanfrancois Arcand
*/
public class DefaultSocket implements Socket {
private final static Logger logger = LoggerFactory.getLogger(DefaultSocket.class);
protected Request request;
protected SocketRuntime socketRuntime;
protected final List<FunctionWrapper> functions = new ArrayList<FunctionWrapper>();
protected Transport transportInUse;
protected final Options options;
public DefaultSocket(Options options) {
this.options = options;
}
/**
* {@inheritDoc}
*/
@Override
public Future fire(Object data) throws IOException {
checkState();
if (transportInUse.status().equals(STATUS.CLOSE) ||
transportInUse.status().equals(STATUS.ERROR)) {
transportInUse.error(new IOException("Invalid Socket Status " + transportInUse.status().name()));
return socketRuntime.rootFuture;
}
return socketRuntime.write(request, data);
}
/**
* {@inheritDoc}
*/
@Override
public Socket on(Function<? extends Object> function) {
return on("", function);
}
/**
* {@inheritDoc}
*/
@Override
public Socket on(String functionName, Function<? extends Object> function) {
functions.add(new FunctionWrapper(functionName, function));
return this;
}
@Override
public Socket on(Event event, Function<?> function) {
return on(event.name(), function);
}
public Socket open(Request request) throws IOException {
return open(request, -1, TimeUnit.MILLISECONDS);
}
/**
* {@inheritDoc}
*/
@Override
public Socket open(Request request, long timeout, TimeUnit tu) throws IOException {
this.request = request;
RequestBuilder r = new RequestBuilder();
r.setUrl(request.uri())
.setMethod(request.method().name())
.setHeaders(request.headers())
.setQueryParameters(decodeQueryString(request));
List<Transport> transports = getTransport(r, request);
return connect(r, transports, timeout, tu);
}
static FluentStringsMap decodeQueryString(Request request) {
Map<String, List<String>> c = request.queryString();
FluentStringsMap f = new FluentStringsMap();
f.putAll(c);
return f;
}
protected Socket connect(final RequestBuilder r, final List<Transport> transports) throws IOException {
return connect(r, transports, -1, TimeUnit.MILLISECONDS);
}
protected Socket connect(final RequestBuilder r, final List<Transport> transports, final long timeout, final TimeUnit tu) throws IOException {
if (transports.size() > 0) {
transportInUse = transports.get(0);
} else {
throw new IOException("No suitable transport supported");
}
DefaultFuture f = new DefaultFuture(this);
socketRuntime = createRuntime(f, options, functions);
transportInUse.connectedFuture(f);
addFunction(timeout, tu);
if (transportInUse.name().equals(Request.TRANSPORT.WEBSOCKET)) {
r.setUrl(request.uri().replace("http", "ws"));
try {
java.util.concurrent.Future<WebSocket> fw = options.runtime().prepareRequest(r.build()).execute(
(AsyncHandler<WebSocket>) transportInUse);
fw.get(timeout, tu);
} catch (ExecutionException t) {
Throwable e = t.getCause();
if (TransportNotSupported.class.isAssignableFrom(e.getClass())) {
return this;
}
transportInUse.close();
closeRuntime(true);
if (!transportInUse.errorHandled() && TimeoutException.class.isAssignableFrom(e.getClass())) {
transportInUse.error(new IOException("Invalid state: " + e.getMessage()));
}
return new VoidSocket();
} catch (Throwable t) {
transportInUse.onThrowable(t);
return new VoidSocket();
}
} else {
r.setUrl(request.uri().replace("ws", "http"));
transportInUse.future(options.runtime().prepareRequest(r.build()).execute((AsyncHandler<String>) transportInUse));
try {
// TODO: Give a chance to connect and then unlock. With Atmosphere we will received junk at the
// beginning for streaming and sse, but nothing for long-polling
if (options.waitBeforeUnlocking() > 0) {
logger.info("Waiting {}, allowing the http connection to get handled by the server.", options.waitBeforeUnlocking());
}
if (request.queryString().containsKey("X-atmo-protocol")) {
f.get();
} else {
f.get(options.waitBeforeUnlocking(), TimeUnit.MILLISECONDS);
}
} catch (Throwable t) {
// Swallow LOG ME
logger.trace("", t);
} finally {
f.done();
}
}
return this;
}
protected void addFunction(final long timeout, final TimeUnit tu) {
functions.add(new FunctionWrapper("", new Function<TransportNotSupported>() {
@Override
public void on(TransportNotSupported transportNotSupported) {
request.transport().remove(0);
if (request.transport().size() > 0) {
try {
open(request, timeout, tu);
} catch (IOException e) {
logger.error("", e);
}
} else {
throw new Error("No suitable transport supported by the server");
}
}
}));
}
/**
* {@inheritDoc}
*/
@Override
public void close() {
// Not connected, but close the underlying AHC.
if (transportInUse == null) {
closeRuntime(false);
} else if (socketRuntime != null && !transportInUse.status().equals(STATUS.CLOSE)) {
transportInUse.close();
closeRuntime(true);
}
}
protected void closeRuntime(boolean async) {
if (!options.runtimeShared() && !options.runtime().isClosed()) {
if (async) {
// AHC is broken when calling closeAsynchronously.
// https://github.com/AsyncHttpClient/async-http-client/issues/290
final ExecutorService e= Executors.newSingleThreadExecutor();
e.submit(new Runnable() {
@Override
public void run() {
options.runtime().close();
e.shutdown();
}
});
}
else
options.runtime().close();
} else if (options.runtimeShared()) {
logger.warn("Cannot close underlying AsyncHttpClient because it is shared. Make sure you close it manually.");
}
}
@Override
public Socket.STATUS status() {
if (transportInUse == null) {
return STATUS.CLOSE;
} else {
return transportInUse.status();
}
}
protected SocketRuntime internalSocket() {
return socketRuntime;
}
protected List<Transport> getTransport(RequestBuilder r, Request request) throws IOException {
List<Transport> transports = new ArrayList<Transport>();
if (request.transport().size() == 0) {
transports.add(new WebSocketTransport(r, options, request, functions));
transports.add(new LongPollingTransport(r, options, request, functions));
}
for (Request.TRANSPORT t : request.transport()) {
if (t.equals(Request.TRANSPORT.WEBSOCKET)) {
transports.add(new WebSocketTransport(r, options, request, functions));
} else if (t.equals(Request.TRANSPORT.SSE)) {
transports.add(new SSETransport(r, options, request, functions));
} else if (t.equals(Request.TRANSPORT.LONG_POLLING)) {
transports.add(new LongPollingTransport(r, options, request, functions));
} else if (t.equals(Request.TRANSPORT.STREAMING)) {
transports.add(new StreamTransport(r, options, request, functions));
}
}
return transports;
}
protected Request request() {
return request;
}
private final static class VoidSocket implements Socket {
@Override
public Future fire(Object data) throws IOException {
throw new IllegalStateException("An error occurred during connection. Please add a Function(Throwable) to debug.");
}
@Override
public Socket on(Function<? extends Object> function) {
throw new IllegalStateException("An error occurred during connection. Please add a Function(Throwable) to debug.");
}
@Override
public Socket on(String functionMessage, Function<? extends Object> function) {
throw new IllegalStateException("An error occurred during connection. Please add a Function(Throwable) to debug.");
}
@Override
public Socket on(Event event, Function<?> function) {
throw new IllegalStateException("An error occurred during connection. Please add a Function(Throwable) to debug.");
}
@Override
public Socket open(Request request) throws IOException {
throw new IllegalStateException("An error occurred during connection. Please add a Function(Throwable) to debug.");
}
@Override
public void close() {
throw new IllegalStateException("An error occurred during connection. Please add a Function(Throwable) to debug.");
}
@Override
public STATUS status() {
return STATUS.ERROR;
}
@Override
public Socket open(Request request, long timeout, TimeUnit tu) throws IOException {
throw new IllegalStateException("An error occured during connection. Please add a Function(Throwable) to debug.");
}
}
void checkState() {
if (transportInUse == null) {
throw new IllegalStateException("Invalid Socket Status : Not Connected");
}
}
public SocketRuntime createRuntime(DefaultFuture future, Options options, List<FunctionWrapper> functions) {
return new SocketRuntime(transportInUse, options, future, functions);
}
}