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
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
/*
 * Copyright (C) 2015-2016 Neo Visionaries Inc.
 *
 * 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 NeoVisionaries.WebSockets;


import static NeoVisionaries.WebSockets.WebSocketOpcode.BINARY;
import static NeoVisionaries.WebSockets.WebSocketOpcode.CLOSE;
import static NeoVisionaries.WebSockets.WebSocketOpcode.CONTINUATION;
import static NeoVisionaries.WebSockets.WebSocketOpcode.PING;
import static NeoVisionaries.WebSockets.WebSocketOpcode.PONG;
import static NeoVisionaries.WebSockets.WebSocketOpcode.TEXT;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * WebSocket frame.
 * 
 * <EMBED CLASS='external-html' DATA-FILE-ID=LICENSE>
 *
 * @see <a href="https://tools.ietf.org/html/rfc6455#section-5"
 *      >RFC 6455, 5. Data Framing</a>
 */
public class WebSocketFrame
{
    private boolean mFin;
    private boolean mRsv1;
    private boolean mRsv2;
    private boolean mRsv3;
    private int mOpcode;
    private boolean mMask;
    private byte[] mPayload;


    /**
     * Get the value of FIN bit.
     *
     * @return
     *         The value of FIN bit.
     */
    public boolean getFin()
    {
        return mFin;
    }


    /**
     * Set the value of FIN bit.
     *
     * @param fin
     *         The value of FIN bit.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocketFrame setFin(boolean fin)
    {
        mFin = fin;

        return this;
    }


    /**
     * Get the value of RSV1 bit.
     *
     * @return
     *         The value of RSV1 bit.
     */
    public boolean getRsv1()
    {
        return mRsv1;
    }


    /**
     * Set the value of RSV1 bit.
     *
     * @param rsv1
     *         The value of RSV1 bit.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocketFrame setRsv1(boolean rsv1)
    {
        mRsv1 = rsv1;

        return this;
    }


    /**
     * Get the value of RSV2 bit.
     *
     * @return
     *         The value of RSV2 bit.
     */
    public boolean getRsv2()
    {
        return mRsv2;
    }


    /**
     * Set the value of RSV2 bit.
     *
     * @param rsv2
     *         The value of RSV2 bit.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocketFrame setRsv2(boolean rsv2)
    {
        mRsv2 = rsv2;

        return this;
    }


    /**
     * Get the value of RSV3 bit.
     *
     * @return
     *         The value of RSV3 bit.
     */
    public boolean getRsv3()
    {
        return mRsv3;
    }


    /**
     * Set the value of RSV3 bit.
     *
     * @param rsv3
     *         The value of RSV3 bit.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocketFrame setRsv3(boolean rsv3)
    {
        mRsv3 = rsv3;

        return this;
    }


    /**
     * Get the opcode.
     *
     * <table border="1" cellpadding="5" style="table-collapse: collapse;">
     *   <caption>WebSocket opcode</caption>
     *   <thead>
     *     <tr>
     *       <th>Value</th>
     *       <th>Description</th>
     *     </tr>
     *   </thead>
     *   <tbody>
     *     <tr>
     *       <td>0x0</td>
     *       <td>Frame continuation</td>
     *     </tr>
     *     <tr>
     *       <td>0x1</td>
     *       <td>Text frame</td>
     *     </tr>
     *     <tr>
     *       <td>0x2</td>
     *       <td>Binary frame</td>
     *     </tr>
     *     <tr>
     *       <td>0x3-0x7</td>
     *       <td>Reserved</td>
     *     </tr>
     *     <tr>
     *       <td>0x8</td>
     *       <td>Connection close</td>
     *     </tr>
     *     <tr>
     *       <td>0x9</td>
     *       <td>Ping</td>
     *     </tr>
     *     <tr>
     *       <td>0xA</td>
     *       <td>Pong</td>
     *     </tr>
     *     <tr>
     *       <td>0xB-0xF</td>
     *       <td>Reserved</td>
     *     </tr>
     *   </tbody>
     * </table>
     *
     * @return
     *         The opcode.
     *
     * @see WebSocketOpcode
     */
    public int getOpcode()
    {
        return mOpcode;
    }


    /**
     * Set the opcode
     *
     * @param opcode
     *         The opcode.
     *
     * @return
     *         {@code this} object.
     *
     * @see WebSocketOpcode
     */
    public WebSocketFrame setOpcode(int opcode)
    {
        mOpcode = opcode;

        return this;
    }


    /**
     * Check if this frame is a continuation frame.
     *
     * <p>
     * This method returns {@code true} when the value of the
     * opcode is 0x0 ({@link WebSocketOpcode#CONTINUATION}).
     * </p>
     *
     * @return
     *         {@code true} if this frame is a continuation frame
     *         (= if the opcode is 0x0).
     */
    public boolean isContinuationFrame()
    {
        return (mOpcode == CONTINUATION);
    }


    /**
     * Check if this frame is a text frame.
     *
     * <p>
     * This method returns {@code true} when the value of the
     * opcode is 0x1 ({@link WebSocketOpcode#TEXT}).
     * </p>
     *
     * @return
     *         {@code true} if this frame is a text frame
     *         (= if the opcode is 0x1).
     */
    public boolean isTextFrame()
    {
        return (mOpcode == TEXT);
    }


    /**
     * Check if this frame is a binary frame.
     *
     * <p>
     * This method returns {@code true} when the value of the
     * opcode is 0x2 ({@link WebSocketOpcode#BINARY}).
     * </p>
     *
     * @return
     *         {@code true} if this frame is a binary frame
     *         (= if the opcode is 0x2).
     */
    public boolean isBinaryFrame()
    {
        return (mOpcode == BINARY);
    }


    /**
     * Check if this frame is a close frame.
     *
     * <p>
     * This method returns {@code true} when the value of the
     * opcode is 0x8 ({@link WebSocketOpcode#CLOSE}).
     * </p>
     *
     * @return
     *         {@code true} if this frame is a close frame
     *         (= if the opcode is 0x8).
     */
    public boolean isCloseFrame()
    {
        return (mOpcode == CLOSE);
    }


    /**
     * Check if this frame is a ping frame.
     *
     * <p>
     * This method returns {@code true} when the value of the
     * opcode is 0x9 ({@link WebSocketOpcode#PING}).
     * </p>
     *
     * @return
     *         {@code true} if this frame is a ping frame
     *         (= if the opcode is 0x9).
     */
    public boolean isPingFrame()
    {
        return (mOpcode == PING);
    }


    /**
     * Check if this frame is a pong frame.
     *
     * <p>
     * This method returns {@code true} when the value of the
     * opcode is 0xA ({@link WebSocketOpcode#PONG}).
     * </p>
     *
     * @return
     *         {@code true} if this frame is a pong frame
     *         (= if the opcode is 0xA).
     */
    public boolean isPongFrame()
    {
        return (mOpcode == PONG);
    }


    /**
     * Check if this frame is a data frame.
     *
     * <p>
     * This method returns {@code true} when the value of the
     * opcode is in between 0x1 and 0x7.
     * </p>
     *
     * @return
     *         {@code true} if this frame is a data frame
     *         (= if the opcode is in between 0x1 and 0x7).
     */
    public boolean isDataFrame()
    {
        return (0x1 <= mOpcode && mOpcode <= 0x7);
    }


    /**
     * Check if this frame is a control frame.
     *
     * <p>
     * This method returns {@code true} when the value of the
     * opcode is in between 0x8 and 0xF.
     * </p>
     *
     * @return
     *         {@code true} if this frame is a control frame
     *         (= if the opcode is in between 0x8 and 0xF).
     */
    public boolean isControlFrame()
    {
        return (0x8 <= mOpcode && mOpcode <= 0xF);
    }


    /**
     * Get the value of MASK bit.
     *
     * @return
     *         The value of MASK bit.
     */
    boolean getMask()
    {
        return mMask;
    }


    /**
     * Set the value of MASK bit.
     *
     * @param mask
     *         The value of MASK bit.
     *
     * @return
     *         {@code this} object.
     */
    WebSocketFrame setMask(boolean mask)
    {
        mMask = mask;

        return this;
    }


    /**
     * Check if this frame has payload.
     *
     * @return
     *         {@code true} if this frame has payload.
     */
    public boolean hasPayload()
    {
        return mPayload != null;
    }


    /**
     * Get the payload length.
     *
     * @return
     *         The payload length.
     */
    public int getPayloadLength()
    {
        if (mPayload == null)
        {
            return 0;
        }

        return mPayload.length;
    }


    /**
     * Get the unmasked payload.
     *
     * @return
     *         The unmasked payload. {@code null} may be returned.
     */
    public byte[] getPayload()
    {
        return mPayload;
    }


    /**
     * Get the unmasked payload as a text.
     *
     * @return
     *         A string constructed by interrupting the payload
     *         as a UTF-8 bytes.
     */
    public String getPayloadText()
    {
        if (mPayload == null)
        {
            return null;
        }

        return Misc.toStringUTF8(mPayload);
    }


    /**
     * Set the unmasked payload.
     *
     * <p>
     * Note that the payload length of a <a href="http://tools.ietf.org/html/rfc6455#section-5.5"
     * >control frame</a> must be 125 bytes or less.
     * </p>
     *
     * @param payload
     *         The unmasked payload. {@code null} is accepted.
     *         An empty byte array is treated in the same way
     *         as {@code null}.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocketFrame setPayload(byte[] payload)
    {
        if (payload != null && payload.length == 0)
        {
            payload = null;
        }

        mPayload = payload;

        return this;
    }


    /**
     * Set the payload. The given string is converted to a byte array
     * in UTF-8 encoding.
     *
     * <p>
     * Note that the payload length of a <a href="http://tools.ietf.org/html/rfc6455#section-5.5"
     * >control frame</a> must be 125 bytes or less.
     * </p>
     *
     * @param payload
     *         The unmasked payload. {@code null} is accepted.
     *         An empty string is treated in the same way as
     *         {@code null}.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocketFrame setPayload(String payload)
    {
        if (payload == null || payload.length() == 0)
        {
            return setPayload((byte[])null);
        }

        return setPayload(Misc.getBytesUTF8(payload));
    }


    /**
     * Set the payload that conforms to the payload format of close frames.
     *
     * <p>
     * The given parameters are encoded based on the rules described in
     * "<a href="http://tools.ietf.org/html/rfc6455#section-5.5.1"
     * >5.5.1. Close</a>" of RFC 6455.
     * </p>
     *
     * <p>
     * Note that the reason should not be too long because the payload
     * length of a <a href="http://tools.ietf.org/html/rfc6455#section-5.5"
     * >control frame</a> must be 125 bytes or less.
     * </p>
     *
     * @param closeCode
     *         The close code.
     *
     * @param reason
     *         The reason. {@code null} is accepted. An empty string
     *         is treated in the same way as {@code null}.
     *
     * @return
     *         {@code this} object.
     *
     * @see <a href="http://tools.ietf.org/html/rfc6455#section-5.5.1"
     *      >RFC 6455, 5.5.1. Close</a>
     *
     * @see WebSocketCloseCode
     */
    public WebSocketFrame setCloseFramePayload(int closeCode, String reason)
    {
        // Convert the close code to a 2-byte unsigned integer
        // in network byte order.
        byte[] encodedCloseCode = new byte[] {
            (byte)((closeCode >> 8) & 0xFF),
            (byte)((closeCode     ) & 0xFF)
        };

        // If a reason string is not given.
        if (reason == null || reason.length() == 0)
        {
            // Use the close code only.
            return setPayload(encodedCloseCode);
        }

        // Convert the reason into a byte array.
        byte[] encodedReason = Misc.getBytesUTF8(reason);

        // Concatenate the close code and the reason.
        byte[] payload = new byte[2 + encodedReason.length];
        System.arraycopy(encodedCloseCode, 0, payload, 0, 2);
        System.arraycopy(encodedReason, 0, payload, 2, encodedReason.length);

        // Use the concatenated string.
        return setPayload(payload);
    }


    /**
     * Parse the first two bytes of the payload as a close code.
     *
     * <p>
     * If any payload is not set or the length of the payload is less than 2,
     * this method returns 1005 ({@link WebSocketCloseCode#NONE}).
     * </p>
     *
     * <p>
     * The value returned from this method is meaningless if this frame
     * is not a close frame.
     * </p>
     *
     * @return
     *         The close code.
     *
     * @see <a href="http://tools.ietf.org/html/rfc6455#section-5.5.1"
     *      >RFC 6455, 5.5.1. Close</a>
     *
     * @see WebSocketCloseCode
     */
    public int getCloseCode()
    {
        if (mPayload == null || mPayload.length < 2)
        {
            return WebSocketCloseCode.NONE;
        }

        // A close code is encoded in network byte order.
        int closeCode = (((mPayload[0] & 0xFF) << 8) | (mPayload[1] & 0xFF));

        return closeCode;
    }


    /**
     * Parse the third and subsequent bytes of the payload as a close reason.
     *
     * <p>
     * If any payload is not set or the length of the payload is less than 3,
     * this method returns {@code null}.
     * </p>
     *
     * <p>
     * The value returned from this method is meaningless if this frame
     * is not a close frame.
     * </p>
     *
     * @return
     *         The close reason.
     */
    public String getCloseReason()
    {
        if (mPayload == null || mPayload.length < 3)
        {
            return null;
        }

        return Misc.toStringUTF8(mPayload, 2, mPayload.length - 2);
    }


    @Override
    public String toString()
    {
        StringBuilder builder = new StringBuilder()
            .append("WebSocketFrame(FIN=").append(mFin ? "1" : "0")
            .append(",RSV1=").append(mRsv1 ? "1" : "0")
            .append(",RSV2=").append(mRsv2 ? "1" : "0")
            .append(",RSV3=").append(mRsv3 ? "1" : "0")
            .append(",Opcode=").append(Misc.toOpcodeName(mOpcode))
            .append(",Length=").append(getPayloadLength());

        switch (mOpcode)
        {
            case TEXT:
                appendPayloadText(builder);
                break;

            case BINARY:
                appendPayloadBinary(builder);
                break;

            case CLOSE:
                appendPayloadClose(builder);
                break;
        }

        return builder.append(")").toString();
    }


    private boolean appendPayloadCommon(StringBuilder builder)
    {
        builder.append(",Payload=");

        if (mPayload == null)
        {
            builder.append("null");

            // Nothing more to append.
            return true;
        }

        if (mRsv1)
        {
            // In the current implementation, mRsv1=true is allowed
            // only when Per-Message Compression is applied.
            builder.append("compressed");

            // Nothing more to append.
            return true;
        }

        // Continue.
        return false;
    }


    private void appendPayloadText(StringBuilder builder)
    {
        if (appendPayloadCommon(builder))
        {
            // Nothing more to append.
            return;
        }

        builder.append("\"");
        builder.append(getPayloadText());
        builder.append("\"");
    }


    private void appendPayloadClose(StringBuilder builder)
    {
        builder
            .append(",CloseCode=").append(getCloseCode())
            .append(",Reason=");

        String reason = getCloseReason();

        if (reason == null)
        {
            builder.append("null");
        }
        else
        {
            builder.append("\"").append(reason).append("\"");
        }
    }


    private void appendPayloadBinary(StringBuilder builder)
    {
        if (appendPayloadCommon(builder))
        {
            // Nothing more to append.
            return;
        }

        for (int i = 0; i < mPayload.length; ++i)
        {
            builder.append(String.format("%02X ", (0xFF & mPayload[i])));
        }

        if (mPayload.length != 0)
        {
            // Remove the last space.
            builder.setLength(builder.length() - 1);
        }
    }


    /**
     * Create a continuation frame. Note that the FIN bit of the
     * returned frame is false.
     *
     * @return
     *         A WebSocket frame whose FIN bit is false, opcode is
     *         {@link WebSocketOpcode#CONTINUATION CONTINUATION} and
     *         payload is {@code null}.
     */
    public static WebSocketFrame createContinuationFrame()
    {
        return new WebSocketFrame()
            .setOpcode(CONTINUATION);
    }


    /**
     * Create a continuation frame. Note that the FIN bit of the
     * returned frame is false.
     *
     * @param payload
     *         The payload for a newly create frame.
     *
     * @return
     *         A WebSocket frame whose FIN bit is false, opcode is
     *         {@link WebSocketOpcode#CONTINUATION CONTINUATION} and
     *         payload is the given one.
     */
    public static WebSocketFrame createContinuationFrame(byte[] payload)
    {
        return createContinuationFrame().setPayload(payload);
    }


    /**
     * Create a continuation frame. Note that the FIN bit of the
     * returned frame is false.
     *
     * @param payload
     *         The payload for a newly create frame.
     *
     * @return
     *         A WebSocket frame whose FIN bit is false, opcode is
     *         {@link WebSocketOpcode#CONTINUATION CONTINUATION} and
     *         payload is the given one.
     */
    public static WebSocketFrame createContinuationFrame(String payload)
    {
        return createContinuationFrame().setPayload(payload);
    }


    /**
     * Create a text frame.
     *
     * @param payload
     *         The payload for a newly created frame.
     *
     * @return
     *         A WebSocket frame whose FIN bit is true, opcode is
     *         {@link WebSocketOpcode#TEXT TEXT} and payload is
     *         the given one.
     */
    public static WebSocketFrame createTextFrame(String payload)
    {
        return new WebSocketFrame()
            .setFin(true)
            .setOpcode(TEXT)
            .setPayload(payload);
    }


    /**
     * Create a binary frame.
     *
     * @param payload
     *         The payload for a newly created frame.
     *
     * @return
     *         A WebSocket frame whose FIN bit is true, opcode is
     *         {@link WebSocketOpcode#BINARY BINARY} and payload is
     *         the given one.
     */
    public static WebSocketFrame createBinaryFrame(byte[] payload)
    {
        return new WebSocketFrame()
            .setFin(true)
            .setOpcode(BINARY)
            .setPayload(payload);
    }


    /**
     * Create a close frame.
     *
     * @return
     *         A WebSocket frame whose FIN bit is true, opcode is
     *         {@link WebSocketOpcode#CLOSE CLOSE} and payload is
     *         {@code null}.
     */
    public static WebSocketFrame createCloseFrame()
    {
        return new WebSocketFrame()
            .setFin(true)
            .setOpcode(CLOSE);
    }


    /**
     * Create a close frame.
     *
     * @param closeCode
     *         The close code.
     *
     * @return
     *         A WebSocket frame whose FIN bit is true, opcode is
     *         {@link WebSocketOpcode#CLOSE CLOSE} and payload
     *         contains a close code.
     *
     * @see WebSocketCloseCode
     */
    public static WebSocketFrame createCloseFrame(int closeCode)
    {
        return createCloseFrame().setCloseFramePayload(closeCode, null);
    }


    /**
     * Create a close frame.
     *
     * @param closeCode
     *         The close code.
     *
     * @param reason
     *         The close reason.
     *         Note that a control frame's payload length must be 125 bytes or less
     *         (RFC 6455, <a href="https://tools.ietf.org/html/rfc6455#section-5.5"
     *         >5.5. Control Frames</a>).
     *
     * @return
     *         A WebSocket frame whose FIN bit is true, opcode is
     *         {@link WebSocketOpcode#CLOSE CLOSE} and payload
     *         contains a close code and a close reason.
     *
     * @see WebSocketCloseCode
     */
    public static WebSocketFrame createCloseFrame(int closeCode, String reason)
    {
        return createCloseFrame().setCloseFramePayload(closeCode, reason);
    }


    /**
     * Create a ping frame.
     *
     * @return
     *         A WebSocket frame whose FIN bit is true, opcode is
     *         {@link WebSocketOpcode#PING PING} and payload is
     *         {@code null}.
     */
    public static WebSocketFrame createPingFrame()
    {
        return new WebSocketFrame()
            .setFin(true)
            .setOpcode(PING);
    }


    /**
     * Create a ping frame.
     *
     * @param payload
     *         The payload for a newly created frame.
     *         Note that a control frame's payload length must be 125 bytes or less
     *         (RFC 6455, <a href="https://tools.ietf.org/html/rfc6455#section-5.5"
     *         >5.5. Control Frames</a>).
     *
     * @return
     *         A WebSocket frame whose FIN bit is true, opcode is
     *         {@link WebSocketOpcode#PING PING} and payload is
     *         the given one.
     */
    public static WebSocketFrame createPingFrame(byte[] payload)
    {
        return createPingFrame().setPayload(payload);
    }


    /**
     * Create a ping frame.
     *
     * @param payload
     *         The payload for a newly created frame.
     *         Note that a control frame's payload length must be 125 bytes or less
     *         (RFC 6455, <a href="https://tools.ietf.org/html/rfc6455#section-5.5"
     *         >5.5. Control Frames</a>).
     *
     * @return
     *         A WebSocket frame whose FIN bit is true, opcode is
     *         {@link WebSocketOpcode#PING PING} and payload is
     *         the given one.
     */
    public static WebSocketFrame createPingFrame(String payload)
    {
        return createPingFrame().setPayload(payload);
    }


    /**
     * Create a pong frame.
     *
     * @return
     *         A WebSocket frame whose FIN bit is true, opcode is
     *         {@link WebSocketOpcode#PONG PONG} and payload is
     *         {@code null}.
     */
    public static WebSocketFrame createPongFrame()
    {
        return new WebSocketFrame()
            .setFin(true)
            .setOpcode(PONG);
    }


    /**
     * Create a pong frame.
     *
     * @param payload
     *         The payload for a newly created frame.
     *         Note that a control frame's payload length must be 125 bytes or less
     *         (RFC 6455, <a href="https://tools.ietf.org/html/rfc6455#section-5.5"
     *         >5.5. Control Frames</a>).
     *
     * @return
     *         A WebSocket frame whose FIN bit is true, opcode is
     *         {@link WebSocketOpcode#PONG PONG} and payload is
     *         the given one.
     */
    public static WebSocketFrame createPongFrame(byte[] payload)
    {
        return createPongFrame().setPayload(payload);
    }


    /**
     * Create a pong frame.
     *
     * @param payload
     *         The payload for a newly created frame.
     *         Note that a control frame's payload length must be 125 bytes or less
     *         (RFC 6455, <a href="https://tools.ietf.org/html/rfc6455#section-5.5"
     *         >5.5. Control Frames</a>).
     *
     * @return
     *         A WebSocket frame whose FIN bit is true, opcode is
     *         {@link WebSocketOpcode#PONG PONG} and payload is
     *         the given one.
     */
    public static WebSocketFrame createPongFrame(String payload)
    {
        return createPongFrame().setPayload(payload);
    }


    /**
     * Mask/unmask payload.
     *
     * <p>
     * The logic of masking/unmasking is described in "<a href=
     * "http://tools.ietf.org/html/rfc6455#section-5.3">5.3.
     * Client-to-Server Masking</a>" in RFC 6455.
     * </p>
     *
     * @param maskingKey
     *         The masking key. If {@code null} is given or the length
     *         of the masking key is less than 4, nothing is performed.
     *
     * @param payload
     *         Payload to be masked/unmasked.
     *
     * @return
     *         {@code payload}.
     *
     * @see <a href="http://tools.ietf.org/html/rfc6455#section-5.3">5.3. Client-to-Server Masking</a>
     */
    static byte[] mask(byte[] maskingKey, byte[] payload)
    {
        if (maskingKey == null || maskingKey.length < 4 || payload == null)
        {
            return payload;
        }

        for (int i = 0; i < payload.length; ++i)
        {
            payload[i] ^= maskingKey[i % 4];
        }

        return payload;
    }


    static WebSocketFrame compressFrame(WebSocketFrame frame, PerMessageCompressionExtension pmce)
    {
        // If Per-Message Compression is not enabled.
        if (pmce == null)
        {
            // No compression.
            return frame;
        }

        // If the frame is neither a TEXT frame nor a BINARY frame.
        if (frame.isTextFrame()   == false &&
            frame.isBinaryFrame() == false)
        {
            // No compression.
            return frame;
        }

        // If the frame is not the final frame.
        if (frame.getFin() == false)
        {
            // The compression must be applied to this frame and
            // all the subsequent continuation frames, but the
            // current implementation does not support the behavior.
            return frame;
        }

        // If the RSV1 bit is set.
        if (frame.getRsv1())
        {
            // In the current implementation, RSV1=true is allowed
            // only as Per-Message Compressed Bit (See RFC 7692,
            // 6. Framing). Therefore, RSV1=true here is regarded
            // as "already compressed".
            return frame;
        }

        // The plain payload before compression.
        byte[] payload = frame.getPayload();

        // If the payload is empty.
        if (payload == null || payload.length == 0)
        {
            // No compression.
            return frame;
        }

        // Compress the payload.
        byte[] compressed = compress(payload, pmce);

        // If the length of the compressed data is not less than
        // that of the original plain payload.
        if (payload.length <= compressed.length)
        {
            // It's better not to compress the payload.
            return frame;
        }

        // Replace the plain payload with the compressed data.
        frame.setPayload(compressed);

        // Set Per-Message Compressed Bit (See RFC 7692, 6. Framing).
        frame.setRsv1(true);

        return frame;
    }


    private static byte[] compress(byte[] data, PerMessageCompressionExtension pmce)
    {
        try
        {
            // Compress the data.
            return pmce.compress(data);
        }
        catch (WebSocketException e)
        {
            // Failed to compress the data. Ignore this error and use
            // the plain original data. The current implementation
            // does not call any listener callback method for this error.
            return data;
        }
    }


    static List<WebSocketFrame> splitIfNecessary(
            WebSocketFrame frame, int maxPayloadSize, PerMessageCompressionExtension pmce)
    {
        // If the maximum payload size is not specified.
        if (maxPayloadSize == 0)
        {
            // Not split.
            return null;
        }

        // If the total length of the payload is equal to or
        // less than the maximum payload size.
        if (frame.getPayloadLength() <= maxPayloadSize)
        {
            // Not split.
            return null;
        }

        // If the frame is a binary frame or a text frame.
        if (frame.isBinaryFrame() || frame.isTextFrame())
        {
            // Try to compress the frame. In the current implementation, binary
            // frames and text frames with the FIN bit true can be compressed.
            // The compressFrame() method may change the payload and the RSV1
            // bit of the given frame.
            frame = compressFrame(frame, pmce);

            // If the payload length of the frame has become equal to or less
            // than the maximum payload size as a result of the compression.
            if (frame.getPayloadLength() <= maxPayloadSize)
            {
                // Not split. (Note that the frame has been compressed)
                return null;
            }
        }
        else if (frame.isContinuationFrame() == false)
        {
            // Control frames (Close/Ping/Pong) are not split.
            return null;
        }

        // Split the frame.
        return split(frame, maxPayloadSize);
    }


    private static List<WebSocketFrame> split(WebSocketFrame frame, int maxPayloadSize)
    {
        // The original payload and the original FIN bit.
        byte[] originalPayload = frame.getPayload();
        boolean originalFin    = frame.getFin();

        List<WebSocketFrame> frames = new ArrayList<WebSocketFrame>();

        // Generate the first frame using the existing WebSocketFrame instance.
        // Note that the reserved bit 1 and the opcode are untouched.
        byte[] payload = Arrays.copyOf(originalPayload, maxPayloadSize);
        frame.setFin(false).setPayload(payload);
        frames.add(frame);

        for (int from = maxPayloadSize; from < originalPayload.length; from += maxPayloadSize)
        {
            // Prepare the payload of the next continuation frame.
            int to  = Math.min(from + maxPayloadSize, originalPayload.length);
            payload = Arrays.copyOfRange(originalPayload, from, to);

            // Create a continuation frame.
            WebSocketFrame cont = WebSocketFrame.createContinuationFrame(payload);
            frames.add(cont);
        }

        if (originalFin)
        {
            // Set the FIN bit of the last frame.
            frames.get(frames.size() - 1).setFin(true);
        }

        return frames;
    }
}