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 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.tomcat.websocket;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.websocket.DeploymentException;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
import javax.websocket.RemoteEndpoint;
import javax.websocket.SendHandler;
import javax.websocket.SendResult;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.buf.Utf8Encoder;
import org.apache.tomcat.util.res.StringManager;
public abstract class WsRemoteEndpointImplBase implements RemoteEndpoint {
private static final StringManager sm =
StringManager.getManager(Constants.PACKAGE_NAME);
// Milliseconds so this is 20 seconds
private static final long DEFAULT_BLOCKING_SEND_TIMEOUT = 20 * 1000;
public static final String BLOCKING_SEND_TIMEOUT_PROPERTY =
"org.apache.tomcat.websocket.BLOCKING_SEND_TIMEOUT";
private final Log log = LogFactory.getLog(WsRemoteEndpointImplBase.class);
private final StateMachine stateMachine = new StateMachine();
private final IntermediateMessageHandler intermediateMessageHandler =
new IntermediateMessageHandler(this);
private Transformation transformation = null;
private boolean messagePartInProgress = false;
private final Queue<MessagePart> messagePartQueue = new ArrayDeque<MessagePart>();
private final Object messagePartLock = new Object();
// State
private volatile boolean closed = false;
private boolean fragmented = false;
private boolean nextFragmented = false;
private boolean text = false;
private boolean nextText = false;
// Max size of WebSocket header is 14 bytes
private final ByteBuffer headerBuffer = ByteBuffer.allocate(14);
private final ByteBuffer outputBuffer = ByteBuffer.allocate(8192);
private final CharsetEncoder encoder = new Utf8Encoder();
private final ByteBuffer encoderBuffer = ByteBuffer.allocate(8192);
private final AtomicBoolean batchingAllowed = new AtomicBoolean(false);
private volatile long sendTimeout = -1;
private WsSession wsSession;
private List<EncoderEntry> encoderEntries = new ArrayList<EncoderEntry>();
protected void setTransformation(Transformation transformation) {
this.transformation = transformation;
}
public long getSendTimeout() {
return sendTimeout;
}
public void setSendTimeout(long timeout) {
this.sendTimeout = timeout;
}
@Override
public void setBatchingAllowed(boolean batchingAllowed) throws IOException {
boolean oldValue = this.batchingAllowed.getAndSet(batchingAllowed);
if (oldValue && !batchingAllowed) {
flushBatch();
}
}
@Override
public boolean getBatchingAllowed() {
return batchingAllowed.get();
}
@Override
public void flushBatch() throws IOException {
startMessageBlock(Constants.INTERNAL_OPCODE_FLUSH, null, true);
}
public void sendBytes(ByteBuffer data) throws IOException {
stateMachine.binaryStart();
startMessageBlock(Constants.OPCODE_BINARY, data, true);
stateMachine.complete(true);
}
public Future<Void> sendBytesByFuture(ByteBuffer data) {
FutureToSendHandler f2sh = new FutureToSendHandler(wsSession);
sendBytesByCompletion(data, f2sh);
return f2sh;
}
public void sendBytesByCompletion(ByteBuffer data, SendHandler handler) {
StateUpdateSendHandler sush = new StateUpdateSendHandler(handler);
stateMachine.binaryStart();
startMessage(Constants.OPCODE_BINARY, data, true, sush);
}
public void sendPartialBytes(ByteBuffer partialByte, boolean last)
throws IOException {
stateMachine.binaryPartialStart();
startMessageBlock(Constants.OPCODE_BINARY, partialByte, last);
stateMachine.complete(last);
}
@Override
public void sendPing(ByteBuffer applicationData) throws IOException,
IllegalArgumentException {
startMessageBlock(Constants.OPCODE_PING, applicationData, true);
}
@Override
public void sendPong(ByteBuffer applicationData) throws IOException,
IllegalArgumentException {
startMessageBlock(Constants.OPCODE_PONG, applicationData, true);
}
public void sendString(String text) throws IOException {
stateMachine.textStart();
sendPartialString(CharBuffer.wrap(text), true);
}
public Future<Void> sendStringByFuture(String text) {
FutureToSendHandler f2sh = new FutureToSendHandler(wsSession);
sendStringByCompletion(text, f2sh);
return f2sh;
}
public void sendStringByCompletion(String text, SendHandler handler) {
stateMachine.textStart();
TextMessageSendHandler tmsh = new TextMessageSendHandler(handler,
CharBuffer.wrap(text), true, encoder, encoderBuffer, this);
tmsh.write();
// TextMessageSendHandler will update stateMachine when it completes
}
public void sendPartialString(String fragment, boolean isLast)
throws IOException {
stateMachine.textPartialStart();
sendPartialString(CharBuffer.wrap(fragment), isLast);
}
public OutputStream getSendStream() {
stateMachine.streamStart();
return new WsOutputStream(this);
}
public Writer getSendWriter() {
stateMachine.writeStart();
return new WsWriter(this);
}
void sendPartialString(CharBuffer part, boolean last) throws IOException {
try {
// Get the timeout before we send the message. The message may
// trigger a session close and depending on timing the client
// session may close before we can read the timeout.
long timeout = getBlockingSendTimeout();
FutureToSendHandler f2sh = new FutureToSendHandler(wsSession);
TextMessageSendHandler tmsh = new TextMessageSendHandler(f2sh, part,
last, encoder, encoderBuffer, this);
tmsh.write();
if (timeout == -1) {
f2sh.get();
} else {
f2sh.get(timeout, TimeUnit.MILLISECONDS);
}
} catch (InterruptedException e) {
throw new IOException(e);
} catch (ExecutionException e) {
throw new IOException(e);
} catch (TimeoutException e) {
throw new IOException(e);
}
}
void startMessageBlock(byte opCode, ByteBuffer payload, boolean last)
throws IOException {
// Get the timeout before we send the message. The message may
// trigger a session close and depending on timing the client
// session may close before we can read the timeout.
long timeout = getBlockingSendTimeout();
FutureToSendHandler f2sh = new FutureToSendHandler(wsSession);
startMessage(opCode, payload, last, f2sh);
try {
if (timeout == -1) {
f2sh.get();
} else {
f2sh.get(timeout, TimeUnit.MILLISECONDS);
}
} catch (InterruptedException e) {
throw new IOException(e);
} catch (ExecutionException e) {
throw new IOException(e);
} catch (TimeoutException e) {
throw new IOException(e);
}
}
void startMessage(byte opCode, ByteBuffer payload, boolean last,
SendHandler handler) {
wsSession.updateLastActive();
List<MessagePart> messageParts = new ArrayList<MessagePart>();
messageParts.add(new MessagePart(last, 0, opCode, payload,
intermediateMessageHandler,
new EndMessageHandler(this, handler)));
messageParts = transformation.sendMessagePart(messageParts);
// Some extensions/transformations may buffer messages so it is possible
// that no message parts will be returned. If this is the case the
// trigger the suppler SendHandler
if (messageParts.size() == 0) {
handler.onResult(new SendResult());
return;
}
MessagePart mp = messageParts.remove(0);
boolean doWrite = false;
synchronized (messagePartLock) {
if (Constants.OPCODE_CLOSE == mp.getOpCode()) {
try {
setBatchingAllowed(false);
} catch (IOException e) {
log.warn(sm.getString(
"wsRemoteEndpoint.flushOnCloseFailed"), e);
}
}
if (messagePartInProgress) {
// When a control message is sent while another message is being
// sent, the control message is queued. Chances are the
// subsequent data message part will end up queued while the
// control message is sent. The logic in this class (state
// machine, EndMessageHandler, TextMessageSendHandler) ensures
// that there will only ever be one data message part in the
// queue. There could be multiple control messages in the queue.
// Add it to the queue
messagePartQueue.add(mp);
} else {
messagePartInProgress = true;
doWrite = true;
}
// Add any remaining messages to the queue
messagePartQueue.addAll(messageParts);
}
if (doWrite) {
// Actual write has to be outside sync block to avoid possible
// deadlock between messagePartLock and writeLock in
// o.a.coyote.http11.upgrade.AbstractServletOutputStream
writeMessagePart(mp);
}
}
void endMessage(SendHandler handler, SendResult result) {
boolean doWrite = false;
MessagePart mpNext = null;
synchronized (messagePartLock) {
fragmented = nextFragmented;
text = nextText;
mpNext = messagePartQueue.poll();
if (mpNext == null) {
messagePartInProgress = false;
} else if (!closed){
// Session may have been closed unexpectedly in the middle of
// sending a fragmented message closing the endpoint. If this
// happens, clearly there is no point trying to send the rest of
// the message.
doWrite = true;
}
}
if (doWrite) {
// Actual write has to be outside sync block to avoid possible
// deadlock between messagePartLock and writeLock in
// o.a.coyote.http11.upgrade.AbstractServletOutputStream
writeMessagePart(mpNext);
}
wsSession.updateLastActive();
// Some handlers, such as the IntermediateMessageHandler, do not have a
// nested handler so handler may be null.
if (handler != null) {
handler.onResult(result);
}
}
void writeMessagePart(MessagePart mp) {
if (closed) {
throw new IllegalStateException(
sm.getString("wsRemoteEndpoint.closed"));
}
if (Constants.INTERNAL_OPCODE_FLUSH == mp.getOpCode()) {
nextFragmented = fragmented;
nextText = text;
doWrite(mp.getEndHandler(), outputBuffer);
return;
}
// Control messages may be sent in the middle of fragmented message
// so they have no effect on the fragmented or text flags
boolean first;
if (Util.isControl(mp.getOpCode())) {
nextFragmented = fragmented;
nextText = text;
if (mp.getOpCode() == Constants.OPCODE_CLOSE) {
closed = true;
}
first = true;
} else {
boolean isText = Util.isText(mp.getOpCode());
if (fragmented) {
// Currently fragmented
if (text != isText) {
throw new IllegalStateException(
sm.getString("wsRemoteEndpoint.changeType"));
}
nextText = text;
nextFragmented = !mp.isFin();
first = false;
} else {
// Wasn't fragmented. Might be now
if (mp.isFin()) {
nextFragmented = false;
} else {
nextFragmented = true;
nextText = isText;
}
first = true;
}
}
byte[] mask;
if (isMasked()) {
mask = Util.generateMask();
} else {
mask = null;
}
headerBuffer.clear();
writeHeader(headerBuffer, mp.isFin(), mp.getRsv(), mp.getOpCode(),
isMasked(), mp.getPayload(), mask, first);
headerBuffer.flip();
if (getBatchingAllowed() || isMasked()) {
// Need to write via output buffer
OutputBufferSendHandler obsh = new OutputBufferSendHandler(
mp.getEndHandler(), headerBuffer, mp.getPayload(), mask,
outputBuffer, !getBatchingAllowed(), this);
obsh.write();
} else {
// Can write directly
doWrite(mp.getEndHandler(), headerBuffer, mp.getPayload());
}
}
private long getBlockingSendTimeout() {
Object obj = wsSession.getUserProperties().get(
BLOCKING_SEND_TIMEOUT_PROPERTY);
Long userTimeout = null;
if (obj instanceof Long) {
userTimeout = (Long) obj;
}
if (userTimeout == null) {
return DEFAULT_BLOCKING_SEND_TIMEOUT;
} else {
return userTimeout.longValue();
}
}
/**
* Wraps the user provided handler so that the end point is notified when
* the message is complete.
*/
private static class EndMessageHandler implements SendHandler {
private final WsRemoteEndpointImplBase endpoint;
private final SendHandler handler;
public EndMessageHandler(WsRemoteEndpointImplBase endpoint,
SendHandler handler) {
this.endpoint = endpoint;
this.handler = handler;
}
@Override
public void onResult(SendResult result) {
endpoint.endMessage(handler, result);
}
}
/**
* If a transformation needs to split a {@link MessagePart} into multiple
* {@link MessagePart}s, it uses this handler as the end handler for each of
* the additional {@link MessagePart}s. This handler notifies this this
* class that the {@link MessagePart} has been processed and that the next
* {@link MessagePart} in the queue should be started. The final
* {@link MessagePart} will use the {@link EndMessageHandler} provided with
* the original {@link MessagePart}.
*/
private static class IntermediateMessageHandler implements SendHandler {
private final WsRemoteEndpointImplBase endpoint;
public IntermediateMessageHandler(WsRemoteEndpointImplBase endpoint) {
this.endpoint = endpoint;
}
@Override
public void onResult(SendResult result) {
endpoint.endMessage(null, result);
}
}
public void sendObject(Object obj) throws IOException {
Future<Void> f = sendObjectByFuture(obj);
try {
f.get();
} catch (InterruptedException e) {
throw new IOException(e);
} catch (ExecutionException e) {
throw new IOException(e);
}
}
public Future<Void> sendObjectByFuture(Object obj) {
FutureToSendHandler f2sh = new FutureToSendHandler(wsSession);
sendObjectByCompletion(obj, f2sh);
return f2sh;
}
@SuppressWarnings({"unchecked", "rawtypes"})
public void sendObjectByCompletion(Object obj, SendHandler completion) {
if (Util.isPrimitive(obj.getClass())) {
String msg = obj.toString();
sendStringByCompletion(msg, completion);
return;
}
Encoder encoder = findEncoder(obj);
try {
if (encoder instanceof Encoder.Text) {
String msg = ((Encoder.Text) encoder).encode(obj);
sendStringByCompletion(msg, completion);
} else if (encoder instanceof Encoder.TextStream) {
Writer w = null;
try {
w = getSendWriter();
((Encoder.TextStream) encoder).encode(obj, w);
} finally {
if (w != null) {
try {
w.close();
} catch (IOException ioe) {
// Ignore
}
}
}
completion.onResult(new SendResult());
} else if (encoder instanceof Encoder.Binary) {
ByteBuffer msg = ((Encoder.Binary) encoder).encode(obj);
sendBytesByCompletion(msg, completion);
} else if (encoder instanceof Encoder.BinaryStream) {
OutputStream os = null;
try {
os = getSendStream();
((Encoder.BinaryStream) encoder).encode(obj, os);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException ioe) {
// Ignore
}
}
}
completion.onResult(new SendResult());
} else {
throw new EncodeException(obj, sm.getString(
"wsRemoteEndpoint.noEncoder", obj.getClass()));
}
} catch (EncodeException e) {
SendResult sr = new SendResult(e);
completion.onResult(sr);
} catch (IOException e) {
SendResult sr = new SendResult(e);
completion.onResult(sr);
}
}
protected void setSession(WsSession wsSession) {
this.wsSession = wsSession;
}
protected void setEncoders(EndpointConfig endpointConfig)
throws DeploymentException {
encoderEntries.clear();
for (Class<? extends Encoder> encoderClazz :
endpointConfig.getEncoders()) {
Encoder instance;
try {
instance = encoderClazz.newInstance();
instance.init(endpointConfig);
} catch (InstantiationException e) {
throw new DeploymentException(
sm.getString("wsRemoteEndpoint.invalidEncoder",
encoderClazz.getName()), e);
} catch (IllegalAccessException e) {
throw new DeploymentException(
sm.getString("wsRemoteEndpoint.invalidEncoder",
encoderClazz.getName()), e);
}
EncoderEntry entry = new EncoderEntry(
Util.getEncoderType(encoderClazz), instance);
encoderEntries.add(entry);
}
}
private Encoder findEncoder(Object obj) {
for (EncoderEntry entry : encoderEntries) {
if (entry.getClazz().isAssignableFrom(obj.getClass())) {
return entry.getEncoder();
}
}
return null;
}
public final void close() {
for (EncoderEntry entry : encoderEntries) {
entry.getEncoder().destroy();
}
doClose();
}
protected abstract void doWrite(SendHandler handler, ByteBuffer... data);
protected abstract boolean isMasked();
protected abstract void doClose();
private static void writeHeader(ByteBuffer headerBuffer, boolean fin,
int rsv, byte opCode, boolean masked, ByteBuffer payload,
byte[] mask, boolean first) {
byte b = 0;
if (fin) {
// Set the fin bit
b -= 128;
}
b += (rsv << 4);
if (first) {
// This is the first fragment of this message
b += opCode;
}
// If not the first fragment, it is a continuation with opCode of zero
headerBuffer.put(b);
if (masked) {
b = (byte) 0x80;
} else {
b = 0;
}
// Next write the mask && length length
if (payload.limit() < 126) {
headerBuffer.put((byte) (payload.limit() | b));
} else if (payload.limit() < 65536) {
headerBuffer.put((byte) (126 | b));
headerBuffer.put((byte) (payload.limit() >>> 8));
headerBuffer.put((byte) (payload.limit() & 0xFF));
} else {
// Will never be more than 2^31-1
headerBuffer.put((byte) (127 | b));
headerBuffer.put((byte) 0);
headerBuffer.put((byte) 0);
headerBuffer.put((byte) 0);
headerBuffer.put((byte) 0);
headerBuffer.put((byte) (payload.limit() >>> 24));
headerBuffer.put((byte) (payload.limit() >>> 16));
headerBuffer.put((byte) (payload.limit() >>> 8));
headerBuffer.put((byte) (payload.limit() & 0xFF));
}
if (masked) {
headerBuffer.put(mask[0]);
headerBuffer.put(mask[1]);
headerBuffer.put(mask[2]);
headerBuffer.put(mask[3]);
}
}
private class TextMessageSendHandler implements SendHandler {
private final SendHandler handler;
private final CharBuffer message;
private final boolean isLast;
private final CharsetEncoder encoder;
private final ByteBuffer buffer;
private final WsRemoteEndpointImplBase endpoint;
private volatile boolean isDone = false;
public TextMessageSendHandler(SendHandler handler, CharBuffer message,
boolean isLast, CharsetEncoder encoder,
ByteBuffer encoderBuffer, WsRemoteEndpointImplBase endpoint) {
this.handler = handler;
this.message = message;
this.isLast = isLast;
this.encoder = encoder.reset();
this.buffer = encoderBuffer;
this.endpoint = endpoint;
}
public void write() {
buffer.clear();
CoderResult cr = encoder.encode(message, buffer, true);
if (cr.isError()) {
throw new IllegalArgumentException(cr.toString());
}
isDone = !cr.isOverflow();
buffer.flip();
endpoint.startMessage(Constants.OPCODE_TEXT, buffer,
isDone && isLast, this);
}
@Override
public void onResult(SendResult result) {
if (isDone) {
endpoint.stateMachine.complete(isLast);
handler.onResult(result);
} else if(!result.isOK()) {
handler.onResult(result);
} else if (closed){
SendResult sr = new SendResult(new IOException(
sm.getString("wsRemoteEndpoint.closedDuringMessage")));
handler.onResult(sr);
} else {
write();
}
}
}
/**
* Used to write data to the output buffer, flushing the buffer if it fills
* up.
*/
private static class OutputBufferSendHandler implements SendHandler {
private final SendHandler handler;
private final ByteBuffer headerBuffer;
private final ByteBuffer payload;
private final byte[] mask;
private final ByteBuffer outputBuffer;
private final boolean flushRequired;
private final WsRemoteEndpointImplBase endpoint;
private int maskIndex = 0;
public OutputBufferSendHandler(SendHandler completion,
ByteBuffer headerBuffer, ByteBuffer payload, byte[] mask,
ByteBuffer outputBuffer, boolean flushRequired,
WsRemoteEndpointImplBase endpoint) {
this.handler = completion;
this.headerBuffer = headerBuffer;
this.payload = payload;
this.mask = mask;
this.outputBuffer = outputBuffer;
this.flushRequired = flushRequired;
this.endpoint = endpoint;
}
public void write() {
// Write the header
while (headerBuffer.hasRemaining() && outputBuffer.hasRemaining()) {
outputBuffer.put(headerBuffer.get());
}
if (headerBuffer.hasRemaining()) {
// Still more headers to write, need to flush
outputBuffer.flip();
endpoint.doWrite(this, outputBuffer);
return;
}
// Write the payload
int payloadLeft = payload.remaining();
int payloadLimit = payload.limit();
int outputSpace = outputBuffer.remaining();
int toWrite = payloadLeft;
if (payloadLeft > outputSpace) {
toWrite = outputSpace;
// Temporarily reduce the limit
payload.limit(payload.position() + toWrite);
}
if (mask == null) {
// Use a bulk copy
outputBuffer.put(payload);
} else {
for (int i = 0; i < toWrite; i++) {
outputBuffer.put(
(byte) (payload.get() ^ (mask[maskIndex++] & 0xFF)));
if (maskIndex > 3) {
maskIndex = 0;
}
}
}
if (payloadLeft > outputSpace) {
// Restore the original limit
payload.limit(payloadLimit);
// Still more headers to write, need to flush
outputBuffer.flip();
endpoint.doWrite(this, outputBuffer);
return;
}
if (flushRequired) {
outputBuffer.flip();
if (outputBuffer.remaining() == 0) {
handler.onResult(new SendResult());
} else {
endpoint.doWrite(this, outputBuffer);
}
} else {
handler.onResult(new SendResult());
}
}
// ------------------------------------------------- SendHandler methods
@Override
public void onResult(SendResult result) {
if (result.isOK()) {
if (outputBuffer.hasRemaining()) {
endpoint.doWrite(this, outputBuffer);
} else {
outputBuffer.clear();
write();
}
} else {
handler.onResult(result);
}
}
}
private class WsOutputStream extends OutputStream {
private final WsRemoteEndpointImplBase endpoint;
private final ByteBuffer buffer = ByteBuffer.allocate(8192);
private final Object closeLock = new Object();
private volatile boolean closed = false;
public WsOutputStream(WsRemoteEndpointImplBase endpoint) {
this.endpoint = endpoint;
}
@Override
public void write(int b) throws IOException {
if (closed) {
throw new IllegalStateException(
sm.getString("wsRemoteEndpoint.closedOutputStream"));
}
if (buffer.remaining() == 0) {
flush();
}
buffer.put((byte) b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (closed) {
throw new IllegalStateException(
sm.getString("wsRemoteEndpoint.closedOutputStream"));
}
if (len == 0) {
return;
}
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
}
if (buffer.remaining() == 0) {
flush();
}
int remaining = buffer.remaining();
int written = 0;
while (remaining < len - written) {
buffer.put(b, off + written, remaining);
written += remaining;
flush();
remaining = buffer.remaining();
}
buffer.put(b, off + written, len - written);
}
@Override
public void flush() throws IOException {
if (closed) {
throw new IllegalStateException(
sm.getString("wsRemoteEndpoint.closedOutputStream"));
}
doWrite(false);
}
@Override
public void close() throws IOException {
synchronized (closeLock) {
if (closed) {
return;
}
closed = true;
}
doWrite(true);
}
private void doWrite(boolean last) throws IOException {
buffer.flip();
endpoint.startMessageBlock(Constants.OPCODE_BINARY, buffer, last);
stateMachine.complete(last);
buffer.clear();
}
}
private static class WsWriter extends Writer {
private final WsRemoteEndpointImplBase endpoint;
private final CharBuffer buffer = CharBuffer.allocate(8192);
private final Object closeLock = new Object();
private volatile boolean closed = false;
public WsWriter(WsRemoteEndpointImplBase endpoint) {
this.endpoint = endpoint;
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
if (closed) {
throw new IllegalStateException(
sm.getString("wsRemoteEndpoint.closedWriter"));
}
if (len == 0) {
return;
}
if ((off < 0) || (off > cbuf.length) || (len < 0) ||
((off + len) > cbuf.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
}
if (buffer.remaining() == 0) {
flush();
}
int remaining = buffer.remaining();
int written = 0;
while (remaining < len - written) {
buffer.put(cbuf, off + written, remaining);
written += remaining;
flush();
remaining = buffer.remaining();
}
buffer.put(cbuf, off + written, len - written);
}
@Override
public void flush() throws IOException {
if (closed) {
throw new IllegalStateException(
sm.getString("wsRemoteEndpoint.closedWriter"));
}
doWrite(false);
}
@Override
public void close() throws IOException {
synchronized (closeLock) {
if (closed) {
return;
}
closed = true;
}
doWrite(true);
}
private void doWrite(boolean last) throws IOException {
buffer.flip();
endpoint.sendPartialString(buffer, last);
buffer.clear();
}
}
private static class EncoderEntry {
private final Class<?> clazz;
private final Encoder encoder;
public EncoderEntry(Class<?> clazz, Encoder encoder) {
this.clazz = clazz;
this.encoder = encoder;
}
public Class<?> getClazz() {
return clazz;
}
public Encoder getEncoder() {
return encoder;
}
}
private static enum State {
OPEN,
STREAM_WRITING,
WRITER_WRITING,
BINARY_PARTIAL_WRITING,
BINARY_PARTIAL_READY,
BINARY_FULL_WRITING,
TEXT_PARTIAL_WRITING,
TEXT_PARTIAL_READY,
TEXT_FULL_WRITING
}
private static class StateMachine {
private State state = State.OPEN;
public synchronized void streamStart() {
checkState(State.OPEN);
state = State.STREAM_WRITING;
}
public synchronized void writeStart() {
checkState(State.OPEN);
state = State.WRITER_WRITING;
}
public synchronized void binaryPartialStart() {
checkState(State.OPEN, State.BINARY_PARTIAL_READY);
state = State.BINARY_PARTIAL_WRITING;
}
public synchronized void binaryStart() {
checkState(State.OPEN);
state = State.BINARY_FULL_WRITING;
}
public synchronized void textPartialStart() {
checkState(State.OPEN, State.TEXT_PARTIAL_READY);
state = State.TEXT_PARTIAL_WRITING;
}
public synchronized void textStart() {
checkState(State.OPEN);
state = State.TEXT_FULL_WRITING;
}
public synchronized void complete(boolean last) {
if (last) {
checkState(State.TEXT_PARTIAL_WRITING, State.TEXT_FULL_WRITING,
State.BINARY_PARTIAL_WRITING, State.BINARY_FULL_WRITING,
State.STREAM_WRITING, State.WRITER_WRITING);
state = State.OPEN;
} else {
checkState(State.TEXT_PARTIAL_WRITING, State.BINARY_PARTIAL_WRITING,
State.STREAM_WRITING, State.WRITER_WRITING);
if (state == State.TEXT_PARTIAL_WRITING) {
state = State.TEXT_PARTIAL_READY;
} else if (state == State.BINARY_PARTIAL_WRITING){
state = State.BINARY_PARTIAL_READY;
} else if (state == State.WRITER_WRITING) {
// NO-OP. Leave state as is.
} else if (state == State.STREAM_WRITING) {
// NO-OP. Leave state as is.
} else {
// Should never happen
// The if ... else ... blocks above should cover all states
// permitted by the preceding checkState() call
throw new IllegalStateException(
"BUG: This code should never be called");
}
}
}
private void checkState(State... required) {
for (State state : required) {
if (this.state == state) {
return;
}
}
throw new IllegalStateException(
sm.getString("wsRemoteEndpoint.wrongState", this.state));
}
}
private class StateUpdateSendHandler implements SendHandler {
private final SendHandler handler;
public StateUpdateSendHandler(SendHandler handler) {
this.handler = handler;
}
@Override
public void onResult(SendResult result) {
if (result.isOK()) {
stateMachine.complete(true);
}
handler.onResult(result);
}
}
}
|