author | prappo |
Wed, 08 Jun 2016 15:19:58 +0100 | |
changeset 38864 | bf2b41533aed |
parent 38856 | cc3a0d1e96e0 |
child 39133 | b5641ce64cf7 |
permissions | -rw-r--r-- |
37874 | 1 |
/* |
2 |
* Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. |
|
3 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
|
4 |
* |
|
5 |
* This code is free software; you can redistribute it and/or modify it |
|
6 |
* under the terms of the GNU General Public License version 2 only, as |
|
7 |
* published by the Free Software Foundation. Oracle designates this |
|
8 |
* particular file as subject to the "Classpath" exception as provided |
|
9 |
* by Oracle in the LICENSE file that accompanied this code. |
|
10 |
* |
|
11 |
* This code is distributed in the hope that it will be useful, but WITHOUT |
|
12 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
13 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
14 |
* version 2 for more details (a copy is included in the LICENSE file that |
|
15 |
* accompanied this code). |
|
16 |
* |
|
17 |
* You should have received a copy of the GNU General Public License version |
|
18 |
* 2 along with this work; if not, write to the Free Software Foundation, |
|
19 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
|
20 |
* |
|
21 |
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA |
|
22 |
* or visit www.oracle.com if you need additional information or have any |
|
23 |
* questions. |
|
24 |
*/ |
|
25 |
package java.net.http; |
|
26 |
||
27 |
import java.io.IOException; |
|
28 |
import java.net.ProtocolException; |
|
29 |
import java.net.http.WSOpeningHandshake.Result; |
|
30 |
import java.nio.ByteBuffer; |
|
31 |
import java.util.Optional; |
|
32 |
import java.util.concurrent.CompletableFuture; |
|
33 |
import java.util.concurrent.CompletionStage; |
|
34 |
import java.util.concurrent.Executor; |
|
35 |
import java.util.function.Consumer; |
|
36 |
import java.util.function.Supplier; |
|
37 |
import java.util.stream.Stream; |
|
38 |
||
39 |
import static java.lang.System.Logger.Level.ERROR; |
|
40 |
import static java.lang.System.Logger.Level.WARNING; |
|
41 |
import static java.net.http.WSUtils.logger; |
|
42 |
import static java.util.Objects.requireNonNull; |
|
43 |
||
44 |
/* |
|
45 |
* A WebSocket client. |
|
46 |
* |
|
47 |
* Consists of two independent parts; a transmitter responsible for sending |
|
48 |
* messages, and a receiver which notifies the listener of incoming messages. |
|
49 |
*/ |
|
50 |
final class WS implements WebSocket { |
|
51 |
||
52 |
private final String subprotocol; |
|
53 |
private final RawChannel channel; |
|
54 |
private final WSTransmitter transmitter; |
|
55 |
private final WSReceiver receiver; |
|
56 |
private final Listener listener; |
|
57 |
private final Object stateLock = new Object(); |
|
58 |
private volatile State state = State.CONNECTED; |
|
59 |
private final CompletableFuture<Void> whenClosed = new CompletableFuture<>(); |
|
60 |
||
61 |
static CompletableFuture<WebSocket> newInstanceAsync(WSBuilder b) { |
|
62 |
CompletableFuture<Result> result = new WSOpeningHandshake(b).performAsync(); |
|
63 |
Listener listener = b.getListener(); |
|
64 |
Executor executor = b.getClient().executorService(); |
|
65 |
return result.thenApply(r -> { |
|
66 |
WS ws = new WS(listener, r.subprotocol, r.channel, executor); |
|
67 |
ws.start(); |
|
68 |
return ws; |
|
69 |
}); |
|
70 |
} |
|
71 |
||
72 |
private WS(Listener listener, String subprotocol, RawChannel channel, |
|
73 |
Executor executor) { |
|
74 |
this.listener = wrapListener(listener); |
|
75 |
this.channel = channel; |
|
76 |
this.subprotocol = subprotocol; |
|
77 |
Consumer<Throwable> errorHandler = error -> { |
|
78 |
if (error == null) { |
|
79 |
throw new InternalError(); |
|
80 |
} |
|
81 |
// If the channel is closed, we need to update the state, to denote |
|
82 |
// there's no point in trying to continue using WebSocket |
|
83 |
if (!channel.isOpen()) { |
|
84 |
synchronized (stateLock) { |
|
85 |
tryChangeState(State.ERROR); |
|
86 |
} |
|
87 |
} |
|
88 |
}; |
|
38864
bf2b41533aed
8156693: Improve usability of CompletableFuture use in WebSocket API
prappo
parents:
38856
diff
changeset
|
89 |
transmitter = new WSTransmitter(this, executor, channel, errorHandler); |
37874 | 90 |
receiver = new WSReceiver(this.listener, this, executor, channel); |
91 |
} |
|
92 |
||
93 |
private void start() { |
|
94 |
receiver.start(); |
|
95 |
} |
|
96 |
||
97 |
@Override |
|
38864
bf2b41533aed
8156693: Improve usability of CompletableFuture use in WebSocket API
prappo
parents:
38856
diff
changeset
|
98 |
public CompletableFuture<WebSocket> sendText(CharSequence message, boolean isLast) { |
37874 | 99 |
requireNonNull(message, "message"); |
100 |
synchronized (stateLock) { |
|
101 |
checkState(); |
|
102 |
return transmitter.sendText(message, isLast); |
|
103 |
} |
|
104 |
} |
|
105 |
||
106 |
@Override |
|
38864
bf2b41533aed
8156693: Improve usability of CompletableFuture use in WebSocket API
prappo
parents:
38856
diff
changeset
|
107 |
public CompletableFuture<WebSocket> sendText(Stream<? extends CharSequence> message) { |
37874 | 108 |
requireNonNull(message, "message"); |
109 |
synchronized (stateLock) { |
|
110 |
checkState(); |
|
111 |
return transmitter.sendText(message); |
|
112 |
} |
|
113 |
} |
|
114 |
||
115 |
@Override |
|
38864
bf2b41533aed
8156693: Improve usability of CompletableFuture use in WebSocket API
prappo
parents:
38856
diff
changeset
|
116 |
public CompletableFuture<WebSocket> sendBinary(ByteBuffer message, boolean isLast) { |
37874 | 117 |
requireNonNull(message, "message"); |
118 |
synchronized (stateLock) { |
|
119 |
checkState(); |
|
120 |
return transmitter.sendBinary(message, isLast); |
|
121 |
} |
|
122 |
} |
|
123 |
||
124 |
@Override |
|
38864
bf2b41533aed
8156693: Improve usability of CompletableFuture use in WebSocket API
prappo
parents:
38856
diff
changeset
|
125 |
public CompletableFuture<WebSocket> sendPing(ByteBuffer message) { |
37874 | 126 |
requireNonNull(message, "message"); |
127 |
synchronized (stateLock) { |
|
128 |
checkState(); |
|
129 |
return transmitter.sendPing(message); |
|
130 |
} |
|
131 |
} |
|
132 |
||
133 |
@Override |
|
38864
bf2b41533aed
8156693: Improve usability of CompletableFuture use in WebSocket API
prappo
parents:
38856
diff
changeset
|
134 |
public CompletableFuture<WebSocket> sendPong(ByteBuffer message) { |
37874 | 135 |
requireNonNull(message, "message"); |
136 |
synchronized (stateLock) { |
|
137 |
checkState(); |
|
138 |
return transmitter.sendPong(message); |
|
139 |
} |
|
140 |
} |
|
141 |
||
142 |
@Override |
|
38864
bf2b41533aed
8156693: Improve usability of CompletableFuture use in WebSocket API
prappo
parents:
38856
diff
changeset
|
143 |
public CompletableFuture<WebSocket> sendClose(CloseCode code, CharSequence reason) { |
37874 | 144 |
requireNonNull(code, "code"); |
145 |
requireNonNull(reason, "reason"); |
|
146 |
synchronized (stateLock) { |
|
147 |
return doSendClose(() -> transmitter.sendClose(code, reason)); |
|
148 |
} |
|
149 |
} |
|
150 |
||
151 |
@Override |
|
38864
bf2b41533aed
8156693: Improve usability of CompletableFuture use in WebSocket API
prappo
parents:
38856
diff
changeset
|
152 |
public CompletableFuture<WebSocket> sendClose() { |
37874 | 153 |
synchronized (stateLock) { |
154 |
return doSendClose(() -> transmitter.sendClose()); |
|
155 |
} |
|
156 |
} |
|
157 |
||
38864
bf2b41533aed
8156693: Improve usability of CompletableFuture use in WebSocket API
prappo
parents:
38856
diff
changeset
|
158 |
private CompletableFuture<WebSocket> doSendClose(Supplier<CompletableFuture<WebSocket>> s) { |
37874 | 159 |
checkState(); |
160 |
boolean closeChannel = false; |
|
161 |
synchronized (stateLock) { |
|
162 |
if (state == State.CLOSED_REMOTELY) { |
|
163 |
closeChannel = tryChangeState(State.CLOSED); |
|
164 |
} else { |
|
165 |
tryChangeState(State.CLOSED_LOCALLY); |
|
166 |
} |
|
167 |
} |
|
38864
bf2b41533aed
8156693: Improve usability of CompletableFuture use in WebSocket API
prappo
parents:
38856
diff
changeset
|
168 |
CompletableFuture<WebSocket> sent = s.get(); |
37874 | 169 |
if (closeChannel) { |
170 |
sent.whenComplete((v, t) -> { |
|
171 |
try { |
|
172 |
channel.close(); |
|
173 |
} catch (IOException e) { |
|
174 |
logger.log(ERROR, "Error transitioning to state " + State.CLOSED, e); |
|
175 |
} |
|
176 |
}); |
|
177 |
} |
|
178 |
return sent; |
|
179 |
} |
|
180 |
||
181 |
@Override |
|
182 |
public long request(long n) { |
|
183 |
if (n < 0L) { |
|
184 |
throw new IllegalArgumentException("The number must not be negative: " + n); |
|
185 |
} |
|
186 |
return receiver.request(n); |
|
187 |
} |
|
188 |
||
189 |
@Override |
|
190 |
public String getSubprotocol() { |
|
191 |
return subprotocol; |
|
192 |
} |
|
193 |
||
194 |
@Override |
|
195 |
public boolean isClosed() { |
|
196 |
return state.isTerminal(); |
|
197 |
} |
|
198 |
||
199 |
@Override |
|
200 |
public void abort() throws IOException { |
|
201 |
synchronized (stateLock) { |
|
202 |
tryChangeState(State.ABORTED); |
|
203 |
} |
|
204 |
channel.close(); |
|
205 |
} |
|
206 |
||
207 |
@Override |
|
208 |
public String toString() { |
|
209 |
return super.toString() + "[" + state + "]"; |
|
210 |
} |
|
211 |
||
212 |
private void checkState() { |
|
213 |
if (state.isTerminal() || state == State.CLOSED_LOCALLY) { |
|
214 |
throw new IllegalStateException("WebSocket is closed [" + state + "]"); |
|
215 |
} |
|
216 |
} |
|
217 |
||
218 |
/* |
|
219 |
* Wraps the user's listener passed to the constructor into own listener to |
|
220 |
* intercept transitions to terminal states (onClose and onError) and to act |
|
221 |
* upon exceptions and values from the user's listener. |
|
222 |
*/ |
|
223 |
private Listener wrapListener(Listener listener) { |
|
224 |
return new Listener() { |
|
225 |
||
226 |
// Listener's method MUST be invoked in a happen-before order |
|
227 |
private final Object visibilityLock = new Object(); |
|
228 |
||
229 |
@Override |
|
230 |
public void onOpen(WebSocket webSocket) { |
|
231 |
synchronized (visibilityLock) { |
|
232 |
listener.onOpen(webSocket); |
|
233 |
} |
|
234 |
} |
|
235 |
||
236 |
@Override |
|
38856
cc3a0d1e96e0
8156650: Simplify Text message support in WebSocket API
prappo
parents:
37874
diff
changeset
|
237 |
public CompletionStage<?> onText(WebSocket webSocket, CharSequence message, |
37874 | 238 |
MessagePart part) { |
239 |
synchronized (visibilityLock) { |
|
240 |
return listener.onText(webSocket, message, part); |
|
241 |
} |
|
242 |
} |
|
243 |
||
244 |
@Override |
|
245 |
public CompletionStage<?> onBinary(WebSocket webSocket, ByteBuffer message, |
|
246 |
MessagePart part) { |
|
247 |
synchronized (visibilityLock) { |
|
248 |
return listener.onBinary(webSocket, message, part); |
|
249 |
} |
|
250 |
} |
|
251 |
||
252 |
@Override |
|
253 |
public CompletionStage<?> onPing(WebSocket webSocket, ByteBuffer message) { |
|
254 |
synchronized (visibilityLock) { |
|
255 |
return listener.onPing(webSocket, message); |
|
256 |
} |
|
257 |
} |
|
258 |
||
259 |
@Override |
|
260 |
public CompletionStage<?> onPong(WebSocket webSocket, ByteBuffer message) { |
|
261 |
synchronized (visibilityLock) { |
|
262 |
return listener.onPong(webSocket, message); |
|
263 |
} |
|
264 |
} |
|
265 |
||
266 |
@Override |
|
267 |
public void onClose(WebSocket webSocket, Optional<CloseCode> code, String reason) { |
|
268 |
synchronized (stateLock) { |
|
269 |
if (state == State.CLOSED_REMOTELY || state.isTerminal()) { |
|
270 |
throw new InternalError("Unexpected onClose in state " + state); |
|
271 |
} else if (state == State.CLOSED_LOCALLY) { |
|
272 |
try { |
|
273 |
channel.close(); |
|
274 |
} catch (IOException e) { |
|
275 |
logger.log(ERROR, "Error transitioning to state " + State.CLOSED, e); |
|
276 |
} |
|
277 |
tryChangeState(State.CLOSED); |
|
278 |
} else if (state == State.CONNECTED) { |
|
279 |
tryChangeState(State.CLOSED_REMOTELY); |
|
280 |
} |
|
281 |
} |
|
282 |
synchronized (visibilityLock) { |
|
283 |
listener.onClose(webSocket, code, reason); |
|
284 |
} |
|
285 |
} |
|
286 |
||
287 |
@Override |
|
288 |
public void onError(WebSocket webSocket, Throwable error) { |
|
289 |
// An error doesn't necessarily mean the connection must be |
|
290 |
// closed automatically |
|
291 |
if (!channel.isOpen()) { |
|
292 |
synchronized (stateLock) { |
|
293 |
tryChangeState(State.ERROR); |
|
294 |
} |
|
295 |
} else if (error instanceof ProtocolException |
|
296 |
&& error.getCause() instanceof WSProtocolException) { |
|
297 |
WSProtocolException cause = (WSProtocolException) error.getCause(); |
|
298 |
logger.log(WARNING, "Failing connection {0}, reason: ''{1}''", |
|
299 |
webSocket, cause.getMessage()); |
|
300 |
CloseCode cc = cause.getCloseCode(); |
|
301 |
transmitter.sendClose(cc, "").whenComplete((v, t) -> { |
|
302 |
synchronized (stateLock) { |
|
303 |
tryChangeState(State.ERROR); |
|
304 |
} |
|
305 |
try { |
|
306 |
channel.close(); |
|
307 |
} catch (IOException e) { |
|
308 |
logger.log(ERROR, e); |
|
309 |
} |
|
310 |
}); |
|
311 |
} |
|
312 |
synchronized (visibilityLock) { |
|
313 |
listener.onError(webSocket, error); |
|
314 |
} |
|
315 |
} |
|
316 |
}; |
|
317 |
} |
|
318 |
||
319 |
private boolean tryChangeState(State newState) { |
|
320 |
assert Thread.holdsLock(stateLock); |
|
321 |
if (state.isTerminal()) { |
|
322 |
return false; |
|
323 |
} |
|
324 |
state = newState; |
|
325 |
if (newState.isTerminal()) { |
|
326 |
whenClosed.complete(null); |
|
327 |
} |
|
328 |
return true; |
|
329 |
} |
|
330 |
||
331 |
CompletionStage<Void> whenClosed() { |
|
332 |
return whenClosed; |
|
333 |
} |
|
334 |
||
335 |
/* |
|
336 |
* WebSocket connection internal state. |
|
337 |
*/ |
|
338 |
private enum State { |
|
339 |
||
340 |
/* |
|
341 |
* Initial WebSocket state. The WebSocket is connected (i.e. remains in |
|
342 |
* this state) unless proven otherwise. For example, by reading or |
|
343 |
* writing operations on the channel. |
|
344 |
*/ |
|
345 |
CONNECTED, |
|
346 |
||
347 |
/* |
|
348 |
* A Close message has been received by the client. No more messages |
|
349 |
* will be received. |
|
350 |
*/ |
|
351 |
CLOSED_REMOTELY, |
|
352 |
||
353 |
/* |
|
354 |
* A Close message has been sent by the client. No more messages can be |
|
355 |
* sent. |
|
356 |
*/ |
|
357 |
CLOSED_LOCALLY, |
|
358 |
||
359 |
/* |
|
360 |
* Close messages has been both sent and received (closing handshake) |
|
361 |
* and TCP connection closed. Closed _cleanly_ in terms of RFC 6455. |
|
362 |
*/ |
|
363 |
CLOSED, |
|
364 |
||
365 |
/* |
|
366 |
* The connection has been aborted by the client. Closed not _cleanly_ |
|
367 |
* in terms of RFC 6455. |
|
368 |
*/ |
|
369 |
ABORTED, |
|
370 |
||
371 |
/* |
|
372 |
* The connection has been terminated due to a protocol or I/O error. |
|
373 |
* Might happen during sending or receiving. |
|
374 |
*/ |
|
375 |
ERROR; |
|
376 |
||
377 |
/* |
|
378 |
* Returns `true` if this state is terminal. If WebSocket has transited |
|
379 |
* to such a state, if remains in it forever. |
|
380 |
*/ |
|
381 |
boolean isTerminal() { |
|
382 |
return this == CLOSED || this == ABORTED || this == ERROR; |
|
383 |
} |
|
384 |
} |
|
385 |
} |