From ac6db57db934dc18d8bbc98028af08fdd9f135ca Mon Sep 17 00:00:00 2001 From: Marcel Prestel Date: Fri, 28 Jun 2019 18:18:03 +0200 Subject: [PATCH 001/165] Wrap IOException and include WebSocket Fixes #900 --- .../exceptions/WrappedIOException.java | 74 +++++++++++++++++++ .../server/WebSocketServer.java | 28 ++++--- 2 files changed, 91 insertions(+), 11 deletions(-) create mode 100644 src/main/java/org/java_websocket/exceptions/WrappedIOException.java diff --git a/src/main/java/org/java_websocket/exceptions/WrappedIOException.java b/src/main/java/org/java_websocket/exceptions/WrappedIOException.java new file mode 100644 index 000000000..7d25900f2 --- /dev/null +++ b/src/main/java/org/java_websocket/exceptions/WrappedIOException.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2010-2019 Nathan Rajlich + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +package org.java_websocket.exceptions; + +import org.java_websocket.WebSocket; + +import java.io.IOException; + +/** + * Exception to wrap an IOException and include information about the websocket which had the exception + * @since 1.4.1 + */ +public class WrappedIOException extends Throwable { + + /** + * The websocket where the IOException happened + */ + private final WebSocket connection; + + /** + * The IOException + */ + private final IOException ioException; + + /** + * Wrapp an IOException and include the websocket + * @param connection the websocket where the IOException happened + * @param ioException the IOException + */ + public WrappedIOException(WebSocket connection, IOException ioException) { + this.connection = connection; + this.ioException = ioException; + } + + /** + * The websocket where the IOException happened + * @return the websocket for the wrapped IOException + */ + public WebSocket getConnection() { + return connection; + } + + /** + * The wrapped IOException + * @return IOException which is wrapped + */ + public IOException getIOException() { + return ioException; + } +} diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 19331e968..cc04afaf2 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -48,6 +48,7 @@ import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.WebsocketNotConnectedException; +import org.java_websocket.exceptions.WrappedIOException; import org.java_websocket.framing.CloseFrame; import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ClientHandshake; @@ -320,7 +321,6 @@ public void run() { int selectTimeout = 0; while ( !selectorthread.isInterrupted() && iShutdownCount != 0) { SelectionKey key = null; - WebSocketImpl conn = null; try { if (isclosed.get()) { selectTimeout = 5; @@ -334,7 +334,6 @@ public void run() { while ( i.hasNext() ) { key = i.next(); - conn = null; if( !key.isValid() ) { continue; @@ -358,10 +357,10 @@ public void run() { // an other thread may cancel the key } catch ( ClosedByInterruptException e ) { return; // do the same stuff as when InterruptedException is thrown + } catch ( WrappedIOException ex) { + handleIOException( key, ex.getConnection(), ex.getIOException()); } catch ( IOException ex ) { - if( key != null ) - key.cancel(); - handleIOException( key, conn, ex ); + handleIOException( key, null, ex ); } catch ( InterruptedException e ) { // FIXME controlled shutdown (e.g. take care of buffermanagement) Thread.currentThread().interrupt(); @@ -445,7 +444,7 @@ private void doAccept(SelectionKey key, Iterator i) throws IOExcep * @throws InterruptedException thrown by taking a buffer * @throws IOException if an error happened during read */ - private boolean doRead(SelectionKey key, Iterator i) throws InterruptedException, IOException { + private boolean doRead(SelectionKey key, Iterator i) throws InterruptedException, WrappedIOException { WebSocketImpl conn = (WebSocketImpl) key.attachment(); ByteBuffer buf = takeBuffer(); if(conn.getChannel() == null){ @@ -471,7 +470,7 @@ private boolean doRead(SelectionKey key, Iterator i) throws Interr } } catch ( IOException e ) { pushBuffer( buf ); - throw e; + throw new WrappedIOException(conn, e); } return true; } @@ -481,12 +480,16 @@ private boolean doRead(SelectionKey key, Iterator i) throws Interr * @param key the selectionkey to write on * @throws IOException if an error happened during batch */ - private void doWrite(SelectionKey key) throws IOException { + private void doWrite(SelectionKey key) throws WrappedIOException { WebSocketImpl conn = (WebSocketImpl) key.attachment(); - if( SocketChannelIOHelper.batch( conn, conn.getChannel() ) ) { - if( key.isValid() ) { - key.interestOps(SelectionKey.OP_READ); + try { + if (SocketChannelIOHelper.batch(conn, conn.getChannel())) { + if (key.isValid()) { + key.interestOps(SelectionKey.OP_READ); + } } + } catch (IOException e) { + throw new WrappedIOException(conn, e); } } @@ -598,6 +601,9 @@ private void pushBuffer( ByteBuffer buf ) throws InterruptedException { private void handleIOException( SelectionKey key, WebSocket conn, IOException ex ) { // onWebsocketError( conn, ex );// conn may be null here + if (key != null) { + key.cancel(); + } if( conn != null ) { conn.closeConnection( CloseFrame.ABNORMAL_CLOSE, ex.getMessage() ); } else if( key != null ) { From 0f6cbdd385274f79eb2e1ca9f4f8fbcb5caa8e20 Mon Sep 17 00:00:00 2001 From: Marcel Prestel Date: Sat, 13 Jul 2019 10:38:10 +0200 Subject: [PATCH 002/165] Rework after review --- .../java/org/java_websocket/exceptions/WrappedIOException.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/exceptions/WrappedIOException.java b/src/main/java/org/java_websocket/exceptions/WrappedIOException.java index 7d25900f2..075de883e 100644 --- a/src/main/java/org/java_websocket/exceptions/WrappedIOException.java +++ b/src/main/java/org/java_websocket/exceptions/WrappedIOException.java @@ -34,7 +34,7 @@ * Exception to wrap an IOException and include information about the websocket which had the exception * @since 1.4.1 */ -public class WrappedIOException extends Throwable { +public class WrappedIOException extends Exception { /** * The websocket where the IOException happened From 10b5d2b9525a83e005af773766feb5aa34e56ffb Mon Sep 17 00:00:00 2001 From: Thomas Perkins Date: Fri, 9 Aug 2019 15:41:52 +0100 Subject: [PATCH 003/165] Add unit tests for Base64 and Charsetfunctions These tests were written using Diffblue Cover. --- .../org/java_websocket/util/Base64Test.java | 93 +++++++++++++++++++ .../util/CharsetfunctionsTest.java | 77 +++++++++++++++ 2 files changed, 170 insertions(+) create mode 100644 src/test/java/org/java_websocket/util/Base64Test.java create mode 100644 src/test/java/org/java_websocket/util/CharsetfunctionsTest.java diff --git a/src/test/java/org/java_websocket/util/Base64Test.java b/src/test/java/org/java_websocket/util/Base64Test.java new file mode 100644 index 000000000..48499326a --- /dev/null +++ b/src/test/java/org/java_websocket/util/Base64Test.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2010-2019 Nathan Rajlich + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.java_websocket.util; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.io.IOException; + +public class Base64Test { + + @Rule public final ExpectedException thrown = ExpectedException.none(); + + @Test + public void testEncodeBytes() throws IOException { + Assert.assertEquals("", Base64.encodeBytes(new byte[0])); + Assert.assertEquals("QHE=", + Base64.encodeBytes(new byte[] {49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 2, 2, 0)); + } + + @Test + public void testEncodeBytes2() throws IOException { + thrown.expect(IllegalArgumentException.class); + Base64.encodeBytes(new byte[0], -2, -2, -56); + } + + @Test + public void testEncodeBytes3() throws IOException { + thrown.expect(IllegalArgumentException.class); + Base64.encodeBytes(new byte[] {64, -128, 32, 18, 16, 16, 0, 18, 16}, + 2064072977, -2064007440, 10); + } + + @Test + public void testEncodeBytes4() { + thrown.expect(NullPointerException.class); + Base64.encodeBytes(null); + } + + @Test + public void testEncodeBytes5() throws IOException { + thrown.expect(IllegalArgumentException.class); + Base64.encodeBytes(null, 32766, 0, 8); + } + + @Test + public void testEncodeBytesToBytes1() throws IOException { + Assert.assertArrayEquals(new byte[] {95, 68, 111, 78, 55, 45, 61, 61}, + Base64.encodeBytesToBytes(new byte[] {-108, -19, 24, 32}, 0, 4, 32)); + Assert.assertArrayEquals(new byte[] {95, 68, 111, 78, 55, 67, 111, 61}, + Base64.encodeBytesToBytes(new byte[] {-108, -19, 24, 32, -35}, 0, 5, 40)); + Assert.assertArrayEquals(new byte[] {95, 68, 111, 78, 55, 67, 111, 61}, + Base64.encodeBytesToBytes(new byte[] {-108, -19, 24, 32, -35}, 0, 5, 32)); + Assert.assertArrayEquals(new byte[] {87, 50, 77, 61}, + Base64.encodeBytesToBytes(new byte[] {115, 42, 123, 99, 10, -33, 75, 30, 91, 99}, 8, 2, 48)); + Assert.assertArrayEquals(new byte[] {87, 50, 77, 61}, + Base64.encodeBytesToBytes(new byte[] {115, 42, 123, 99, 10, -33, 75, 30, 91, 99}, 8, 2, 56)); + Assert.assertArrayEquals(new byte[] {76, 53, 66, 61}, + Base64.encodeBytesToBytes(new byte[] {113, 42, 123, 99, 10, -33, 75, 30, 88, 99}, 8, 2, 36));Assert.assertArrayEquals(new byte[] {87, 71, 77, 61}, + Base64.encodeBytesToBytes(new byte[] {113, 42, 123, 99, 10, -33, 75, 30, 88, 99}, 8, 2, 4)); + } + + @Test + public void testEncodeBytesToBytes2() throws IOException { + thrown.expect(IllegalArgumentException.class); + Base64.encodeBytesToBytes(new byte[] {83, 10, 91, 67, 42, -1, 107, 62, 91, 67}, 8, 6, 26); + } +} diff --git a/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java b/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java new file mode 100644 index 000000000..e228a67d0 --- /dev/null +++ b/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2010-2019 Nathan Rajlich + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.java_websocket.util; + +import org.java_websocket.exceptions.InvalidDataException; +import org.junit.Assert; +import org.junit.Test; + +import java.nio.ByteBuffer; + +public class CharsetfunctionsTest { + + @Test + public void testAsciiBytes() { + Assert.assertArrayEquals(new byte[] {102, 111, 111}, Charsetfunctions.asciiBytes("foo")); + } + + @Test + public void testStringUtf8ByteBuffer() throws InvalidDataException { + Assert.assertEquals("foo", Charsetfunctions.stringUtf8(ByteBuffer.wrap(new byte[] {102, 111, 111}))); + } + + + @Test + public void testIsValidUTF8off() { + Assert.assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[] {100}), 2)); + Assert.assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[] {(byte) 128}), 0)); + + Assert.assertTrue(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[] {100}), 0)); + } + + @Test + public void testIsValidUTF8() { + Assert.assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[] {(byte) 128}))); + + Assert.assertTrue(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[] {100}))); + } + + @Test + public void testStringAscii1() { + Assert.assertEquals("oBar", Charsetfunctions.stringAscii(new byte[] {102, 111, 111, 66, 97, 114}, 2, 4)); + + } + + @Test + public void testStringAscii2() { + Assert.assertEquals("foo", Charsetfunctions.stringAscii(new byte[] {102, 111, 111})); + } + + @Test + public void testUtf8Bytes() { + Assert.assertArrayEquals(new byte[] {102, 111, 111, 66, 97, 114}, Charsetfunctions.utf8Bytes("fooBar")); + } +} From 89eaf410dd8fe3845fa6fb0de3469b55da0205cb Mon Sep 17 00:00:00 2001 From: doyledavidson Date: Mon, 9 Sep 2019 12:11:47 -0400 Subject: [PATCH 004/165] suggested fix for issue 665 "data read at end of SSL handshake is discarded" --- .../org/java_websocket/SSLSocketChannel2.java | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/SSLSocketChannel2.java b/src/main/java/org/java_websocket/SSLSocketChannel2.java index 75a56c68a..896faa40d 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel2.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel2.java @@ -215,6 +215,7 @@ protected void consumeDelegatedTasks() { } protected void createBuffers( SSLSession session ) { + saveCryptedData(); // save any remaining data in inCrypt int netBufferMax = session.getPacketBufferSize(); int appBufferMax = Math.max(session.getApplicationBufferSize(), netBufferMax); @@ -269,6 +270,7 @@ public int write( ByteBuffer src ) throws IOException { * @return the number of bytes read. **/ public int read(ByteBuffer dst) throws IOException { + tryRestoreCryptedData(); while (true) { if (!dst.hasRemaining()) return 0; @@ -329,6 +331,7 @@ private int readRemaining( ByteBuffer dst ) throws SSLException { } if( !inData.hasRemaining() ) inData.clear(); + tryRestoreCryptedData(); // test if some bytes left from last read (e.g. BUFFER_UNDERFLOW) if( inCrypt.hasRemaining() ) { unwrap(); @@ -396,7 +399,7 @@ public void writeMore() throws IOException { @Override public boolean isNeedRead() { - return inData.hasRemaining() || ( inCrypt.hasRemaining() && readEngineResult.getStatus() != Status.BUFFER_UNDERFLOW && readEngineResult.getStatus() != Status.CLOSED ); + return saveCryptData != null || inData.hasRemaining() || ( inCrypt.hasRemaining() && readEngineResult.getStatus() != Status.BUFFER_UNDERFLOW && readEngineResult.getStatus() != Status.CLOSED ); } @Override @@ -430,4 +433,31 @@ public boolean isBlocking() { public SSLEngine getSSLEngine() { return sslEngine; } + + + // to avoid complexities with inCrypt, extra unwrapped data after SSL handshake will be saved off in a byte array + // and the inserted back on first read + private byte[] saveCryptData = null; + private void saveCryptedData() + { + // did we find any extra data? + if (inCrypt != null && inCrypt.remaining() > 0) + { + int saveCryptSize = inCrypt.remaining(); + saveCryptData = new byte[saveCryptSize]; + inCrypt.get(saveCryptData); + } + } + + private void tryRestoreCryptedData() + { + // was there any extra data, then put into inCrypt and clean up + if ( saveCryptData != null ) + { + inCrypt.clear(); + inCrypt.put( saveCryptData ); + inCrypt.flip(); + saveCryptData = null; + } + } } \ No newline at end of file From 9275fed312da0d8f44c4059c0e7fd21e91210b85 Mon Sep 17 00:00:00 2001 From: victor augusto Date: Sat, 12 Oct 2019 17:59:24 -0300 Subject: [PATCH 005/165] Fix broken link on README.markdown The actual link for getting information about wss on android is broken, so we need to update it with a link from the relevant page in the wiki --- README.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.markdown b/README.markdown index 439d460cd..937e0ba9f 100644 --- a/README.markdown +++ b/README.markdown @@ -100,8 +100,7 @@ It is currently not possible to accept ws and wss connections at the same time v For some reason Firefox does not allow multiple connections to the same wss server if the server uses a different port than the default port (443). - -If you want to use `wss` on the android platfrom you should take a look at [this](http://blog.antoine.li/2010/10/22/android-trusting-ssl-certificates/). +If you want to use `wss` on the android platfrom you should take a look at [this](https://github.com/TooTallNate/Java-WebSocket/wiki/FAQ:-Secure-WebSockets#wss-on-android). I ( @Davidiusdadi ) would be glad if you would give some feedback whether wss is working fine for you or not. From db1c860b6d06438c1355a7150331b4c0e7924c86 Mon Sep 17 00:00:00 2001 From: haruntuncay Date: Sat, 9 Mar 2019 17:44:56 +0300 Subject: [PATCH 006/165] Add PerMessageDeflate Extension support, see #574 --- .../example/PerMessageDeflateExample.java | 72 +++++++ .../PerMessageDeflateExtension.java | 185 ++++++++++++++++++ .../PerMessageDeflateExtensionTest.java | 118 +++++++++++ 3 files changed, 375 insertions(+) create mode 100644 src/main/example/PerMessageDeflateExample.java create mode 100644 src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java create mode 100644 src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java diff --git a/src/main/example/PerMessageDeflateExample.java b/src/main/example/PerMessageDeflateExample.java new file mode 100644 index 000000000..aceb81d85 --- /dev/null +++ b/src/main/example/PerMessageDeflateExample.java @@ -0,0 +1,72 @@ +import org.java_websocket.WebSocket; +import org.java_websocket.client.WebSocketClient; +import org.java_websocket.drafts.Draft; +import org.java_websocket.drafts.Draft_6455; +import org.java_websocket.extensions.permessage_deflate.PerMessageDeflateExtension; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.handshake.ServerHandshake; +import org.java_websocket.server.WebSocketServer; + +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Collections; + +/** + * This class only serves the purpose of showing how to enable PerMessageDeflateExtension for both server and client sockets.
+ * Extensions are required to be registered in + * @see Draft objects and both + * @see WebSocketClient and + * @see WebSocketServer accept a + * @see Draft object in their constructors. + * This example shows how to achieve it for both server and client sockets. + * Once the connection has been established, PerMessageDeflateExtension will be enabled + * and any messages (binary or text) will be compressed/decompressed automatically.
+ * Since no additional code is required when sending or receiving messages, this example skips those parts. + */ +public class PerMessageDeflateExample { + + private static final Draft perMessageDeflateDraft = new Draft_6455(new PerMessageDeflateExtension()); + private static final int PORT = 8887; + + private static class DeflateClient extends WebSocketClient { + + public DeflateClient() throws URISyntaxException { + super(new URI("ws://localhost:" + PORT), perMessageDeflateDraft); + } + + @Override + public void onOpen(ServerHandshake handshakedata) { } + + @Override + public void onMessage(String message) { } + + @Override + public void onClose(int code, String reason, boolean remote) { } + + @Override + public void onError(Exception ex) { } + } + + private static class DeflateServer extends WebSocketServer { + + public DeflateServer() { + super(new InetSocketAddress(PORT), Collections.singletonList(perMessageDeflateDraft)); + } + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { } + + @Override + public void onMessage(WebSocket conn, String message) { } + + @Override + public void onError(WebSocket conn, Exception ex) { } + + @Override + public void onStart() { } + } +} \ No newline at end of file diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java new file mode 100644 index 000000000..4c1999b74 --- /dev/null +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -0,0 +1,185 @@ +package org.java_websocket.extensions.permessage_deflate; + +import org.java_websocket.enums.Opcode; +import org.java_websocket.exceptions.InvalidDataException; +import org.java_websocket.exceptions.InvalidFrameException; +import org.java_websocket.extensions.CompressionExtension; +import org.java_websocket.extensions.IExtension; +import org.java_websocket.framing.*; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.util.zip.DataFormatException; +import java.util.zip.Deflater; +import java.util.zip.Inflater; + +public class PerMessageDeflateExtension extends CompressionExtension { + + // Name of the extension as registered by IETF https://tools.ietf.org/html/rfc7692#section-9. + private static final String EXTENSION_REGISTERED_NAME = "permessage-deflate"; + + // Below values are defined for convenience. They are not used in the compression/decompression phase. + // They may be needed during the extension-negotiation offer in the future. + private static final String SERVER_NO_CONTEXT_TAKEOVER = "server_no_context_takeover"; + private static final String CLIENT_NO_CONTEXT_TAKEOVER = "client_no_context_takeover"; + private static final String SERVER_MAX_WINDOW_BITS = "server_max_window_bits"; + private static final String CLIENT_MAX_WINDOW_BITS = "client_max_window_bits"; + private static final boolean serverNoContextTakeover = true; + private static final boolean clientNoContextTakeover = true; + private static final int serverMaxWindowBits = 1 << 15; + private static final int clientMaxWindowBits = 1 << 15; + + private static final byte[] TAIL_BYTES = {0x00, 0x00, (byte)0xFF, (byte)0xFF}; + private static final int BUFFER_SIZE = 1 << 10; + + /* + An endpoint uses the following algorithm to decompress a message. + 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the + payload of the message. + 2. Decompress the resulting data using DEFLATE. + See, https://tools.ietf.org/html/rfc7692#section-7.2.2 + */ + @Override + public void decodeFrame(Framedata inputFrame) throws InvalidDataException { + // Only DataFrames can be decompressed. + if(!(inputFrame instanceof DataFrame)) + return; + + // RSV1 bit must be set only for the first frame. + if(inputFrame.getOpcode() == Opcode.CONTINUOUS && inputFrame.isRSV1()) + throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "RSV1 bit can only be set for the first frame."); + + // Decompressed output buffer. + ByteArrayOutputStream output = new ByteArrayOutputStream(); + Inflater inflater = new Inflater(true); + try { + decompress(inflater, inputFrame.getPayloadData().array(), output); + // Decompress 4 bytes of 0x00 0x00 0xff 0xff as if they were appended to the end of message. + if(inputFrame.isFin()) + decompress(inflater, TAIL_BYTES, output); + } catch (DataFormatException e) { + throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "Given data format couldn't be decompressed."); + }finally { + inflater.end(); + } + + // Set frames payload to the new decompressed data. + ((FramedataImpl1) inputFrame).setPayload(ByteBuffer.wrap(output.toByteArray())); + } + + private void decompress(Inflater inflater, byte[] data, ByteArrayOutputStream outputBuffer) throws DataFormatException{ + inflater.setInput(data); + byte[] buffer = new byte[BUFFER_SIZE]; + + int bytesInflated; + while((bytesInflated = inflater.inflate(buffer)) > 0){ + outputBuffer.write(buffer, 0, bytesInflated); + } + } + + @Override + public void encodeFrame(Framedata inputFrame) { + // Only DataFrames can be decompressed. + if(!(inputFrame instanceof DataFrame)) + return; + + // Only the first frame's RSV1 must be set. + if(!(inputFrame instanceof ContinuousFrame)) + ((DataFrame) inputFrame).setRSV1(true); + + Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); + deflater.setInput(inputFrame.getPayloadData().array()); + deflater.finish(); + + // Compressed output buffer. + ByteArrayOutputStream output = new ByteArrayOutputStream(); + // Temporary buffer to hold compressed output. + byte[] buffer = new byte[1024]; + int bytesCompressed; + while((bytesCompressed = deflater.deflate(buffer)) > 0) { + output.write(buffer, 0, bytesCompressed); + } + deflater.end(); + + byte outputBytes[] = output.toByteArray(); + int outputLength = outputBytes.length; + /* + https://tools.ietf.org/html/rfc7692#section-7.2.1 states that if the final fragment's compressed + payload ends with 0x00 0x00 0xff 0xff, they should be removed. + To simulate removal, we just pass 4 bytes less to the new payload + if the frame is final and outputBytes ends with 0x00 0x00 0xff 0xff. + */ + if(inputFrame.isFin() && endsWithTail(outputBytes)) + outputLength -= TAIL_BYTES.length; + + // Set frames payload to the new compressed data. + ((FramedataImpl1) inputFrame).setPayload(ByteBuffer.wrap(outputBytes, 0, outputLength)); + } + + private boolean endsWithTail(byte[] data){ + if(data.length < 4) + return false; + + int length = data.length; + for(int i = 0; i <= TAIL_BYTES.length; i--){ + if(TAIL_BYTES[i] != data[length - TAIL_BYTES.length + i]) + return false; + } + + return true; + } + + @Override + public boolean acceptProvidedExtensionAsServer(String inputExtension) { + String[] requestedExtensions = inputExtension.split(","); + for(String extension : requestedExtensions) + if(EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extension.trim())) + return true; + + return false; + } + + @Override + public boolean acceptProvidedExtensionAsClient(String inputExtension) { + String[] requestedExtensions = inputExtension.split(","); + for(String extension : requestedExtensions) + if(EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extension.trim())) + return true; + + return false; + } + + @Override + public String getProvidedExtensionAsClient() { + return EXTENSION_REGISTERED_NAME; + } + + @Override + public String getProvidedExtensionAsServer() { + return EXTENSION_REGISTERED_NAME; + } + + @Override + public IExtension copyInstance() { + return new PerMessageDeflateExtension(); + } + + /** + * This extension requires the RSV1 bit to be set only for the first frame. + * If the frame is type is CONTINUOUS, RSV1 bit must be unset. + */ + @Override + public void isFrameValid(Framedata inputFrame) throws InvalidDataException { + if((inputFrame instanceof TextFrame || inputFrame instanceof BinaryFrame) && !inputFrame.isRSV1()) + throw new InvalidFrameException("RSV1 bit must be set for DataFrames."); + if((inputFrame instanceof ContinuousFrame) && (inputFrame.isRSV1() || inputFrame.isRSV2() || inputFrame.isRSV3())) + throw new InvalidFrameException( "bad rsv RSV1: " + inputFrame.isRSV1() + " RSV2: " + inputFrame.isRSV2() + " RSV3: " + inputFrame.isRSV3() ); + super.isFrameValid(inputFrame); + } + + @Override + public String toString() { + return "PerMessageDeflateExtension"; + } + +} \ No newline at end of file diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java new file mode 100644 index 000000000..a419b55ee --- /dev/null +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -0,0 +1,118 @@ +package org.java_websocket.extensions; + +import org.java_websocket.exceptions.InvalidDataException; +import org.java_websocket.extensions.permessage_deflate.PerMessageDeflateExtension; +import org.java_websocket.framing.ContinuousFrame; +import org.java_websocket.framing.TextFrame; +import org.junit.Test; + +import java.nio.ByteBuffer; + +import static org.junit.Assert.*; + +public class PerMessageDeflateExtensionTest { + + @Test + public void testDecodeFrame() throws InvalidDataException { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + String str = "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text"; + byte[] message = str.getBytes(); + TextFrame frame = new TextFrame(); + frame.setPayload(ByteBuffer.wrap(message)); + deflateExtension.encodeFrame(frame); + deflateExtension.decodeFrame(frame); + assertArrayEquals(message, frame.getPayloadData().array()); + } + + @Test + public void testEncodeFrame() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + String str = "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text"; + byte[] message = str.getBytes(); + TextFrame frame = new TextFrame(); + frame.setPayload(ByteBuffer.wrap(message)); + deflateExtension.encodeFrame(frame); + assertTrue(message.length > frame.getPayloadData().array().length); + } + + @Test + public void testAcceptProvidedExtensionAsServer() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertTrue(deflateExtension.acceptProvidedExtensionAsServer("permessage-deflate")); + assertTrue(deflateExtension.acceptProvidedExtensionAsServer("some-other-extension, permessage-deflate")); + assertFalse(deflateExtension.acceptProvidedExtensionAsServer("wrong-permessage-deflate")); + } + + @Test + public void testAcceptProvidedExtensionAsClient() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertTrue(deflateExtension.acceptProvidedExtensionAsClient("permessage-deflate")); + assertTrue(deflateExtension.acceptProvidedExtensionAsClient("some-other-extension, permessage-deflate")); + assertFalse(deflateExtension.acceptProvidedExtensionAsClient("wrong-permessage-deflate")); + } + + @Test + public void testIsFrameValid() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + TextFrame frame = new TextFrame(); + try { + deflateExtension.isFrameValid(frame); + fail("Frame not valid. RSV1 must be set."); + } catch (Exception e) { + // + } + frame.setRSV1(true); + try { + deflateExtension.isFrameValid(frame); + } catch (Exception e) { + fail("Frame is valid."); + } + frame.setRSV2(true); + try { + deflateExtension.isFrameValid(frame); + fail("Only RSV1 bit must be set."); + } catch (Exception e) { + // + } + ContinuousFrame contFrame = new ContinuousFrame(); + contFrame.setRSV1(true); + try { + deflateExtension.isFrameValid(contFrame); + fail("RSV1 must only be set for first fragments.Continuous frames can't have RSV1 bit set."); + } catch (Exception e) { + // + } + contFrame.setRSV1(false); + try { + deflateExtension.isFrameValid(contFrame); + } catch (Exception e) { + fail("Continuous frame is valid."); + } + } + + @Test + public void testGetProvidedExtensionAsClient() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertEquals( "permessage-deflate", deflateExtension.getProvidedExtensionAsClient() ); + } + + @Test + public void testGetProvidedExtensionAsServer() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertEquals( "permessage-deflate", deflateExtension.getProvidedExtensionAsServer() ); + } + + @Test + public void testToString() throws Exception { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertEquals( "PerMessageDeflateExtension", deflateExtension.toString() ); + } +} \ No newline at end of file From 66f07a0d428380d56c87c1f7d217b841b21715c7 Mon Sep 17 00:00:00 2001 From: haruntuncay Date: Sun, 17 Mar 2019 10:00:31 +0300 Subject: [PATCH 007/165] Fix: Clear RSV1 bit after decoding. --- src/main/example/PerMessageDeflateExample.java | 2 +- .../permessage_deflate/PerMessageDeflateExtension.java | 6 +++++- .../extensions/PerMessageDeflateExtensionTest.java | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/example/PerMessageDeflateExample.java b/src/main/example/PerMessageDeflateExample.java index aceb81d85..94bc3fd2d 100644 --- a/src/main/example/PerMessageDeflateExample.java +++ b/src/main/example/PerMessageDeflateExample.java @@ -69,4 +69,4 @@ public void onError(WebSocket conn, Exception ex) { } @Override public void onStart() { } } -} \ No newline at end of file +} diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index 4c1999b74..2a614a329 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -63,6 +63,10 @@ public void decodeFrame(Framedata inputFrame) throws InvalidDataException { inflater.end(); } + // RSV1 bit must be cleared after decoding, so that other extensions don't throw an exception. + if(inputFrame.isRSV1()) + ((DataFrame) inputFrame).setRSV1(false); + // Set frames payload to the new decompressed data. ((FramedataImpl1) inputFrame).setPayload(ByteBuffer.wrap(output.toByteArray())); } @@ -182,4 +186,4 @@ public String toString() { return "PerMessageDeflateExtension"; } -} \ No newline at end of file +} diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index a419b55ee..16a746980 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -115,4 +115,4 @@ public void testToString() throws Exception { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); assertEquals( "PerMessageDeflateExtension", deflateExtension.toString() ); } -} \ No newline at end of file +} From 391e184f022ccaf5393ce87b0745356020806fe2 Mon Sep 17 00:00:00 2001 From: haruntuncay Date: Sun, 14 Apr 2019 16:20:39 +0300 Subject: [PATCH 008/165] Ran Autobahn tests and made fixes based on autobahn reports and added a class to conveniently parse an extension request --- .../org/java_websocket/drafts/Draft_6455.java | 27 ++++++ .../extensions/ExtensionRequestData.java | 52 ++++++++++ .../PerMessageDeflateExtension.java | 94 ++++++++++++++----- .../example/AutobahnServerTest.java | 3 +- 4 files changed, 152 insertions(+), 24 deletions(-) create mode 100644 src/main/java/org/java_websocket/extensions/ExtensionRequestData.java diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index 126f154d9..0718f2c46 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -427,6 +427,12 @@ private ByteBuffer createByteBufferFromFramedata( Framedata framedata ) { byte optcode = fromOpcode( framedata.getOpcode() ); byte one = ( byte ) ( framedata.isFin() ? -128 : 0 ); one |= optcode; + if(framedata.isRSV1()) + one |= getRSVByte(1); + if(framedata.isRSV2()) + one |= getRSVByte(2); + if(framedata.isRSV3()) + one |= getRSVByte(3); buf.put( one ); byte[] payloadlengthbytes = toByteArray( mes.remaining(), sizebytes ); assert ( payloadlengthbytes.length == sizebytes ); @@ -585,6 +591,27 @@ private void translateSingleFrameCheckPacketSize(int maxpacketsize, int realpack } } + /** + * Get a byte that can set RSV bits when OR(|)'d. + * 0 1 2 3 4 5 6 7 + * +-+-+-+-+-------+ + * |F|R|R|R| opcode| + * |I|S|S|S| (4) | + * |N|V|V|V| | + * | |1|2|3| | + * @param rsv Can only be {0, 1, 2, 3} + * @return byte that represents which RSV bit is set. + */ + private byte getRSVByte(int rsv){ + if(rsv == 1) // 0100 0000 + return 64; + if(rsv == 2) // 0010 0000 + return 32; + if(rsv == 3) // 0001 0000 + return 16; + return 0; + } + /** * Get the mask byte if existing * @param mask is mask active or not diff --git a/src/main/java/org/java_websocket/extensions/ExtensionRequestData.java b/src/main/java/org/java_websocket/extensions/ExtensionRequestData.java new file mode 100644 index 000000000..639dd802b --- /dev/null +++ b/src/main/java/org/java_websocket/extensions/ExtensionRequestData.java @@ -0,0 +1,52 @@ +package org.java_websocket.extensions; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class ExtensionRequestData { + + public static String EMPTY_VALUE = ""; + + private Map extensionParameters; + private String extensionName; + + private ExtensionRequestData() { + extensionParameters = new LinkedHashMap(); + } + + public static ExtensionRequestData parseExtensionRequest(String extensionRequest) { + ExtensionRequestData extensionData = new ExtensionRequestData(); + String[] parts = extensionRequest.split(";"); + extensionData.extensionName = parts[0].trim(); + + for(int i = 1; i < parts.length; i++) { + String[] keyValue = parts[i].split("="); + String value = EMPTY_VALUE; + + // Some parameters don't take a value. For those that do, parse the value. + if(keyValue.length > 1) { + String tempValue = keyValue[1].trim(); + + // If the value is wrapped in quotes, just get the data between them. + if((tempValue.startsWith("\"") && tempValue.endsWith("\"")) + || (tempValue.startsWith("'") && tempValue.endsWith("'")) + && tempValue.length() > 2) + tempValue = tempValue.substring(1, tempValue.length() - 1); + + value = tempValue; + } + + extensionData.extensionParameters.put(keyValue[0].trim(), value); + } + + return extensionData; + } + + public String getExtensionName() { + return extensionName; + } + + public Map getExtensionParameters() { + return extensionParameters; + } +} diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index 2a614a329..44a5a67cc 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -4,11 +4,14 @@ import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.InvalidFrameException; import org.java_websocket.extensions.CompressionExtension; +import org.java_websocket.extensions.ExtensionRequestData; import org.java_websocket.extensions.IExtension; import org.java_websocket.framing.*; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.zip.DataFormatException; import java.util.zip.Deflater; import java.util.zip.Inflater; @@ -17,7 +20,6 @@ public class PerMessageDeflateExtension extends CompressionExtension { // Name of the extension as registered by IETF https://tools.ietf.org/html/rfc7692#section-9. private static final String EXTENSION_REGISTERED_NAME = "permessage-deflate"; - // Below values are defined for convenience. They are not used in the compression/decompression phase. // They may be needed during the extension-negotiation offer in the future. private static final String SERVER_NO_CONTEXT_TAKEOVER = "server_no_context_takeover"; @@ -28,10 +30,25 @@ public class PerMessageDeflateExtension extends CompressionExtension { private static final boolean clientNoContextTakeover = true; private static final int serverMaxWindowBits = 1 << 15; private static final int clientMaxWindowBits = 1 << 15; - private static final byte[] TAIL_BYTES = {0x00, 0x00, (byte)0xFF, (byte)0xFF}; private static final int BUFFER_SIZE = 1 << 10; + // For WebSocketServers, this variable holds the extension parameters that the peer client has requested. + // For WebSocketClients, this variable holds the extension parameters that client himself has requested. + private Map requestedParameters = new LinkedHashMap(); + + /** + * A message to send can be fragmented and if the message is first compressed in it's entirety and then fragmented, + * those fragments can refer to backref-lengths from previous fragments. (up-to 32,768 bytes) + * In order to support this behavior, and Inflater must hold on to the previously uncompressed data + * until all the fragments of a message has been sent. + * Therefore, the + * @see #inflater must be an instance variable rather than a local variables in + * @see PerMessageDeflateExtension#decodeFrame(Framedata) so that it can retain the uncompressed data between multiple calls to + * @see PerMessageDeflateExtension#decodeFrame(Framedata). + */ + private Inflater inflater = new Inflater(true); + /* An endpoint uses the following algorithm to decompress a message. 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the @@ -51,16 +68,28 @@ public void decodeFrame(Framedata inputFrame) throws InvalidDataException { // Decompressed output buffer. ByteArrayOutputStream output = new ByteArrayOutputStream(); - Inflater inflater = new Inflater(true); try { - decompress(inflater, inputFrame.getPayloadData().array(), output); - // Decompress 4 bytes of 0x00 0x00 0xff 0xff as if they were appended to the end of message. - if(inputFrame.isFin()) - decompress(inflater, TAIL_BYTES, output); + decompress(inputFrame.getPayloadData().array(), output); + + /* + If a message is "first fragmented and then compressed", as this project does, then the inflater + can not inflate fragments except the first one. + This behavior occurs most likely because those fragments end with "final deflate blocks". + We can check the getRemaining() method to see whether the data we supplied has been decompressed or not. + And if not, we just reset the inflater and decompress again. + Note that this behavior doesn't occur if the message is "first compressed and then fragmented". + */ + if(inflater.getRemaining() > 0){ + inflater = new Inflater(true); + decompress(inputFrame.getPayloadData().array(), output); + } + + if(inputFrame.isFin()) { + decompress(TAIL_BYTES, output); + inflater = new Inflater(true); + } } catch (DataFormatException e) { - throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "Given data format couldn't be decompressed."); - }finally { - inflater.end(); + throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, e.getMessage()); } // RSV1 bit must be cleared after decoding, so that other extensions don't throw an exception. @@ -68,10 +97,10 @@ public void decodeFrame(Framedata inputFrame) throws InvalidDataException { ((DataFrame) inputFrame).setRSV1(false); // Set frames payload to the new decompressed data. - ((FramedataImpl1) inputFrame).setPayload(ByteBuffer.wrap(output.toByteArray())); + ((FramedataImpl1) inputFrame).setPayload(ByteBuffer.wrap(output.toByteArray(), 0, output.size())); } - private void decompress(Inflater inflater, byte[] data, ByteArrayOutputStream outputBuffer) throws DataFormatException{ + private void decompress(byte[] data, ByteArrayOutputStream outputBuffer) throws DataFormatException{ inflater.setInput(data); byte[] buffer = new byte[BUFFER_SIZE]; @@ -107,12 +136,13 @@ public void encodeFrame(Framedata inputFrame) { byte outputBytes[] = output.toByteArray(); int outputLength = outputBytes.length; + /* https://tools.ietf.org/html/rfc7692#section-7.2.1 states that if the final fragment's compressed payload ends with 0x00 0x00 0xff 0xff, they should be removed. To simulate removal, we just pass 4 bytes less to the new payload if the frame is final and outputBytes ends with 0x00 0x00 0xff 0xff. - */ + */ if(inputFrame.isFin() && endsWithTail(outputBytes)) outputLength -= TAIL_BYTES.length; @@ -125,7 +155,7 @@ private boolean endsWithTail(byte[] data){ return false; int length = data.length; - for(int i = 0; i <= TAIL_BYTES.length; i--){ + for(int i = 0; i < TAIL_BYTES.length; i++){ if(TAIL_BYTES[i] != data[length - TAIL_BYTES.length + i]) return false; } @@ -136,9 +166,18 @@ private boolean endsWithTail(byte[] data){ @Override public boolean acceptProvidedExtensionAsServer(String inputExtension) { String[] requestedExtensions = inputExtension.split(","); - for(String extension : requestedExtensions) - if(EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extension.trim())) - return true; + for(String extension : requestedExtensions) { + ExtensionRequestData extensionData = ExtensionRequestData.parseExtensionRequest(extension); + if(!EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extensionData.getExtensionName())) + continue; + + // Holds parameters that peer client has sent. + Map headers = extensionData.getExtensionParameters(); + requestedParameters.putAll(headers); + // After this point, parameters can be used if necessary, but for now they are not used. + + return true; + } return false; } @@ -146,21 +185,31 @@ public boolean acceptProvidedExtensionAsServer(String inputExtension) { @Override public boolean acceptProvidedExtensionAsClient(String inputExtension) { String[] requestedExtensions = inputExtension.split(","); - for(String extension : requestedExtensions) - if(EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extension.trim())) - return true; + for(String extension : requestedExtensions) { + ExtensionRequestData extensionData = ExtensionRequestData.parseExtensionRequest(extension); + if(!EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extensionData.getExtensionName())) + continue; + + // Holds parameters that are sent by the server, as a response to our initial extension request. + Map headers = extensionData.getExtensionParameters(); + // After this point, parameters that the server sent back can be configured, but we don't use them for now. + return true; + } return false; } @Override public String getProvidedExtensionAsClient() { - return EXTENSION_REGISTERED_NAME; + requestedParameters.put(CLIENT_NO_CONTEXT_TAKEOVER, ExtensionRequestData.EMPTY_VALUE); + requestedParameters.put(SERVER_NO_CONTEXT_TAKEOVER, ExtensionRequestData.EMPTY_VALUE); + + return EXTENSION_REGISTERED_NAME + "; " + CLIENT_NO_CONTEXT_TAKEOVER + "; " + SERVER_NO_CONTEXT_TAKEOVER; } @Override public String getProvidedExtensionAsServer() { - return EXTENSION_REGISTERED_NAME; + return EXTENSION_REGISTERED_NAME + "; " + SERVER_NO_CONTEXT_TAKEOVER + "; " + CLIENT_NO_CONTEXT_TAKEOVER; } @Override @@ -185,5 +234,4 @@ public void isFrameValid(Framedata inputFrame) throws InvalidDataException { public String toString() { return "PerMessageDeflateExtension"; } - } diff --git a/src/test/java/org/java_websocket/example/AutobahnServerTest.java b/src/test/java/org/java_websocket/example/AutobahnServerTest.java index 61eb4291c..e07e33558 100644 --- a/src/test/java/org/java_websocket/example/AutobahnServerTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnServerTest.java @@ -28,6 +28,7 @@ import org.java_websocket.WebSocket; import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_6455; +import org.java_websocket.extensions.permessage_deflate.PerMessageDeflateExtension; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; @@ -101,7 +102,7 @@ public static void main( String[] args ) throws UnknownHostException { System.out.println( "No limit specified. Defaulting to MaxInteger" ); limit = Integer.MAX_VALUE; } - AutobahnServerTest test = new AutobahnServerTest( port, limit, new Draft_6455() ); + AutobahnServerTest test = new AutobahnServerTest( port, limit, new Draft_6455( new PerMessageDeflateExtension()) ); test.setConnectionLostTimeout( 0 ); test.start(); } From 71d5e00602935f592c1834846bbc61b93e8e4b5e Mon Sep 17 00:00:00 2001 From: haruntuncay Date: Sun, 14 Apr 2019 16:23:18 +0300 Subject: [PATCH 009/165] Fixed test case --- .../permessage_deflate/PerMessageDeflateExtension.java | 2 +- .../extensions/PerMessageDeflateExtensionTest.java | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index 44a5a67cc..5f92f87a8 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -204,7 +204,7 @@ public String getProvidedExtensionAsClient() { requestedParameters.put(CLIENT_NO_CONTEXT_TAKEOVER, ExtensionRequestData.EMPTY_VALUE); requestedParameters.put(SERVER_NO_CONTEXT_TAKEOVER, ExtensionRequestData.EMPTY_VALUE); - return EXTENSION_REGISTERED_NAME + "; " + CLIENT_NO_CONTEXT_TAKEOVER + "; " + SERVER_NO_CONTEXT_TAKEOVER; + return EXTENSION_REGISTERED_NAME + "; " + SERVER_NO_CONTEXT_TAKEOVER + "; " + CLIENT_NO_CONTEXT_TAKEOVER; } @Override diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index 16a746980..d83072790 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -101,13 +101,15 @@ public void testIsFrameValid() { @Test public void testGetProvidedExtensionAsClient() { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertEquals( "permessage-deflate", deflateExtension.getProvidedExtensionAsClient() ); + assertEquals( "permessage-deflate; server_no_context_takeover; client_no_context_takeover", + deflateExtension.getProvidedExtensionAsClient() ); } @Test public void testGetProvidedExtensionAsServer() { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertEquals( "permessage-deflate", deflateExtension.getProvidedExtensionAsServer() ); + assertEquals( "permessage-deflate; server_no_context_takeover; client_no_context_takeover", + deflateExtension.getProvidedExtensionAsServer() ); } @Test From 27c46eddbe86afea9190cf5368c8144db9f92d9f Mon Sep 17 00:00:00 2001 From: haruntuncay Date: Sun, 14 Apr 2019 16:25:46 +0300 Subject: [PATCH 010/165] Change integer rsv bytes to hex values for clarity --- src/main/java/org/java_websocket/drafts/Draft_6455.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index 0718f2c46..4c19daf84 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -604,11 +604,11 @@ private void translateSingleFrameCheckPacketSize(int maxpacketsize, int realpack */ private byte getRSVByte(int rsv){ if(rsv == 1) // 0100 0000 - return 64; + return 0x40; if(rsv == 2) // 0010 0000 - return 32; + return 0x20; if(rsv == 3) // 0001 0000 - return 16; + return 0x10; return 0; } From 032dde8a94a0b322f697f1d2ba2e6ae997f7b5d2 Mon Sep 17 00:00:00 2001 From: Harun Tuncay Date: Wed, 17 Apr 2019 22:57:41 +0300 Subject: [PATCH 011/165] Add files via upload --- index.html | 5923 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 5923 insertions(+) create mode 100644 index.html diff --git a/index.html b/index.html new file mode 100644 index 000000000..5c6c573e2 --- /dev/null +++ b/index.html @@ -0,0 +1,5923 @@ + + + + + + + + + +
Toggle Details
+ +
+
Autobahn WebSocket Testsuite Report
+
Autobahn WebSocket
+
+

Summary report generated on 2019-04-12T14:37:19.401Z (UTC) by Autobahn WebSocket Testsuite v0.8.1/v0.10.9.

+ + + + + + + + + + + + + + + + + + + + + + +
PassTest case was executed and passed successfully.
Non-StrictTest case was executed and passed non-strictly. + A non-strict behavior is one that does not adhere to a SHOULD-behavior as described in the protocol specification or + a well-defined, canonical behavior that appears to be desirable but left open in the protocol specification. + An implementation with non-strict behavior is still conformant to the protocol specification.
FailTest case was executed and failed. An implementation which fails a test case - other + than a performance/limits related one - is non-conforming to a MUST-behavior as described in the protocol specification.
InfoInformational test case which detects certain implementation behavior left unspecified by the spec + but nevertheless potentially interesting to implementors.
MissingTest case is missing, either because it was skipped via the test suite configuration + or deactivated, i.e. because the implementation does not implement the tested feature or breaks during running + the test case.
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
1 FramingTooTallNate Java-WebSocket
1.1 Text Messages
Case 1.1.1Missing
Case 1.1.2Missing
Case 1.1.3Missing
Case 1.1.4Missing
Case 1.1.5Missing
Case 1.1.6Missing
Case 1.1.7Missing
Case 1.1.8Missing
1 FramingTooTallNate Java-WebSocket
1.2 Binary Messages
Case 1.2.1Missing
Case 1.2.2Missing
Case 1.2.3Missing
Case 1.2.4Missing
Case 1.2.5Missing
Case 1.2.6Missing
Case 1.2.7Missing
Case 1.2.8Missing
2 Pings/PongsTooTallNate Java-WebSocket
Case 2.1Missing
Case 2.2Missing
Case 2.3Missing
Case 2.4Missing
Case 2.5Missing
Case 2.6Missing
Case 2.7Missing
Case 2.8Missing
Case 2.9Missing
Case 2.10Missing
Case 2.11Missing
3 Reserved BitsTooTallNate Java-WebSocket
Case 3.1Missing
Case 3.2Missing
Case 3.3Missing
Case 3.4Missing
Case 3.5Missing
Case 3.6Missing
Case 3.7Missing
4 OpcodesTooTallNate Java-WebSocket
4.1 Non-control Opcodes
Case 4.1.1Missing
Case 4.1.2Missing
Case 4.1.3Missing
Case 4.1.4Missing
Case 4.1.5Missing
4 OpcodesTooTallNate Java-WebSocket
4.2 Control Opcodes
Case 4.2.1Missing
Case 4.2.2Missing
Case 4.2.3Missing
Case 4.2.4Missing
Case 4.2.5Missing
5 FragmentationTooTallNate Java-WebSocket
Case 5.1Missing
Case 5.2Missing
Case 5.3Missing
Case 5.4Missing
Case 5.5Missing
Case 5.6Missing
Case 5.7Missing
Case 5.8Missing
Case 5.9Missing
Case 5.10Missing
Case 5.11Missing
Case 5.12Missing
Case 5.13Missing
Case 5.14Missing
Case 5.15Missing
Case 5.16Missing
Case 5.17Missing
Case 5.18Missing
Case 5.19Missing
Case 5.20Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.1 Valid UTF-8 with zero payload fragments
Case 6.1.1Missing
Case 6.1.2Missing
Case 6.1.3Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.2 Valid UTF-8 unfragmented, fragmented on code-points and within code-points
Case 6.2.1Missing
Case 6.2.2Missing
Case 6.2.3Missing
Case 6.2.4Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.3 Invalid UTF-8 differently fragmented
Case 6.3.1Missing
Case 6.3.2Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.4 Fail-fast on invalid UTF-8
Case 6.4.1Missing
Case 6.4.2Missing
Case 6.4.3Missing
Case 6.4.4Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.5 Some valid UTF-8 sequences
Case 6.5.1Missing
Case 6.5.2Missing
Case 6.5.3Missing
Case 6.5.4Missing
Case 6.5.5Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.6 All prefixes of a valid UTF-8 string that contains multi-byte code points
Case 6.6.1Missing
Case 6.6.2Missing
Case 6.6.3Missing
Case 6.6.4Missing
Case 6.6.5Missing
Case 6.6.6Missing
Case 6.6.7Missing
Case 6.6.8Missing
Case 6.6.9Missing
Case 6.6.10Missing
Case 6.6.11Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.7 First possible sequence of a certain length
Case 6.7.1Missing
Case 6.7.2Missing
Case 6.7.3Missing
Case 6.7.4Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.8 First possible sequence length 5/6 (invalid codepoints)
Case 6.8.1Missing
Case 6.8.2Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.9 Last possible sequence of a certain length
Case 6.9.1Missing
Case 6.9.2Missing
Case 6.9.3Missing
Case 6.9.4Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.10 Last possible sequence length 4/5/6 (invalid codepoints)
Case 6.10.1Missing
Case 6.10.2Missing
Case 6.10.3Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.11 Other boundary conditions
Case 6.11.1Missing
Case 6.11.2Missing
Case 6.11.3Missing
Case 6.11.4Missing
Case 6.11.5Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.12 Unexpected continuation bytes
Case 6.12.1Missing
Case 6.12.2Missing
Case 6.12.3Missing
Case 6.12.4Missing
Case 6.12.5Missing
Case 6.12.6Missing
Case 6.12.7Missing
Case 6.12.8Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.13 Lonely start characters
Case 6.13.1Missing
Case 6.13.2Missing
Case 6.13.3Missing
Case 6.13.4Missing
Case 6.13.5Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.14 Sequences with last continuation byte missing
Case 6.14.1Missing
Case 6.14.2Missing
Case 6.14.3Missing
Case 6.14.4Missing
Case 6.14.5Missing
Case 6.14.6Missing
Case 6.14.7Missing
Case 6.14.8Missing
Case 6.14.9Missing
Case 6.14.10Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.15 Concatenation of incomplete sequences
Case 6.15.1Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.16 Impossible bytes
Case 6.16.1Missing
Case 6.16.2Missing
Case 6.16.3Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.17 Examples of an overlong ASCII character
Case 6.17.1Missing
Case 6.17.2Missing
Case 6.17.3Missing
Case 6.17.4Missing
Case 6.17.5Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.18 Maximum overlong sequences
Case 6.18.1Missing
Case 6.18.2Missing
Case 6.18.3Missing
Case 6.18.4Missing
Case 6.18.5Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.19 Overlong representation of the NUL character
Case 6.19.1Missing
Case 6.19.2Missing
Case 6.19.3Missing
Case 6.19.4Missing
Case 6.19.5Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.20 Single UTF-16 surrogates
Case 6.20.1Missing
Case 6.20.2Missing
Case 6.20.3Missing
Case 6.20.4Missing
Case 6.20.5Missing
Case 6.20.6Missing
Case 6.20.7Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.21 Paired UTF-16 surrogates
Case 6.21.1Missing
Case 6.21.2Missing
Case 6.21.3Missing
Case 6.21.4Missing
Case 6.21.5Missing
Case 6.21.6Missing
Case 6.21.7Missing
Case 6.21.8Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.22 Non-character code points (valid UTF-8)
Case 6.22.1Missing
Case 6.22.2Missing
Case 6.22.3Missing
Case 6.22.4Missing
Case 6.22.5Missing
Case 6.22.6Missing
Case 6.22.7Missing
Case 6.22.8Missing
Case 6.22.9Missing
Case 6.22.10Missing
Case 6.22.11Missing
Case 6.22.12Missing
Case 6.22.13Missing
Case 6.22.14Missing
Case 6.22.15Missing
Case 6.22.16Missing
Case 6.22.17Missing
Case 6.22.18Missing
Case 6.22.19Missing
Case 6.22.20Missing
Case 6.22.21Missing
Case 6.22.22Missing
Case 6.22.23Missing
Case 6.22.24Missing
Case 6.22.25Missing
Case 6.22.26Missing
Case 6.22.27Missing
Case 6.22.28Missing
Case 6.22.29Missing
Case 6.22.30Missing
Case 6.22.31Missing
Case 6.22.32Missing
Case 6.22.33Missing
Case 6.22.34Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.23 Unicode specials (i.e. replacement char)
Case 6.23.1Missing
Case 6.23.2Missing
Case 6.23.3Missing
Case 6.23.4Missing
Case 6.23.5Missing
Case 6.23.6Missing
Case 6.23.7Missing
7 Close HandlingTooTallNate Java-WebSocket
7.1 Basic close behavior (fuzzer initiated)
Case 7.1.1Missing
Case 7.1.2Missing
Case 7.1.3Missing
Case 7.1.4Missing
Case 7.1.5Missing
Case 7.1.6Missing
7 Close HandlingTooTallNate Java-WebSocket
7.3 Close frame structure: payload length (fuzzer initiated)
Case 7.3.1Missing
Case 7.3.2Missing
Case 7.3.3Missing
Case 7.3.4Missing
Case 7.3.5Missing
Case 7.3.6Missing
7 Close HandlingTooTallNate Java-WebSocket
7.5 Close frame structure: payload value (fuzzer initiated)
Case 7.5.1Missing
7 Close HandlingTooTallNate Java-WebSocket
7.7 Close frame structure: valid close codes (fuzzer initiated)
Case 7.7.1Missing
Case 7.7.2Missing
Case 7.7.3Missing
Case 7.7.4Missing
Case 7.7.5Missing
Case 7.7.6Missing
Case 7.7.7Missing
Case 7.7.8Missing
Case 7.7.9Missing
Case 7.7.10Missing
Case 7.7.11Missing
Case 7.7.12Missing
Case 7.7.13Missing
7 Close HandlingTooTallNate Java-WebSocket
7.9 Close frame structure: invalid close codes (fuzzer initiated)
Case 7.9.1Missing
Case 7.9.2Missing
Case 7.9.3Missing
Case 7.9.4Missing
Case 7.9.5Missing
Case 7.9.6Missing
Case 7.9.7Missing
Case 7.9.8Missing
Case 7.9.9Missing
7 Close HandlingTooTallNate Java-WebSocket
7.13 Informational close information (fuzzer initiated)
Case 7.13.1Missing
Case 7.13.2Missing
9 Limits/PerformanceTooTallNate Java-WebSocket
9.1 Text Message (increasing size)
Case 9.1.1Missing
Case 9.1.2Missing
Case 9.1.3Missing
Case 9.1.4Missing
Case 9.1.5Missing
Case 9.1.6Missing
9 Limits/PerformanceTooTallNate Java-WebSocket
9.2 Binary Message (increasing size)
Case 9.2.1Missing
Case 9.2.2Missing
Case 9.2.3Missing
Case 9.2.4Missing
Case 9.2.5Missing
Case 9.2.6Missing
9 Limits/PerformanceTooTallNate Java-WebSocket
9.3 Fragmented Text Message (fixed size, increasing fragment size)
Case 9.3.1Missing
Case 9.3.2Missing
Case 9.3.3Missing
Case 9.3.4Missing
Case 9.3.5Missing
Case 9.3.6Missing
Case 9.3.7Missing
Case 9.3.8Missing
Case 9.3.9Missing
9 Limits/PerformanceTooTallNate Java-WebSocket
9.4 Fragmented Binary Message (fixed size, increasing fragment size)
Case 9.4.1Missing
Case 9.4.2Missing
Case 9.4.3Missing
Case 9.4.4Missing
Case 9.4.5Missing
Case 9.4.6Missing
Case 9.4.7Missing
Case 9.4.8Missing
Case 9.4.9Missing
9 Limits/PerformanceTooTallNate Java-WebSocket
9.5 Text Message (fixed size, increasing chop size)
Case 9.5.1Missing
Case 9.5.2Missing
Case 9.5.3Missing
Case 9.5.4Missing
Case 9.5.5Missing
Case 9.5.6Missing
9 Limits/PerformanceTooTallNate Java-WebSocket
9.6 Binary Text Message (fixed size, increasing chop size)
Case 9.6.1Missing
Case 9.6.2Missing
Case 9.6.3Missing
Case 9.6.4Missing
Case 9.6.5Missing
Case 9.6.6Missing
9 Limits/PerformanceTooTallNate Java-WebSocket
9.7 Text Message Roundtrip Time (fixed number, increasing size)
Case 9.7.1Missing
Case 9.7.2Missing
Case 9.7.3Missing
Case 9.7.4Missing
Case 9.7.5Missing
Case 9.7.6Missing
9 Limits/PerformanceTooTallNate Java-WebSocket
9.8 Binary Message Roundtrip Time (fixed number, increasing size)
Case 9.8.1Missing
Case 9.8.2Missing
Case 9.8.3Missing
Case 9.8.4Missing
Case 9.8.5Missing
Case 9.8.6Missing
10 MiscTooTallNate Java-WebSocket
10.1 Auto-Fragmentation
Case 10.1.1Missing
12 WebSocket Compression (different payloads)TooTallNate Java-WebSocket
12.1 Large JSON data file (utf8, 194056 bytes)
Case 12.1.1Pass
629 ms [1.000/0.985]
1000
Case 12.1.2Pass
530 ms [1.000/0.748]
1000
Case 12.1.3Pass
580 ms [1.000/0.521]
1000
Case 12.1.4Pass
586 ms [1.000/0.170]
1000
Case 12.1.5Pass
680 ms [1.000/0.075]
1000
Case 12.1.6Pass
743 ms [1.000/0.059]
1000
Case 12.1.7Pass
925 ms [1.000/0.051]
1000
Case 12.1.8Pass
1399 ms [1.000/0.047]
1000
Case 12.1.9Pass
2314 ms [1.000/0.045]
1000
Case 12.1.10Pass
4054 ms [1.000/0.044]
1000
Case 12.1.11Pass
791 ms [1.000/0.059]
1000
Case 12.1.12Pass
1062 ms [1.000/0.051]
1000
Case 12.1.13Pass
1434 ms [1.000/0.047]
1000
Case 12.1.14Pass
2321 ms [1.000/0.045]
1000
Case 12.1.15Pass
4176 ms [1.000/0.044]
1000
Case 12.1.16Pass
4347 ms [1.000/0.044]
1000
Case 12.1.17Pass
4341 ms [1.000/0.044]
1000
Case 12.1.18Pass
3812 ms [1.000/0.044]
1000
12 WebSocket Compression (different payloads)TooTallNate Java-WebSocket
12.2 Lena Picture, Bitmap 512x512 bw (binary, 263222 bytes)
Case 12.2.1Pass
227 ms [1.000/1.174]
1000
Case 12.2.2Pass
267 ms [1.000/1.045]
1000
Case 12.2.3Pass
243 ms [1.000/1.008]
1000
Case 12.2.4Pass
310 ms [1.000/0.949]
1000
Case 12.2.5Pass
426 ms [1.000/0.889]
1000
Case 12.2.6Pass
609 ms [1.000/0.873]
1000
Case 12.2.7Pass
943 ms [1.000/0.865]
1000
Case 12.2.8Pass
1781 ms [1.000/0.860]
1000
Case 12.2.9Pass
3846 ms [1.000/0.855]
1000
Case 12.2.10Pass
8088 ms [1.000/0.853]
1000
Case 12.2.11Pass
931 ms [1.000/0.873]
1000
Case 12.2.12Pass
1584 ms [1.000/0.865]
1000
Case 12.2.13Pass
2828 ms [1.000/0.860]
1000
Case 12.2.14Pass
5984 ms [1.000/0.855]
1000
Case 12.2.15Pass
12014 ms [1.000/0.853]
1000
Case 12.2.16Pass
9343 ms [1.000/0.853]
1000
Case 12.2.17Pass
8312 ms [1.000/0.853]
1000
Case 12.2.18Pass
7942 ms [1.000/0.853]
1000
12 WebSocket Compression (different payloads)TooTallNate Java-WebSocket
12.3 Human readable text, Goethe's Faust I (German) (binary, 222218 bytes)
Case 12.3.1Pass
215 ms [1.000/1.122]
1000
Case 12.3.2Pass
221 ms [1.000/0.976]
1000
Case 12.3.3Pass
258 ms [1.000/0.725]
1000
Case 12.3.4Pass
291 ms [1.000/0.564]
1000
Case 12.3.5Pass
437 ms [1.000/0.481]
1000
Case 12.3.6Pass
693 ms [1.000/0.453]
1000
Case 12.3.7Pass
1220 ms [1.000/0.432]
1000
Case 12.3.8Pass
2539 ms [1.000/0.415]
1000
Case 12.3.9Pass
5329 ms [1.000/0.401]
1000
Case 12.3.10Pass
10841 ms [1.000/0.393]
1000
Case 12.3.11Pass
967 ms [1.000/0.453]
1000
Case 12.3.12Pass
1545 ms [1.000/0.432]
1000
Case 12.3.13Pass
3089 ms [1.000/0.415]
1000
Case 12.3.14Pass
6436 ms [1.000/0.401]
1000
Case 12.3.15Pass
13066 ms [1.000/0.393]
1000
Case 12.3.16Pass
11125 ms [1.000/0.393]
1000
Case 12.3.17Pass
11066 ms [1.000/0.393]
1000
Case 12.3.18Pass
11809 ms [1.000/0.393]
1000
12 WebSocket Compression (different payloads)TooTallNate Java-WebSocket
12.4 Large HTML file (utf8, 263527 bytes)
Case 12.4.1Pass
598 ms [1.000/1.048]
1000
Case 12.4.2Pass
602 ms [1.000/0.832]
1000
Case 12.4.3Pass
619 ms [1.000/0.623]
1000
Case 12.4.4Pass
614 ms [1.000/0.262]
1000
Case 12.4.5Pass
734 ms [1.000/0.112]
1000
Case 12.4.6Pass
846 ms [1.000/0.083]
1000
Case 12.4.7Pass
1017 ms [1.000/0.069]
1000
Case 12.4.8Pass
1381 ms [1.000/0.061]
1000
Case 12.4.9Pass
2304 ms [1.000/0.058]
1000
Case 12.4.10Pass
4112 ms [1.000/0.057]
1000
Case 12.4.11Pass
904 ms [1.000/0.083]
1000
Case 12.4.12Pass
1042 ms [1.000/0.069]
1000
Case 12.4.13Pass
1542 ms [1.000/0.061]
1000
Case 12.4.14Pass
2577 ms [1.000/0.058]
1000
Case 12.4.15Pass
4434 ms [1.000/0.057]
1000
Case 12.4.16Pass
4285 ms [1.000/0.057]
1000
Case 12.4.17Pass
4446 ms [1.000/0.057]
1000
Case 12.4.18Pass
4198 ms [1.000/0.057]
1000
12 WebSocket Compression (different payloads)TooTallNate Java-WebSocket
12.5 A larger PDF (binary, 1042328 bytes)
Case 12.5.1Pass
210 ms [1.000/1.175]
1000
Case 12.5.2Pass
238 ms [1.000/1.074]
1000
Case 12.5.3Pass
298 ms [1.000/1.004]
1000
Case 12.5.4Pass
305 ms [1.000/0.900]
1000
Case 12.5.5Pass
407 ms [1.000/0.855]
1000
Case 12.5.6Pass
550 ms [1.000/0.819]
1000
Case 12.5.7Pass
838 ms [1.000/0.793]
1000
Case 12.5.8Pass
1633 ms [1.000/0.777]
1000
Case 12.5.9Pass
3097 ms [1.000/0.768]
1000
Case 12.5.10Pass
6205 ms [1.000/0.763]
1000
Case 12.5.11Pass
907 ms [1.000/0.819]
1000
Case 12.5.12Pass
1439 ms [1.000/0.793]
1000
Case 12.5.13Pass
2418 ms [1.000/0.777]
1000
Case 12.5.14Pass
4615 ms [1.000/0.768]
1000
Case 12.5.15Pass
9603 ms [1.000/0.763]
1000
Case 12.5.16Pass
7019 ms [1.000/0.763]
1000
Case 12.5.17Pass
6347 ms [1.000/0.763]
1000
Case 12.5.18Pass
6237 ms [1.000/0.763]
1000
13 WebSocket Compression (different parameters)TooTallNate Java-WebSocket
13.1 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]
Case 13.1.1Pass
477 ms [1.000/0.985]
1000
Case 13.1.2Pass
521 ms [1.000/0.748]
1000
Case 13.1.3Pass
544 ms [1.000/0.521]
1000
Case 13.1.4Pass
525 ms [1.000/0.170]
1000
Case 13.1.5Pass
650 ms [1.000/0.075]
1000
Case 13.1.6Pass
745 ms [1.000/0.059]
1000
Case 13.1.7Pass
939 ms [1.000/0.051]
1000
Case 13.1.8Pass
1324 ms [1.000/0.047]
1000
Case 13.1.9Pass
2252 ms [1.000/0.045]
1000
Case 13.1.10Pass
3988 ms [1.000/0.044]
1000
Case 13.1.11Pass
806 ms [1.000/0.059]
1000
Case 13.1.12Pass
977 ms [1.000/0.051]
1000
Case 13.1.13Pass
1467 ms [1.000/0.047]
1000
Case 13.1.14Pass
2335 ms [1.000/0.045]
1000
Case 13.1.15Pass
4039 ms [1.000/0.044]
1000
Case 13.1.16Pass
4009 ms [1.000/0.044]
1000
Case 13.1.17Pass
4423 ms [1.000/0.044]
1000
Case 13.1.18Pass
3806 ms [1.000/0.044]
1000
13 WebSocket Compression (different parameters)TooTallNate Java-WebSocket
13.2 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]
Case 13.2.1Pass
453 ms [1.000/0.985]
1000
Case 13.2.2Pass
496 ms [1.000/0.748]
1000
Case 13.2.3Pass
492 ms [1.000/0.521]
1000
Case 13.2.4Pass
555 ms [1.000/0.170]
1000
Case 13.2.5Pass
635 ms [1.000/0.075]
1000
Case 13.2.6Pass
711 ms [1.000/0.059]
1000
Case 13.2.7Pass
931 ms [1.000/0.051]
1000
Case 13.2.8Pass
1270 ms [1.000/0.047]
1000
Case 13.2.9Pass
2134 ms [1.000/0.045]
1000
Case 13.2.10Pass
3863 ms [1.000/0.044]
1000
Case 13.2.11Pass
779 ms [1.000/0.059]
1000
Case 13.2.12Pass
973 ms [1.000/0.051]
1000
Case 13.2.13Pass
1389 ms [1.000/0.047]
1000
Case 13.2.14Pass
2201 ms [1.000/0.045]
1000
Case 13.2.15Pass
4032 ms [1.000/0.044]
1000
Case 13.2.16Pass
3992 ms [1.000/0.044]
1000
Case 13.2.17Pass
4234 ms [1.000/0.044]
1000
Case 13.2.18Pass
3847 ms [1.000/0.044]
1000
13 WebSocket Compression (different parameters)TooTallNate Java-WebSocket
13.3 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]
Case 13.3.1Pass
538 ms [1.000/0.985]
1000
Case 13.3.2Pass
527 ms [1.000/0.748]
1000
Case 13.3.3Pass
495 ms [1.000/0.521]
1000
Case 13.3.4Pass
544 ms [1.000/0.170]
1000
Case 13.3.5Pass
692 ms [1.000/0.075]
1000
Case 13.3.6Pass
750 ms [1.000/0.059]
1000
Case 13.3.7Pass
978 ms [1.000/0.051]
1000
Case 13.3.8Pass
1316 ms [1.000/0.047]
1000
Case 13.3.9Pass
2134 ms [1.000/0.045]
1000
Case 13.3.10Pass
3762 ms [1.000/0.044]
1000
Case 13.3.11Pass
785 ms [1.000/0.059]
1000
Case 13.3.12Pass
987 ms [1.000/0.051]
1000
Case 13.3.13Pass
1442 ms [1.000/0.047]
1000
Case 13.3.14Pass
2478 ms [1.000/0.045]
1000
Case 13.3.15Pass
4157 ms [1.000/0.044]
1000
Case 13.3.16Pass
4171 ms [1.000/0.044]
1000
Case 13.3.17Pass
4438 ms [1.000/0.044]
1000
Case 13.3.18Pass
3711 ms [1.000/0.044]
1000
13 WebSocket Compression (different parameters)TooTallNate Java-WebSocket
13.4 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]
Case 13.4.1Pass
495 ms [1.000/0.985]
1000
Case 13.4.2Pass
470 ms [1.000/0.748]
1000
Case 13.4.3Pass
493 ms [1.000/0.521]
1000
Case 13.4.4Pass
531 ms [1.000/0.170]
1000
Case 13.4.5Pass
637 ms [1.000/0.075]
1000
Case 13.4.6Pass
719 ms [1.000/0.059]
1000
Case 13.4.7Pass
906 ms [1.000/0.051]
1000
Case 13.4.8Pass
1281 ms [1.000/0.047]
1000
Case 13.4.9Pass
2103 ms [1.000/0.045]
1000
Case 13.4.10Pass
3671 ms [1.000/0.044]
1000
Case 13.4.11Pass
771 ms [1.000/0.059]
1000
Case 13.4.12Pass
976 ms [1.000/0.051]
1000
Case 13.4.13Pass
1435 ms [1.000/0.047]
1000
Case 13.4.14Pass
2350 ms [1.000/0.045]
1000
Case 13.4.15Pass
4051 ms [1.000/0.044]
1000
Case 13.4.16Pass
4005 ms [1.000/0.044]
1000
Case 13.4.17Pass
4504 ms [1.000/0.044]
1000
Case 13.4.18Pass
3954 ms [1.000/0.044]
1000
13 WebSocket Compression (different parameters)TooTallNate Java-WebSocket
13.5 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]
Case 13.5.1Pass
492 ms [1.000/0.985]
1000
Case 13.5.2Pass
525 ms [1.000/0.748]
1000
Case 13.5.3Pass
590 ms [1.000/0.521]
1000
Case 13.5.4Pass
577 ms [1.000/0.170]
1000
Case 13.5.5Pass
722 ms [1.000/0.075]
1000
Case 13.5.6Pass
816 ms [1.000/0.059]
1000
Case 13.5.7Pass
978 ms [1.000/0.051]
1000
Case 13.5.8Pass
1320 ms [1.000/0.047]
1000
Case 13.5.9Pass
2182 ms [1.000/0.045]
1000
Case 13.5.10Pass
3981 ms [1.000/0.044]
1000
Case 13.5.11Pass
823 ms [1.000/0.059]
1000
Case 13.5.12Pass
1042 ms [1.000/0.051]
1000
Case 13.5.13Pass
1456 ms [1.000/0.047]
1000
Case 13.5.14Pass
2339 ms [1.000/0.045]
1000
Case 13.5.15Pass
4093 ms [1.000/0.044]
1000
Case 13.5.16Pass
3879 ms [1.000/0.044]
1000
Case 13.5.17Pass
4201 ms [1.000/0.044]
1000
Case 13.5.18Pass
3777 ms [1.000/0.044]
1000
13 WebSocket Compression (different parameters)TooTallNate Java-WebSocket
13.6 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]
Case 13.6.1Pass
486 ms [1.000/0.985]
1000
Case 13.6.2Pass
519 ms [1.000/0.748]
1000
Case 13.6.3Pass
535 ms [1.000/0.521]
1000
Case 13.6.4Pass
543 ms [1.000/0.170]
1000
Case 13.6.5Pass
653 ms [1.000/0.075]
1000
Case 13.6.6Pass
712 ms [1.000/0.059]
1000
Case 13.6.7Pass
918 ms [1.000/0.051]
1000
Case 13.6.8Pass
1285 ms [1.000/0.047]
1000
Case 13.6.9Pass
2166 ms [1.000/0.045]
1000
Case 13.6.10Pass
3698 ms [1.000/0.044]
1000
Case 13.6.11Pass
773 ms [1.000/0.059]
1000
Case 13.6.12Pass
978 ms [1.000/0.051]
1000
Case 13.6.13Pass
1363 ms [1.000/0.047]
1000
Case 13.6.14Pass
2362 ms [1.000/0.045]
1000
Case 13.6.15Pass
4349 ms [1.000/0.044]
1000
Case 13.6.16Pass
4305 ms [1.000/0.044]
1000
Case 13.6.17Pass
4359 ms [1.000/0.044]
1000
Case 13.6.18Pass
4246 ms [1.000/0.044]
1000
13 WebSocket Compression (different parameters)TooTallNate Java-WebSocket
13.7 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]
Case 13.7.1Pass
612 ms [1.000/0.985]
1000
Case 13.7.2Pass
485 ms [1.000/0.748]
1000
Case 13.7.3Pass
537 ms [1.000/0.521]
1000
Case 13.7.4Pass
558 ms [1.000/0.170]
1000
Case 13.7.5Pass
870 ms [1.000/0.075]
1000
Case 13.7.6Pass
842 ms [1.000/0.059]
1000
Case 13.7.7Pass
1134 ms [1.000/0.051]
1000
Case 13.7.8Pass
1285 ms [1.000/0.047]
1000
Case 13.7.9Pass
2269 ms [1.000/0.045]
1000
Case 13.7.10Pass
3975 ms [1.000/0.044]
1000
Case 13.7.11Pass
960 ms [1.000/0.059]
1000
Case 13.7.12Pass
1079 ms [1.000/0.051]
1000
Case 13.7.13Pass
1434 ms [1.000/0.047]
1000
Case 13.7.14Pass
2523 ms [1.000/0.045]
1000
Case 13.7.15Pass
4308 ms [1.000/0.044]
1000
Case 13.7.16Pass
4000 ms [1.000/0.044]
1000
Case 13.7.17Pass
4446 ms [1.000/0.044]
1000
Case 13.7.18Pass
3730 ms [1.000/0.044]
1000
+

+
+
+ +

Case 1.1.1

+ Up +

Case Description

Send text message with payload 0.

+

Case Expectation

Receive echo'ed text message (with empty payload). Clean close with normal code.

+
+ +

Case 1.1.2

+ Up +

Case Description

Send text message message with payload of length 125.

+

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.

+
+ +

Case 1.1.3

+ Up +

Case Description

Send text message message with payload of length 126.

+

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.

+
+ +

Case 1.1.4

+ Up +

Case Description

Send text message message with payload of length 127.

+

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.

+
+ +

Case 1.1.5

+ Up +

Case Description

Send text message message with payload of length 128.

+

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.

+
+ +

Case 1.1.6

+ Up +

Case Description

Send text message message with payload of length 65535.

+

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.

+
+ +

Case 1.1.7

+ Up +

Case Description

Send text message message with payload of length 65536.

+

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.

+
+ +

Case 1.1.8

+ Up +

Case Description

Send text message message with payload of length 65536. Sent out data in chops of 997 octets.

+

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.

+
+ +

Case 1.2.1

+ Up +

Case Description

Send binary message with payload 0.

+

Case Expectation

Receive echo'ed binary message (with empty payload). Clean close with normal code.

+
+ +

Case 1.2.2

+ Up +

Case Description

Send binary message message with payload of length 125.

+

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.

+
+ +

Case 1.2.3

+ Up +

Case Description

Send binary message message with payload of length 126.

+

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.

+
+ +

Case 1.2.4

+ Up +

Case Description

Send binary message message with payload of length 127.

+

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.

+
+ +

Case 1.2.5

+ Up +

Case Description

Send binary message message with payload of length 128.

+

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.

+
+ +

Case 1.2.6

+ Up +

Case Description

Send binary message message with payload of length 65535.

+

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.

+
+ +

Case 1.2.7

+ Up +

Case Description

Send binary message message with payload of length 65536.

+

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.

+
+ +

Case 1.2.8

+ Up +

Case Description

Send binary message message with payload of length 65536. Sent out data in chops of 997 octets.

+

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.

+
+ +

Case 2.1

+ Up +

Case Description

Send ping without payload.

+

Case Expectation

Pong (with empty payload) is sent in reply to Ping. Clean close with normal code.

+
+ +

Case 2.2

+ Up +

Case Description

Send ping with small text payload.

+

Case Expectation

Pong with payload echo'ed is sent in reply to Ping. Clean close with normal code.

+
+ +

Case 2.3

+ Up +

Case Description

Send ping with small binary (non UTF-8) payload.

+

Case Expectation

Pong with payload echo'ed is sent in reply to Ping. Clean close with normal code.

+
+ +

Case 2.4

+ Up +

Case Description

Send ping with binary payload of 125 octets.

+

Case Expectation

Pong with payload echo'ed is sent in reply to Ping. Clean close with normal code.

+
+ +

Case 2.5

+ Up +

Case Description

Send ping with binary payload of 126 octets.

+

Case Expectation

Connection is failed immediately (1002/Protocol Error), since control frames are only allowed to have payload up to and including 125 octets..

+
+ +

Case 2.6

+ Up +

Case Description

Send ping with binary payload of 125 octets, send in octet-wise chops.

+

Case Expectation

Pong with payload echo'ed is sent in reply to Ping. Implementations must be TCP clean. Clean close with normal code.

+
+ +

Case 2.7

+ Up +

Case Description

Send unsolicited pong without payload. Verify nothing is received. Clean close with normal code.

+

Case Expectation

Nothing.

+
+ +

Case 2.8

+ Up +

Case Description

Send unsolicited pong with payload. Verify nothing is received. Clean close with normal code.

+

Case Expectation

Nothing.

+
+ +

Case 2.9

+ Up +

Case Description

Send unsolicited pong with payload. Send ping with payload. Verify pong for ping is received.

+

Case Expectation

Nothing in reply to own Pong, but Pong with payload echo'ed in reply to Ping. Clean close with normal code.

+
+ +

Case 2.10

+ Up +

Case Description

Send 10 Pings with payload.

+

Case Expectation

Pongs for our Pings with all the payloads. Note: This is not required by the Spec .. but we check for this behaviour anyway. Clean close with normal code.

+
+ +

Case 2.11

+ Up +

Case Description

Send 10 Pings with payload. Send out octets in octet-wise chops.

+

Case Expectation

Pongs for our Pings with all the payloads. Note: This is not required by the Spec .. but we check for this behaviour anyway. Clean close with normal code.

+
+ +

Case 3.1

+ Up +

Case Description

Send small text message with RSV = 1.

+

Case Expectation

The connection is failed immediately (1002/protocol error), since RSV must be 0, when no extension defining RSV meaning has been negotiated.

+
+ +

Case 3.2

+ Up +

Case Description

Send small text message, then send again with RSV = 2, then send Ping.

+

Case Expectation

Echo for first message is received, but then connection is failed immediately, since RSV must be 0, when no extension defining RSV meaning has been negotiated. The Pong is not received.

+
+ +

Case 3.3

+ Up +

Case Description

Send small text message, then send again with RSV = 3, then send Ping. Octets are sent in frame-wise chops. Octets are sent in octet-wise chops.

+

Case Expectation

Echo for first message is received, but then connection is failed immediately, since RSV must be 0, when no extension defining RSV meaning has been negotiated. The Pong is not received.

+
+ +

Case 3.4

+ Up +

Case Description

Send small text message, then send again with RSV = 4, then send Ping. Octets are sent in octet-wise chops.

+

Case Expectation

Echo for first message is received, but then connection is failed immediately, since RSV must be 0, when no extension defining RSV meaning has been negotiated. The Pong is not received.

+
+ +

Case 3.5

+ Up +

Case Description

Send small binary message with RSV = 5.

+

Case Expectation

The connection is failed immediately, since RSV must be 0.

+
+ +

Case 3.6

+ Up +

Case Description

Send Ping with RSV = 6.

+

Case Expectation

The connection is failed immediately, since RSV must be 0.

+
+ +

Case 3.7

+ Up +

Case Description

Send Close with RSV = 7.

+

Case Expectation

The connection is failed immediately, since RSV must be 0.

+
+ +

Case 4.1.1

+ Up +

Case Description

Send frame with reserved non-control Opcode = 3.

+

Case Expectation

The connection is failed immediately.

+
+ +

Case 4.1.2

+ Up +

Case Description

Send frame with reserved non-control Opcode = 4 and non-empty payload.

+

Case Expectation

The connection is failed immediately.

+
+ +

Case 4.1.3

+ Up +

Case Description

Send small text message, then send frame with reserved non-control Opcode = 5, then send Ping.

+

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.

+
+ +

Case 4.1.4

+ Up +

Case Description

Send small text message, then send frame with reserved non-control Opcode = 6 and non-empty payload, then send Ping.

+

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.

+
+ +

Case 4.1.5

+ Up +

Case Description

Send small text message, then send frame with reserved non-control Opcode = 7 and non-empty payload, then send Ping.

+

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.

+
+ +

Case 4.2.1

+ Up +

Case Description

Send frame with reserved control Opcode = 11.

+

Case Expectation

The connection is failed immediately.

+
+ +

Case 4.2.2

+ Up +

Case Description

Send frame with reserved control Opcode = 12 and non-empty payload.

+

Case Expectation

The connection is failed immediately.

+
+ +

Case 4.2.3

+ Up +

Case Description

Send small text message, then send frame with reserved control Opcode = 13, then send Ping.

+

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.

+
+ +

Case 4.2.4

+ Up +

Case Description

Send small text message, then send frame with reserved control Opcode = 14 and non-empty payload, then send Ping.

+

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.

+
+ +

Case 4.2.5

+ Up +

Case Description

Send small text message, then send frame with reserved control Opcode = 15 and non-empty payload, then send Ping.

+

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.

+
+ +

Case 5.1

+ Up +

Case Description

Send Ping fragmented into 2 fragments.

+

Case Expectation

Connection is failed immediately, since control message MUST NOT be fragmented.

+
+ +

Case 5.2

+ Up +

Case Description

Send Pong fragmented into 2 fragments.

+

Case Expectation

Connection is failed immediately, since control message MUST NOT be fragmented.

+
+ +

Case 5.3

+ Up +

Case Description

Send text Message fragmented into 2 fragments.

+

Case Expectation

Message is processed and echo'ed back to us.

+
+ +

Case 5.4

+ Up +

Case Description

Send text Message fragmented into 2 fragments, octets are sent in frame-wise chops.

+

Case Expectation

Message is processed and echo'ed back to us.

+
+ +

Case 5.5

+ Up +

Case Description

Send text Message fragmented into 2 fragments, octets are sent in octet-wise chops.

+

Case Expectation

Message is processed and echo'ed back to us.

+
+ +

Case 5.6

+ Up +

Case Description

Send text Message fragmented into 2 fragments, one ping with payload in-between.

+

Case Expectation

A pong is received, then the message is echo'ed back to us.

+
+ +

Case 5.7

+ Up +

Case Description

Send text Message fragmented into 2 fragments, one ping with payload in-between. Octets are sent in frame-wise chops.

+

Case Expectation

A pong is received, then the message is echo'ed back to us.

+
+ +

Case 5.8

+ Up +

Case Description

Send text Message fragmented into 2 fragments, one ping with payload in-between. Octets are sent in octet-wise chops.

+

Case Expectation

A pong is received, then the message is echo'ed back to us.

+
+ +

Case 5.9

+ Up +

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = true, where there is nothing to continue, sent in one chop.

+

Case Expectation

The connection is failed immediately, since there is no message to continue.

+
+ +

Case 5.10

+ Up +

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = true, where there is nothing to continue, sent in per-frame chops.

+

Case Expectation

The connection is failed immediately, since there is no message to continue.

+
+ +

Case 5.11

+ Up +

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = true, where there is nothing to continue, sent in octet-wise chops.

+

Case Expectation

The connection is failed immediately, since there is no message to continue.

+
+ +

Case 5.12

+ Up +

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = false, where there is nothing to continue, sent in one chop.

+

Case Expectation

The connection is failed immediately, since there is no message to continue.

+
+ +

Case 5.13

+ Up +

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = false, where there is nothing to continue, sent in per-frame chops.

+

Case Expectation

The connection is failed immediately, since there is no message to continue.

+
+ +

Case 5.14

+ Up +

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = false, where there is nothing to continue, sent in octet-wise chops.

+

Case Expectation

The connection is failed immediately, since there is no message to continue.

+
+ +

Case 5.15

+ Up +

Case Description

Send text Message fragmented into 2 fragments, then Continuation Frame with FIN = false where there is nothing to continue, then unfragmented Text Message, all sent in one chop.

+

Case Expectation

The connection is failed immediately, since there is no message to continue.

+
+ +

Case 5.16

+ Up +

Case Description

Repeated 2x: Continuation Frame with FIN = false (where there is nothing to continue), then text Message fragmented into 2 fragments.

+

Case Expectation

The connection is failed immediately, since there is no message to continue.

+
+ +

Case 5.17

+ Up +

Case Description

Repeated 2x: Continuation Frame with FIN = true (where there is nothing to continue), then text Message fragmented into 2 fragments.

+

Case Expectation

The connection is failed immediately, since there is no message to continue.

+
+ +

Case 5.18

+ Up +

Case Description

Send text Message fragmented into 2 fragments, with both frame opcodes set to text, sent in one chop.

+

Case Expectation

The connection is failed immediately, since all data frames after the initial data frame must have opcode 0.

+
+ +

Case 5.19

+ Up +

Case Description

A fragmented text message is sent in multiple frames. After + sending the first 2 frames of the text message, a Ping is sent. Then we wait 1s, + then we send 2 more text fragments, another Ping and then the final text fragment. + Everything is legal.

+

Case Expectation

The peer immediately answers the first Ping before + it has received the last text message fragment. The peer pong's back the Ping's + payload exactly, and echo's the payload of the fragmented message back to us.

+
+ +

Case 5.20

+ Up +

Case Description

Same as Case 5.19, but send all frames with SYNC = True. + Note, this does not change the octets sent in any way, only how the stream + is chopped up on the wire.

+

Case Expectation

Same as Case 5.19. Implementations must be agnostic to how + octet stream is chopped up on wire (must be TCP clean).

+
+ +

Case 6.1.1

+ Up +

Case Description

Send text message of length 0.

+

Case Expectation

A message is echo'ed back to us (with empty payload).

+
+ +

Case 6.1.2

+ Up +

Case Description

Send fragmented text message, 3 fragments each of length 0.

+

Case Expectation

A message is echo'ed back to us (with empty payload).

+
+ +

Case 6.1.3

+ Up +

Case Description

Send fragmented text message, 3 fragments, first and last of length 0, middle non-empty.

+

Case Expectation

A message is echo'ed back to us (with payload = payload of middle fragment).

+
+ +

Case 6.2.1

+ Up +

Case Description

Send a valid UTF-8 text message in one fragment.

MESSAGE:
Hello-µ@ßöäüàá-UTF-8!!
48656c6c6f2dc2b540c39fc3b6c3a4c3bcc3a0c3a12d5554462d382121

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.2.2

+ Up +

Case Description

Send a valid UTF-8 text message in two fragments, fragmented on UTF-8 code point boundary.

MESSAGE FRAGMENT 1:
Hello-µ@ßöä
48656c6c6f2dc2b540c39fc3b6c3a4

MESSAGE FRAGMENT 2:
üàá-UTF-8!!
c3bcc3a0c3a12d5554462d382121

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.2.3

+ Up +

Case Description

Send a valid UTF-8 text message in fragments of 1 octet, resulting in frames ending on positions which are not code point ends.

MESSAGE:
Hello-µ@ßöäüàá-UTF-8!!
48656c6c6f2dc2b540c39fc3b6c3a4c3bcc3a0c3a12d5554462d382121

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.2.4

+ Up +

Case Description

Send a valid UTF-8 text message in fragments of 1 octet, resulting in frames ending on positions which are not code point ends.

MESSAGE:
κόσμε
cebae1bdb9cf83cebcceb5

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.3.1

+ Up +

Case Description

Send invalid UTF-8 text message unfragmented.

MESSAGE:
cebae1bdb9cf83cebcceb5eda080656469746564

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.3.2

+ Up +

Case Description

Send invalid UTF-8 text message in fragments of 1 octet, resulting in frames ending on positions which are not code point ends.

MESSAGE:
cebae1bdb9cf83cebcceb5eda080656469746564

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.4.1

+ Up +

Case Description

Send invalid UTF-8 text message in 3 fragments (frames). +First frame payload is valid, then wait, then 2nd frame which contains the payload making the sequence invalid, then wait, then 3rd frame with rest. +Note that PART1 and PART3 are valid UTF-8 in themselves, PART2 is a 0x110000 encoded as in the UTF-8 integer encoding scheme, but the codepoint is invalid (out of range). +

MESSAGE PARTS:
+PART1 = cebae1bdb9cf83cebcceb5
+PART2 = f4908080
+PART3 = 656469746564
+

+

Case Expectation

The first frame is accepted, we expect to timeout on the first wait. The 2nd frame should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.

+
+ +

Case 6.4.2

+ Up +

Case Description

Same as Case 6.4.1, but in 2nd frame, we send only up to and including the octet making the complete payload invalid. +

MESSAGE PARTS:
+PART1 = cebae1bdb9cf83cebcceb5f4
+PART2 = 90
+PART3 = 8080656469746564
+

+

Case Expectation

The first frame is accepted, we expect to timeout on the first wait. The 2nd frame should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.

+
+ +

Case 6.4.3

+ Up +

Case Description

Same as Case 6.4.1, but we send message not in 3 frames, but in 3 chops of the same message frame. +

MESSAGE PARTS:
+PART1 = cebae1bdb9cf83cebcceb5
+PART2 = f4908080
+PART3 = 656469746564
+

+

Case Expectation

The first chop is accepted, we expect to timeout on the first wait. The 2nd chop should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.

+
+ +

Case 6.4.4

+ Up +

Case Description

Same as Case 6.4.2, but we send message not in 3 frames, but in 3 chops of the same message frame. +

MESSAGE PARTS:
+PART1 = cebae1bdb9cf83cebcceb5f4
+PART2 = 90
+PART3 =
+

+

Case Expectation

The first chop is accepted, we expect to timeout on the first wait. The 2nd chop should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.

+
+ +

Case 6.5.1

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x68656c6c6f24776f726c64

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.5.2

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x68656c6c6fc2a2776f726c64

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.5.3

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x68656c6c6fe282ac776f726c64

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.5.4

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x68656c6c6ff0a4ada2776f726c64

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.5.5

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83cebcceb5

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.6.1

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xce

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.6.2

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xceba

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.6.3

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xcebae1

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.6.4

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xcebae1bd

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.6.5

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.6.6

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.6.7

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.6.8

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83ce

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.6.9

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83cebc

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.6.10

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83cebcce

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.6.11

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83cebcceb5

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.7.1

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x00

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.7.2

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xc280

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.7.3

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xe0a080

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.7.4

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf0908080

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.8.1

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf888808080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.8.2

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc8480808080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.9.1

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x7f

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.9.2

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xdfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.9.3

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.9.4

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf48fbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.10.1

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf7bfbfbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.10.2

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfbbfbfbfbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.10.3

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfdbfbfbfbfbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.11.1

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xed9fbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.11.2

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xee8080

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.11.3

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbd

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.11.4

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf48fbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.11.5

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf4908080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.12.1

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.12.2

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.12.3

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80bf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.12.4

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80bf80

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.12.5

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80bf80bf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.12.6

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80bf80bf80

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.12.7

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80bf80bf80bf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.12.8

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbe

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.13.1

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc020c120c220c320c420c520c620c720c820c920ca20cb20cc20cd20ce20cf20d020d120d220d320d420d520d620d720d820d920da20db20dc20dd20de20

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.13.2

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xe020e120e220e320e420e520e620e720e820e920ea20eb20ec20ed20ee20

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.13.3

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf020f120f220f320f420f520f620

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.13.4

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf820f920fa20

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.13.5

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc20

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.14.1

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc0

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.14.2

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xe080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.14.3

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf08080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.14.4

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf8808080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.14.5

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc80808080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.14.6

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xdf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.14.7

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xefbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.14.8

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf7bfbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.14.9

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfbbfbfbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.14.10

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfdbfbfbfbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.15.1

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc0e080f08080f8808080fc80808080dfefbff7bfbffbbfbfbffdbfbfbfbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.16.1

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfe

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.16.2

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xff

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.16.3

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfefeffff

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.17.1

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc0af

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.17.2

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xe080af

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.17.3

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf08080af

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.17.4

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf8808080af

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.17.5

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc80808080af

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.18.1

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc1bf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.18.2

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xe09fbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.18.3

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf08fbfbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.18.4

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf887bfbfbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.18.5

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc83bfbfbfbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.19.1

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.19.2

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xe08080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.19.3

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf0808080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.19.4

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf880808080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.19.5

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc8080808080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.20.1

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xeda080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.20.2

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedadbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.20.3

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedae80

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.20.4

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedafbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.20.5

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedb080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.20.6

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedbe80

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.20.7

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedbfbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.21.1

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xeda080edb080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.21.2

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xeda080edbfbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.21.3

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedadbfedb080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.21.4

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedadbfedbfbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.21.5

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedae80edb080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.21.6

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedae80edbfbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.21.7

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedafbfedb080

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.21.8

+ Up +

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedafbfedbfbf

+

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

+
+ +

Case 6.22.1

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.2

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.3

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf09fbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.4

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf09fbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.5

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf0afbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.6

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf0afbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.7

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf0bfbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.8

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf0bfbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.9

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf18fbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.10

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf18fbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.11

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf19fbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.12

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf19fbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.13

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf1afbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.14

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf1afbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.15

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf1bfbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.16

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf1bfbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.17

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf28fbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.18

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf28fbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.19

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf29fbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.20

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf29fbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.21

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf2afbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.22

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf2afbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.23

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf2bfbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.24

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf2bfbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.25

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf38fbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.26

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf38fbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.27

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf39fbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.28

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf39fbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.29

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf3afbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.30

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf3afbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.31

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf3bfbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.32

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf3bfbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.33

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf48fbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.22.34

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf48fbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.23.1

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfb9

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.23.2

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfba

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.23.3

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbb

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.23.4

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbc

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.23.5

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbd

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.23.6

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbe

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 6.23.7

+ Up +

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbf

+

Case Expectation

The message is echo'ed back to us.

+
+ +

Case 7.1.1

+ Up +

Case Description

Send a message followed by a close frame

+

Case Expectation

Echoed message followed by clean close with normal code.

+
+ +

Case 7.1.2

+ Up +

Case Description

Send two close frames

+

Case Expectation

Clean close with normal code. Second close frame ignored.

+
+ +

Case 7.1.3

+ Up +

Case Description

Send a ping after close message

+

Case Expectation

Clean close with normal code, no pong.

+
+ +

Case 7.1.4

+ Up +

Case Description

Send text message after sending a close frame.

+

Case Expectation

Clean close with normal code. Text message ignored.

+
+ +

Case 7.1.5

+ Up +

Case Description

Send message fragment1 followed by close then fragment

+

Case Expectation

Clean close with normal code.

+
+ +

Case 7.1.6

+ Up +

Case Description

Send 256K message followed by close then a ping

+

Case Expectation

Case outcome depends on implementation defined close behavior. Message and close frame are sent back to back. If the close frame is processed before the text message write is complete (as can happen in asynchronous processing models) the close frame is processed first and the text message may not be received or may only be partially recieved.

+
+ +

Case 7.3.1

+ Up +

Case Description

Send a close frame with payload length 0 (no close code, no close reason)

+

Case Expectation

Clean close with normal code.

+
+ +

Case 7.3.2

+ Up +

Case Description

Send a close frame with payload length 1

+

Case Expectation

Clean close with protocol error or drop TCP.

+
+ +

Case 7.3.3

+ Up +

Case Description

Send a close frame with payload length 2 (regular close with a code)

+

Case Expectation

Clean close with normal code.

+
+ +

Case 7.3.4

+ Up +

Case Description

Send a close frame with close code and close reason

+

Case Expectation

Clean close with normal code.

+
+ +

Case 7.3.5

+ Up +

Case Description

Send a close frame with close code and close reason of maximum length (123)

+

Case Expectation

Clean close with normal code.

+
+ +

Case 7.3.6

+ Up +

Case Description

Send a close frame with close code and close reason which is too long (124) - total frame payload 126 octets

+

Case Expectation

Clean close with protocol error code or dropped TCP connection.

+
+ +

Case 7.5.1

+ Up +

Case Description

Send a close frame with invalid UTF8 payload

+

Case Expectation

Clean close with protocol error or invalid utf8 code or dropped TCP.

+
+ +

Case 7.7.1

+ Up +

Case Description

Send close with valid close code 1000

+

Case Expectation

Clean close with normal or echoed code

+
+ +

Case 7.7.2

+ Up +

Case Description

Send close with valid close code 1001

+

Case Expectation

Clean close with normal or echoed code

+
+ +

Case 7.7.3

+ Up +

Case Description

Send close with valid close code 1002

+

Case Expectation

Clean close with normal or echoed code

+
+ +

Case 7.7.4

+ Up +

Case Description

Send close with valid close code 1003

+

Case Expectation

Clean close with normal or echoed code

+
+ +

Case 7.7.5

+ Up +

Case Description

Send close with valid close code 1007

+

Case Expectation

Clean close with normal or echoed code

+
+ +

Case 7.7.6

+ Up +

Case Description

Send close with valid close code 1008

+

Case Expectation

Clean close with normal or echoed code

+
+ +

Case 7.7.7

+ Up +

Case Description

Send close with valid close code 1009

+

Case Expectation

Clean close with normal or echoed code

+
+ +

Case 7.7.8

+ Up +

Case Description

Send close with valid close code 1010

+

Case Expectation

Clean close with normal or echoed code

+
+ +

Case 7.7.9

+ Up +

Case Description

Send close with valid close code 1011

+

Case Expectation

Clean close with normal or echoed code

+
+ +

Case 7.7.10

+ Up +

Case Description

Send close with valid close code 3000

+

Case Expectation

Clean close with normal or echoed code

+
+ +

Case 7.7.11

+ Up +

Case Description

Send close with valid close code 3999

+

Case Expectation

Clean close with normal or echoed code

+
+ +

Case 7.7.12

+ Up +

Case Description

Send close with valid close code 4000

+

Case Expectation

Clean close with normal or echoed code

+
+ +

Case 7.7.13

+ Up +

Case Description

Send close with valid close code 4999

+

Case Expectation

Clean close with normal or echoed code

+
+ +

Case 7.9.1

+ Up +

Case Description

Send close with invalid close code 0

+

Case Expectation

Clean close with protocol error code or drop TCP

+
+ +

Case 7.9.2

+ Up +

Case Description

Send close with invalid close code 999

+

Case Expectation

Clean close with protocol error code or drop TCP

+
+ +

Case 7.9.3

+ Up +

Case Description

Send close with invalid close code 1004

+

Case Expectation

Clean close with protocol error code or drop TCP

+
+ +

Case 7.9.4

+ Up +

Case Description

Send close with invalid close code 1005

+

Case Expectation

Clean close with protocol error code or drop TCP

+
+ +

Case 7.9.5

+ Up +

Case Description

Send close with invalid close code 1006

+

Case Expectation

Clean close with protocol error code or drop TCP

+
+ +

Case 7.9.6

+ Up +

Case Description

Send close with invalid close code 1016

+

Case Expectation

Clean close with protocol error code or drop TCP

+
+ +

Case 7.9.7

+ Up +

Case Description

Send close with invalid close code 1100

+

Case Expectation

Clean close with protocol error code or drop TCP

+
+ +

Case 7.9.8

+ Up +

Case Description

Send close with invalid close code 2000

+

Case Expectation

Clean close with protocol error code or drop TCP

+
+ +

Case 7.9.9

+ Up +

Case Description

Send close with invalid close code 2999

+

Case Expectation

Clean close with protocol error code or drop TCP

+
+ +

Case 7.13.1

+ Up +

Case Description

Send close with close code 5000

+

Case Expectation

Actual events are undefined by the spec.

+
+ +

Case 7.13.2

+ Up +

Case Description

Send close with close code 65536

+

Case Expectation

Actual events are undefined by the spec.

+
+ +

Case 9.1.1

+ Up +

Case Description

Send text message message with payload of length 64 * 2**10 (64k).

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.1.2

+ Up +

Case Description

Send text message message with payload of length 256 * 2**10 (256k).

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.1.3

+ Up +

Case Description

Send text message message with payload of length 1 * 2**20 (1M).

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.1.4

+ Up +

Case Description

Send text message message with payload of length 4 * 2**20 (4M).

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.1.5

+ Up +

Case Description

Send text message message with payload of length 8 * 2**20 (8M).

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.1.6

+ Up +

Case Description

Send text message message with payload of length 16 * 2**20 (16M).

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.2.1

+ Up +

Case Description

Send binary message message with payload of length 64 * 2**10 (64k).

+

Case Expectation

Receive echo'ed binary message (with payload as sent).

+
+ +

Case 9.2.2

+ Up +

Case Description

Send binary message message with payload of length 256 * 2**10 (256k).

+

Case Expectation

Receive echo'ed binary message (with payload as sent).

+
+ +

Case 9.2.3

+ Up +

Case Description

Send binary message message with payload of length 1 * 2**20 (1M).

+

Case Expectation

Receive echo'ed binary message (with payload as sent).

+
+ +

Case 9.2.4

+ Up +

Case Description

Send binary message message with payload of length 4 * 2**20 (4M).

+

Case Expectation

Receive echo'ed binary message (with payload as sent).

+
+ +

Case 9.2.5

+ Up +

Case Description

Send binary message message with payload of length 8 * 2**20 (16M).

+

Case Expectation

Receive echo'ed binary message (with payload as sent).

+
+ +

Case 9.2.6

+ Up +

Case Description

Send binary message message with payload of length 16 * 2**20 (16M).

+

Case Expectation

Receive echo'ed binary message (with payload as sent).

+
+ +

Case 9.3.1

+ Up +

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 64.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.3.2

+ Up +

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 256.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.3.3

+ Up +

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 1k.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.3.4

+ Up +

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 4k.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.3.5

+ Up +

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 16k.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.3.6

+ Up +

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 64k.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.3.7

+ Up +

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 256k.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.3.8

+ Up +

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 1M.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.3.9

+ Up +

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (8M). Sent out in fragments of 4M.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.4.1

+ Up +

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 64.

+

Case Expectation

Receive echo'ed binary message (with payload as sent).

+
+ +

Case 9.4.2

+ Up +

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 256.

+

Case Expectation

Receive echo'ed binary message (with payload as sent).

+
+ +

Case 9.4.3

+ Up +

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 1k.

+

Case Expectation

Receive echo'ed binary message (with payload as sent).

+
+ +

Case 9.4.4

+ Up +

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 4k.

+

Case Expectation

Receive echo'ed binary message (with payload as sent).

+
+ +

Case 9.4.5

+ Up +

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 16k.

+

Case Expectation

Receive echo'ed binary message (with payload as sent).

+
+ +

Case 9.4.6

+ Up +

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 64k.

+

Case Expectation

Receive echo'ed binary message (with payload as sent).

+
+ +

Case 9.4.7

+ Up +

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 256k.

+

Case Expectation

Receive echo'ed binary message (with payload as sent).

+
+ +

Case 9.4.8

+ Up +

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 1M.

+

Case Expectation

Receive echo'ed binary message (with payload as sent).

+
+ +

Case 9.4.9

+ Up +

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 4M.

+

Case Expectation

Receive echo'ed binary message (with payload as sent).

+
+ +

Case 9.5.1

+ Up +

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 64 octets.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.5.2

+ Up +

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 128 octets.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.5.3

+ Up +

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 256 octets.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.5.4

+ Up +

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 512 octets.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.5.5

+ Up +

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 1024 octets.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.5.6

+ Up +

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 2048 octets.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.6.1

+ Up +

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 64 octets.

+

Case Expectation

Receive echo'ed binary message (with payload as sent).

+
+ +

Case 9.6.2

+ Up +

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 128 octets.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.6.3

+ Up +

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 256 octets.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.6.4

+ Up +

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 512 octets.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.6.5

+ Up +

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 1024 octets.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.6.6

+ Up +

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 2048 octets.

+

Case Expectation

Receive echo'ed text message (with payload as sent).

+
+ +

Case 9.7.1

+ Up +

Case Description

Send 1000 text messages of payload size 0 to measure implementation/network RTT (round trip time) / latency.

+

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 9.7.2

+ Up +

Case Description

Send 1000 text messages of payload size 16 to measure implementation/network RTT (round trip time) / latency.

+

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 9.7.3

+ Up +

Case Description

Send 1000 text messages of payload size 64 to measure implementation/network RTT (round trip time) / latency.

+

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 9.7.4

+ Up +

Case Description

Send 1000 text messages of payload size 256 to measure implementation/network RTT (round trip time) / latency.

+

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 120 secs.

+
+ +

Case 9.7.5

+ Up +

Case Description

Send 1000 text messages of payload size 1024 to measure implementation/network RTT (round trip time) / latency.

+

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 240 secs.

+
+ +

Case 9.7.6

+ Up +

Case Description

Send 1000 text messages of payload size 4096 to measure implementation/network RTT (round trip time) / latency.

+

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 9.8.1

+ Up +

Case Description

Send 1000 binary messages of payload size 0 to measure implementation/network RTT (round trip time) / latency.

+

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 9.8.2

+ Up +

Case Description

Send 1000 binary messages of payload size 16 to measure implementation/network RTT (round trip time) / latency.

+

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 9.8.3

+ Up +

Case Description

Send 1000 binary messages of payload size 64 to measure implementation/network RTT (round trip time) / latency.

+

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 9.8.4

+ Up +

Case Description

Send 1000 binary messages of payload size 256 to measure implementation/network RTT (round trip time) / latency.

+

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 120 secs.

+
+ +

Case 9.8.5

+ Up +

Case Description

Send 1000 binary messages of payload size 1024 to measure implementation/network RTT (round trip time) / latency.

+

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 240 secs.

+
+ +

Case 9.8.6

+ Up +

Case Description

Send 1000 binary messages of payload size 4096 to measure implementation/network RTT (round trip time) / latency.

+

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 10.1.1

+ Up +

Case Description

Send text message with payload of length 65536 auto-fragmented with autoFragmentSize = 1300.

+

Case Expectation

Receive echo'ed text message (with payload as sent and transmitted frame counts as expected). Clean close with normal code.

+
+ +

Case 12.1.1

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 12.1.2

+ Up +

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 12.1.3

+ Up +

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

+
+ +

Case 12.1.4

+ Up +

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

+
+ +

Case 12.1.5

+ Up +

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.1.6

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.1.7

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.1.8

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.1.9

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.1.10

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.1.11

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.1.12

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.1.13

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.1.14

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.1.15

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.1.16

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.1.17

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.1.18

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.2.1

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 12.2.2

+ Up +

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 12.2.3

+ Up +

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

+
+ +

Case 12.2.4

+ Up +

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

+
+ +

Case 12.2.5

+ Up +

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.2.6

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.2.7

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.2.8

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.2.9

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.2.10

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.2.11

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.2.12

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.2.13

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.2.14

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.2.15

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.2.16

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.2.17

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.2.18

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.3.1

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 12.3.2

+ Up +

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 12.3.3

+ Up +

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

+
+ +

Case 12.3.4

+ Up +

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

+
+ +

Case 12.3.5

+ Up +

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.3.6

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.3.7

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.3.8

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.3.9

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.3.10

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.3.11

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.3.12

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.3.13

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.3.14

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.3.15

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.3.16

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.3.17

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.3.18

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.4.1

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 12.4.2

+ Up +

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 12.4.3

+ Up +

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

+
+ +

Case 12.4.4

+ Up +

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

+
+ +

Case 12.4.5

+ Up +

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.4.6

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.4.7

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.4.8

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.4.9

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.4.10

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.4.11

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.4.12

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.4.13

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.4.14

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.4.15

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.4.16

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.4.17

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.4.18

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.5.1

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 12.5.2

+ Up +

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 12.5.3

+ Up +

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

+
+ +

Case 12.5.4

+ Up +

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

+
+ +

Case 12.5.5

+ Up +

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.5.6

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.5.7

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.5.8

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.5.9

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.5.10

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.5.11

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.5.12

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.5.13

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.5.14

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.5.15

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.5.16

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.5.17

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 12.5.18

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use default permessage-deflate offer.

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.1.1

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 13.1.2

+ Up +

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 13.1.3

+ Up +

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

+
+ +

Case 13.1.4

+ Up +

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

+
+ +

Case 13.1.5

+ Up +

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.1.6

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.1.7

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.1.8

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.1.9

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.1.10

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.1.11

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.1.12

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.1.13

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.1.14

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.1.15

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.1.16

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.1.17

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.1.18

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.2.1

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 13.2.2

+ Up +

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 13.2.3

+ Up +

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

+
+ +

Case 13.2.4

+ Up +

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

+
+ +

Case 13.2.5

+ Up +

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.2.6

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.2.7

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.2.8

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.2.9

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.2.10

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.2.11

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.2.12

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.2.13

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.2.14

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.2.15

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.2.16

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.2.17

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.2.18

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.3.1

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 13.3.2

+ Up +

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 13.3.3

+ Up +

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

+
+ +

Case 13.3.4

+ Up +

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

+
+ +

Case 13.3.5

+ Up +

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.3.6

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.3.7

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.3.8

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.3.9

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.3.10

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.3.11

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.3.12

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.3.13

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.3.14

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.3.15

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.3.16

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.3.17

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.3.18

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.4.1

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 13.4.2

+ Up +

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 13.4.3

+ Up +

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

+
+ +

Case 13.4.4

+ Up +

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

+
+ +

Case 13.4.5

+ Up +

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.4.6

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.4.7

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.4.8

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.4.9

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.4.10

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.4.11

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.4.12

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.4.13

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.4.14

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.4.15

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.4.16

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.4.17

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.4.18

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.5.1

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 13.5.2

+ Up +

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 13.5.3

+ Up +

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

+
+ +

Case 13.5.4

+ Up +

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

+
+ +

Case 13.5.5

+ Up +

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.5.6

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.5.7

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.5.8

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.5.9

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.5.10

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.5.11

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.5.12

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.5.13

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.5.14

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.5.15

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.5.16

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.5.17

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.5.18

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.6.1

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 13.6.2

+ Up +

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 13.6.3

+ Up +

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

+
+ +

Case 13.6.4

+ Up +

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

+
+ +

Case 13.6.5

+ Up +

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.6.6

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.6.7

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.6.8

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.6.9

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.6.10

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.6.11

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.6.12

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.6.13

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.6.14

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.6.15

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.6.16

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.6.17

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.6.18

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.7.1

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 13.7.2

+ Up +

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

+
+ +

Case 13.7.3

+ Up +

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

+
+ +

Case 13.7.4

+ Up +

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

+
+ +

Case 13.7.5

+ Up +

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.7.6

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.7.7

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.7.8

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.7.9

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.7.10

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.7.11

+ Up +

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.7.12

+ Up +

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.7.13

+ Up +

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.7.14

+ Up +

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.7.15

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.7.16

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.7.17

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+ +

Case 13.7.18

+ Up +

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

+

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

+
+

+ + From dc3934e927746a709f6b869ef5a1232422b2eb13 Mon Sep 17 00:00:00 2001 From: Harun Tuncay Date: Wed, 17 Apr 2019 23:56:00 +0300 Subject: [PATCH 012/165] Delete index.html --- index.html | 5923 ---------------------------------------------------- 1 file changed, 5923 deletions(-) delete mode 100644 index.html diff --git a/index.html b/index.html deleted file mode 100644 index 5c6c573e2..000000000 --- a/index.html +++ /dev/null @@ -1,5923 +0,0 @@ - - - - - - - - - -
Toggle Details
- -
-
Autobahn WebSocket Testsuite Report
-
Autobahn WebSocket
-
-

Summary report generated on 2019-04-12T14:37:19.401Z (UTC) by Autobahn WebSocket Testsuite v0.8.1/v0.10.9.

- - - - - - - - - - - - - - - - - - - - - - -
PassTest case was executed and passed successfully.
Non-StrictTest case was executed and passed non-strictly. - A non-strict behavior is one that does not adhere to a SHOULD-behavior as described in the protocol specification or - a well-defined, canonical behavior that appears to be desirable but left open in the protocol specification. - An implementation with non-strict behavior is still conformant to the protocol specification.
FailTest case was executed and failed. An implementation which fails a test case - other - than a performance/limits related one - is non-conforming to a MUST-behavior as described in the protocol specification.
InfoInformational test case which detects certain implementation behavior left unspecified by the spec - but nevertheless potentially interesting to implementors.
MissingTest case is missing, either because it was skipped via the test suite configuration - or deactivated, i.e. because the implementation does not implement the tested feature or breaks during running - the test case.
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1 FramingTooTallNate Java-WebSocket
1.1 Text Messages
Case 1.1.1Missing
Case 1.1.2Missing
Case 1.1.3Missing
Case 1.1.4Missing
Case 1.1.5Missing
Case 1.1.6Missing
Case 1.1.7Missing
Case 1.1.8Missing
1 FramingTooTallNate Java-WebSocket
1.2 Binary Messages
Case 1.2.1Missing
Case 1.2.2Missing
Case 1.2.3Missing
Case 1.2.4Missing
Case 1.2.5Missing
Case 1.2.6Missing
Case 1.2.7Missing
Case 1.2.8Missing
2 Pings/PongsTooTallNate Java-WebSocket
Case 2.1Missing
Case 2.2Missing
Case 2.3Missing
Case 2.4Missing
Case 2.5Missing
Case 2.6Missing
Case 2.7Missing
Case 2.8Missing
Case 2.9Missing
Case 2.10Missing
Case 2.11Missing
3 Reserved BitsTooTallNate Java-WebSocket
Case 3.1Missing
Case 3.2Missing
Case 3.3Missing
Case 3.4Missing
Case 3.5Missing
Case 3.6Missing
Case 3.7Missing
4 OpcodesTooTallNate Java-WebSocket
4.1 Non-control Opcodes
Case 4.1.1Missing
Case 4.1.2Missing
Case 4.1.3Missing
Case 4.1.4Missing
Case 4.1.5Missing
4 OpcodesTooTallNate Java-WebSocket
4.2 Control Opcodes
Case 4.2.1Missing
Case 4.2.2Missing
Case 4.2.3Missing
Case 4.2.4Missing
Case 4.2.5Missing
5 FragmentationTooTallNate Java-WebSocket
Case 5.1Missing
Case 5.2Missing
Case 5.3Missing
Case 5.4Missing
Case 5.5Missing
Case 5.6Missing
Case 5.7Missing
Case 5.8Missing
Case 5.9Missing
Case 5.10Missing
Case 5.11Missing
Case 5.12Missing
Case 5.13Missing
Case 5.14Missing
Case 5.15Missing
Case 5.16Missing
Case 5.17Missing
Case 5.18Missing
Case 5.19Missing
Case 5.20Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.1 Valid UTF-8 with zero payload fragments
Case 6.1.1Missing
Case 6.1.2Missing
Case 6.1.3Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.2 Valid UTF-8 unfragmented, fragmented on code-points and within code-points
Case 6.2.1Missing
Case 6.2.2Missing
Case 6.2.3Missing
Case 6.2.4Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.3 Invalid UTF-8 differently fragmented
Case 6.3.1Missing
Case 6.3.2Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.4 Fail-fast on invalid UTF-8
Case 6.4.1Missing
Case 6.4.2Missing
Case 6.4.3Missing
Case 6.4.4Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.5 Some valid UTF-8 sequences
Case 6.5.1Missing
Case 6.5.2Missing
Case 6.5.3Missing
Case 6.5.4Missing
Case 6.5.5Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.6 All prefixes of a valid UTF-8 string that contains multi-byte code points
Case 6.6.1Missing
Case 6.6.2Missing
Case 6.6.3Missing
Case 6.6.4Missing
Case 6.6.5Missing
Case 6.6.6Missing
Case 6.6.7Missing
Case 6.6.8Missing
Case 6.6.9Missing
Case 6.6.10Missing
Case 6.6.11Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.7 First possible sequence of a certain length
Case 6.7.1Missing
Case 6.7.2Missing
Case 6.7.3Missing
Case 6.7.4Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.8 First possible sequence length 5/6 (invalid codepoints)
Case 6.8.1Missing
Case 6.8.2Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.9 Last possible sequence of a certain length
Case 6.9.1Missing
Case 6.9.2Missing
Case 6.9.3Missing
Case 6.9.4Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.10 Last possible sequence length 4/5/6 (invalid codepoints)
Case 6.10.1Missing
Case 6.10.2Missing
Case 6.10.3Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.11 Other boundary conditions
Case 6.11.1Missing
Case 6.11.2Missing
Case 6.11.3Missing
Case 6.11.4Missing
Case 6.11.5Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.12 Unexpected continuation bytes
Case 6.12.1Missing
Case 6.12.2Missing
Case 6.12.3Missing
Case 6.12.4Missing
Case 6.12.5Missing
Case 6.12.6Missing
Case 6.12.7Missing
Case 6.12.8Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.13 Lonely start characters
Case 6.13.1Missing
Case 6.13.2Missing
Case 6.13.3Missing
Case 6.13.4Missing
Case 6.13.5Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.14 Sequences with last continuation byte missing
Case 6.14.1Missing
Case 6.14.2Missing
Case 6.14.3Missing
Case 6.14.4Missing
Case 6.14.5Missing
Case 6.14.6Missing
Case 6.14.7Missing
Case 6.14.8Missing
Case 6.14.9Missing
Case 6.14.10Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.15 Concatenation of incomplete sequences
Case 6.15.1Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.16 Impossible bytes
Case 6.16.1Missing
Case 6.16.2Missing
Case 6.16.3Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.17 Examples of an overlong ASCII character
Case 6.17.1Missing
Case 6.17.2Missing
Case 6.17.3Missing
Case 6.17.4Missing
Case 6.17.5Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.18 Maximum overlong sequences
Case 6.18.1Missing
Case 6.18.2Missing
Case 6.18.3Missing
Case 6.18.4Missing
Case 6.18.5Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.19 Overlong representation of the NUL character
Case 6.19.1Missing
Case 6.19.2Missing
Case 6.19.3Missing
Case 6.19.4Missing
Case 6.19.5Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.20 Single UTF-16 surrogates
Case 6.20.1Missing
Case 6.20.2Missing
Case 6.20.3Missing
Case 6.20.4Missing
Case 6.20.5Missing
Case 6.20.6Missing
Case 6.20.7Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.21 Paired UTF-16 surrogates
Case 6.21.1Missing
Case 6.21.2Missing
Case 6.21.3Missing
Case 6.21.4Missing
Case 6.21.5Missing
Case 6.21.6Missing
Case 6.21.7Missing
Case 6.21.8Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.22 Non-character code points (valid UTF-8)
Case 6.22.1Missing
Case 6.22.2Missing
Case 6.22.3Missing
Case 6.22.4Missing
Case 6.22.5Missing
Case 6.22.6Missing
Case 6.22.7Missing
Case 6.22.8Missing
Case 6.22.9Missing
Case 6.22.10Missing
Case 6.22.11Missing
Case 6.22.12Missing
Case 6.22.13Missing
Case 6.22.14Missing
Case 6.22.15Missing
Case 6.22.16Missing
Case 6.22.17Missing
Case 6.22.18Missing
Case 6.22.19Missing
Case 6.22.20Missing
Case 6.22.21Missing
Case 6.22.22Missing
Case 6.22.23Missing
Case 6.22.24Missing
Case 6.22.25Missing
Case 6.22.26Missing
Case 6.22.27Missing
Case 6.22.28Missing
Case 6.22.29Missing
Case 6.22.30Missing
Case 6.22.31Missing
Case 6.22.32Missing
Case 6.22.33Missing
Case 6.22.34Missing
6 UTF-8 HandlingTooTallNate Java-WebSocket
6.23 Unicode specials (i.e. replacement char)
Case 6.23.1Missing
Case 6.23.2Missing
Case 6.23.3Missing
Case 6.23.4Missing
Case 6.23.5Missing
Case 6.23.6Missing
Case 6.23.7Missing
7 Close HandlingTooTallNate Java-WebSocket
7.1 Basic close behavior (fuzzer initiated)
Case 7.1.1Missing
Case 7.1.2Missing
Case 7.1.3Missing
Case 7.1.4Missing
Case 7.1.5Missing
Case 7.1.6Missing
7 Close HandlingTooTallNate Java-WebSocket
7.3 Close frame structure: payload length (fuzzer initiated)
Case 7.3.1Missing
Case 7.3.2Missing
Case 7.3.3Missing
Case 7.3.4Missing
Case 7.3.5Missing
Case 7.3.6Missing
7 Close HandlingTooTallNate Java-WebSocket
7.5 Close frame structure: payload value (fuzzer initiated)
Case 7.5.1Missing
7 Close HandlingTooTallNate Java-WebSocket
7.7 Close frame structure: valid close codes (fuzzer initiated)
Case 7.7.1Missing
Case 7.7.2Missing
Case 7.7.3Missing
Case 7.7.4Missing
Case 7.7.5Missing
Case 7.7.6Missing
Case 7.7.7Missing
Case 7.7.8Missing
Case 7.7.9Missing
Case 7.7.10Missing
Case 7.7.11Missing
Case 7.7.12Missing
Case 7.7.13Missing
7 Close HandlingTooTallNate Java-WebSocket
7.9 Close frame structure: invalid close codes (fuzzer initiated)
Case 7.9.1Missing
Case 7.9.2Missing
Case 7.9.3Missing
Case 7.9.4Missing
Case 7.9.5Missing
Case 7.9.6Missing
Case 7.9.7Missing
Case 7.9.8Missing
Case 7.9.9Missing
7 Close HandlingTooTallNate Java-WebSocket
7.13 Informational close information (fuzzer initiated)
Case 7.13.1Missing
Case 7.13.2Missing
9 Limits/PerformanceTooTallNate Java-WebSocket
9.1 Text Message (increasing size)
Case 9.1.1Missing
Case 9.1.2Missing
Case 9.1.3Missing
Case 9.1.4Missing
Case 9.1.5Missing
Case 9.1.6Missing
9 Limits/PerformanceTooTallNate Java-WebSocket
9.2 Binary Message (increasing size)
Case 9.2.1Missing
Case 9.2.2Missing
Case 9.2.3Missing
Case 9.2.4Missing
Case 9.2.5Missing
Case 9.2.6Missing
9 Limits/PerformanceTooTallNate Java-WebSocket
9.3 Fragmented Text Message (fixed size, increasing fragment size)
Case 9.3.1Missing
Case 9.3.2Missing
Case 9.3.3Missing
Case 9.3.4Missing
Case 9.3.5Missing
Case 9.3.6Missing
Case 9.3.7Missing
Case 9.3.8Missing
Case 9.3.9Missing
9 Limits/PerformanceTooTallNate Java-WebSocket
9.4 Fragmented Binary Message (fixed size, increasing fragment size)
Case 9.4.1Missing
Case 9.4.2Missing
Case 9.4.3Missing
Case 9.4.4Missing
Case 9.4.5Missing
Case 9.4.6Missing
Case 9.4.7Missing
Case 9.4.8Missing
Case 9.4.9Missing
9 Limits/PerformanceTooTallNate Java-WebSocket
9.5 Text Message (fixed size, increasing chop size)
Case 9.5.1Missing
Case 9.5.2Missing
Case 9.5.3Missing
Case 9.5.4Missing
Case 9.5.5Missing
Case 9.5.6Missing
9 Limits/PerformanceTooTallNate Java-WebSocket
9.6 Binary Text Message (fixed size, increasing chop size)
Case 9.6.1Missing
Case 9.6.2Missing
Case 9.6.3Missing
Case 9.6.4Missing
Case 9.6.5Missing
Case 9.6.6Missing
9 Limits/PerformanceTooTallNate Java-WebSocket
9.7 Text Message Roundtrip Time (fixed number, increasing size)
Case 9.7.1Missing
Case 9.7.2Missing
Case 9.7.3Missing
Case 9.7.4Missing
Case 9.7.5Missing
Case 9.7.6Missing
9 Limits/PerformanceTooTallNate Java-WebSocket
9.8 Binary Message Roundtrip Time (fixed number, increasing size)
Case 9.8.1Missing
Case 9.8.2Missing
Case 9.8.3Missing
Case 9.8.4Missing
Case 9.8.5Missing
Case 9.8.6Missing
10 MiscTooTallNate Java-WebSocket
10.1 Auto-Fragmentation
Case 10.1.1Missing
12 WebSocket Compression (different payloads)TooTallNate Java-WebSocket
12.1 Large JSON data file (utf8, 194056 bytes)
Case 12.1.1Pass
629 ms [1.000/0.985]
1000
Case 12.1.2Pass
530 ms [1.000/0.748]
1000
Case 12.1.3Pass
580 ms [1.000/0.521]
1000
Case 12.1.4Pass
586 ms [1.000/0.170]
1000
Case 12.1.5Pass
680 ms [1.000/0.075]
1000
Case 12.1.6Pass
743 ms [1.000/0.059]
1000
Case 12.1.7Pass
925 ms [1.000/0.051]
1000
Case 12.1.8Pass
1399 ms [1.000/0.047]
1000
Case 12.1.9Pass
2314 ms [1.000/0.045]
1000
Case 12.1.10Pass
4054 ms [1.000/0.044]
1000
Case 12.1.11Pass
791 ms [1.000/0.059]
1000
Case 12.1.12Pass
1062 ms [1.000/0.051]
1000
Case 12.1.13Pass
1434 ms [1.000/0.047]
1000
Case 12.1.14Pass
2321 ms [1.000/0.045]
1000
Case 12.1.15Pass
4176 ms [1.000/0.044]
1000
Case 12.1.16Pass
4347 ms [1.000/0.044]
1000
Case 12.1.17Pass
4341 ms [1.000/0.044]
1000
Case 12.1.18Pass
3812 ms [1.000/0.044]
1000
12 WebSocket Compression (different payloads)TooTallNate Java-WebSocket
12.2 Lena Picture, Bitmap 512x512 bw (binary, 263222 bytes)
Case 12.2.1Pass
227 ms [1.000/1.174]
1000
Case 12.2.2Pass
267 ms [1.000/1.045]
1000
Case 12.2.3Pass
243 ms [1.000/1.008]
1000
Case 12.2.4Pass
310 ms [1.000/0.949]
1000
Case 12.2.5Pass
426 ms [1.000/0.889]
1000
Case 12.2.6Pass
609 ms [1.000/0.873]
1000
Case 12.2.7Pass
943 ms [1.000/0.865]
1000
Case 12.2.8Pass
1781 ms [1.000/0.860]
1000
Case 12.2.9Pass
3846 ms [1.000/0.855]
1000
Case 12.2.10Pass
8088 ms [1.000/0.853]
1000
Case 12.2.11Pass
931 ms [1.000/0.873]
1000
Case 12.2.12Pass
1584 ms [1.000/0.865]
1000
Case 12.2.13Pass
2828 ms [1.000/0.860]
1000
Case 12.2.14Pass
5984 ms [1.000/0.855]
1000
Case 12.2.15Pass
12014 ms [1.000/0.853]
1000
Case 12.2.16Pass
9343 ms [1.000/0.853]
1000
Case 12.2.17Pass
8312 ms [1.000/0.853]
1000
Case 12.2.18Pass
7942 ms [1.000/0.853]
1000
12 WebSocket Compression (different payloads)TooTallNate Java-WebSocket
12.3 Human readable text, Goethe's Faust I (German) (binary, 222218 bytes)
Case 12.3.1Pass
215 ms [1.000/1.122]
1000
Case 12.3.2Pass
221 ms [1.000/0.976]
1000
Case 12.3.3Pass
258 ms [1.000/0.725]
1000
Case 12.3.4Pass
291 ms [1.000/0.564]
1000
Case 12.3.5Pass
437 ms [1.000/0.481]
1000
Case 12.3.6Pass
693 ms [1.000/0.453]
1000
Case 12.3.7Pass
1220 ms [1.000/0.432]
1000
Case 12.3.8Pass
2539 ms [1.000/0.415]
1000
Case 12.3.9Pass
5329 ms [1.000/0.401]
1000
Case 12.3.10Pass
10841 ms [1.000/0.393]
1000
Case 12.3.11Pass
967 ms [1.000/0.453]
1000
Case 12.3.12Pass
1545 ms [1.000/0.432]
1000
Case 12.3.13Pass
3089 ms [1.000/0.415]
1000
Case 12.3.14Pass
6436 ms [1.000/0.401]
1000
Case 12.3.15Pass
13066 ms [1.000/0.393]
1000
Case 12.3.16Pass
11125 ms [1.000/0.393]
1000
Case 12.3.17Pass
11066 ms [1.000/0.393]
1000
Case 12.3.18Pass
11809 ms [1.000/0.393]
1000
12 WebSocket Compression (different payloads)TooTallNate Java-WebSocket
12.4 Large HTML file (utf8, 263527 bytes)
Case 12.4.1Pass
598 ms [1.000/1.048]
1000
Case 12.4.2Pass
602 ms [1.000/0.832]
1000
Case 12.4.3Pass
619 ms [1.000/0.623]
1000
Case 12.4.4Pass
614 ms [1.000/0.262]
1000
Case 12.4.5Pass
734 ms [1.000/0.112]
1000
Case 12.4.6Pass
846 ms [1.000/0.083]
1000
Case 12.4.7Pass
1017 ms [1.000/0.069]
1000
Case 12.4.8Pass
1381 ms [1.000/0.061]
1000
Case 12.4.9Pass
2304 ms [1.000/0.058]
1000
Case 12.4.10Pass
4112 ms [1.000/0.057]
1000
Case 12.4.11Pass
904 ms [1.000/0.083]
1000
Case 12.4.12Pass
1042 ms [1.000/0.069]
1000
Case 12.4.13Pass
1542 ms [1.000/0.061]
1000
Case 12.4.14Pass
2577 ms [1.000/0.058]
1000
Case 12.4.15Pass
4434 ms [1.000/0.057]
1000
Case 12.4.16Pass
4285 ms [1.000/0.057]
1000
Case 12.4.17Pass
4446 ms [1.000/0.057]
1000
Case 12.4.18Pass
4198 ms [1.000/0.057]
1000
12 WebSocket Compression (different payloads)TooTallNate Java-WebSocket
12.5 A larger PDF (binary, 1042328 bytes)
Case 12.5.1Pass
210 ms [1.000/1.175]
1000
Case 12.5.2Pass
238 ms [1.000/1.074]
1000
Case 12.5.3Pass
298 ms [1.000/1.004]
1000
Case 12.5.4Pass
305 ms [1.000/0.900]
1000
Case 12.5.5Pass
407 ms [1.000/0.855]
1000
Case 12.5.6Pass
550 ms [1.000/0.819]
1000
Case 12.5.7Pass
838 ms [1.000/0.793]
1000
Case 12.5.8Pass
1633 ms [1.000/0.777]
1000
Case 12.5.9Pass
3097 ms [1.000/0.768]
1000
Case 12.5.10Pass
6205 ms [1.000/0.763]
1000
Case 12.5.11Pass
907 ms [1.000/0.819]
1000
Case 12.5.12Pass
1439 ms [1.000/0.793]
1000
Case 12.5.13Pass
2418 ms [1.000/0.777]
1000
Case 12.5.14Pass
4615 ms [1.000/0.768]
1000
Case 12.5.15Pass
9603 ms [1.000/0.763]
1000
Case 12.5.16Pass
7019 ms [1.000/0.763]
1000
Case 12.5.17Pass
6347 ms [1.000/0.763]
1000
Case 12.5.18Pass
6237 ms [1.000/0.763]
1000
13 WebSocket Compression (different parameters)TooTallNate Java-WebSocket
13.1 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]
Case 13.1.1Pass
477 ms [1.000/0.985]
1000
Case 13.1.2Pass
521 ms [1.000/0.748]
1000
Case 13.1.3Pass
544 ms [1.000/0.521]
1000
Case 13.1.4Pass
525 ms [1.000/0.170]
1000
Case 13.1.5Pass
650 ms [1.000/0.075]
1000
Case 13.1.6Pass
745 ms [1.000/0.059]
1000
Case 13.1.7Pass
939 ms [1.000/0.051]
1000
Case 13.1.8Pass
1324 ms [1.000/0.047]
1000
Case 13.1.9Pass
2252 ms [1.000/0.045]
1000
Case 13.1.10Pass
3988 ms [1.000/0.044]
1000
Case 13.1.11Pass
806 ms [1.000/0.059]
1000
Case 13.1.12Pass
977 ms [1.000/0.051]
1000
Case 13.1.13Pass
1467 ms [1.000/0.047]
1000
Case 13.1.14Pass
2335 ms [1.000/0.045]
1000
Case 13.1.15Pass
4039 ms [1.000/0.044]
1000
Case 13.1.16Pass
4009 ms [1.000/0.044]
1000
Case 13.1.17Pass
4423 ms [1.000/0.044]
1000
Case 13.1.18Pass
3806 ms [1.000/0.044]
1000
13 WebSocket Compression (different parameters)TooTallNate Java-WebSocket
13.2 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]
Case 13.2.1Pass
453 ms [1.000/0.985]
1000
Case 13.2.2Pass
496 ms [1.000/0.748]
1000
Case 13.2.3Pass
492 ms [1.000/0.521]
1000
Case 13.2.4Pass
555 ms [1.000/0.170]
1000
Case 13.2.5Pass
635 ms [1.000/0.075]
1000
Case 13.2.6Pass
711 ms [1.000/0.059]
1000
Case 13.2.7Pass
931 ms [1.000/0.051]
1000
Case 13.2.8Pass
1270 ms [1.000/0.047]
1000
Case 13.2.9Pass
2134 ms [1.000/0.045]
1000
Case 13.2.10Pass
3863 ms [1.000/0.044]
1000
Case 13.2.11Pass
779 ms [1.000/0.059]
1000
Case 13.2.12Pass
973 ms [1.000/0.051]
1000
Case 13.2.13Pass
1389 ms [1.000/0.047]
1000
Case 13.2.14Pass
2201 ms [1.000/0.045]
1000
Case 13.2.15Pass
4032 ms [1.000/0.044]
1000
Case 13.2.16Pass
3992 ms [1.000/0.044]
1000
Case 13.2.17Pass
4234 ms [1.000/0.044]
1000
Case 13.2.18Pass
3847 ms [1.000/0.044]
1000
13 WebSocket Compression (different parameters)TooTallNate Java-WebSocket
13.3 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]
Case 13.3.1Pass
538 ms [1.000/0.985]
1000
Case 13.3.2Pass
527 ms [1.000/0.748]
1000
Case 13.3.3Pass
495 ms [1.000/0.521]
1000
Case 13.3.4Pass
544 ms [1.000/0.170]
1000
Case 13.3.5Pass
692 ms [1.000/0.075]
1000
Case 13.3.6Pass
750 ms [1.000/0.059]
1000
Case 13.3.7Pass
978 ms [1.000/0.051]
1000
Case 13.3.8Pass
1316 ms [1.000/0.047]
1000
Case 13.3.9Pass
2134 ms [1.000/0.045]
1000
Case 13.3.10Pass
3762 ms [1.000/0.044]
1000
Case 13.3.11Pass
785 ms [1.000/0.059]
1000
Case 13.3.12Pass
987 ms [1.000/0.051]
1000
Case 13.3.13Pass
1442 ms [1.000/0.047]
1000
Case 13.3.14Pass
2478 ms [1.000/0.045]
1000
Case 13.3.15Pass
4157 ms [1.000/0.044]
1000
Case 13.3.16Pass
4171 ms [1.000/0.044]
1000
Case 13.3.17Pass
4438 ms [1.000/0.044]
1000
Case 13.3.18Pass
3711 ms [1.000/0.044]
1000
13 WebSocket Compression (different parameters)TooTallNate Java-WebSocket
13.4 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]
Case 13.4.1Pass
495 ms [1.000/0.985]
1000
Case 13.4.2Pass
470 ms [1.000/0.748]
1000
Case 13.4.3Pass
493 ms [1.000/0.521]
1000
Case 13.4.4Pass
531 ms [1.000/0.170]
1000
Case 13.4.5Pass
637 ms [1.000/0.075]
1000
Case 13.4.6Pass
719 ms [1.000/0.059]
1000
Case 13.4.7Pass
906 ms [1.000/0.051]
1000
Case 13.4.8Pass
1281 ms [1.000/0.047]
1000
Case 13.4.9Pass
2103 ms [1.000/0.045]
1000
Case 13.4.10Pass
3671 ms [1.000/0.044]
1000
Case 13.4.11Pass
771 ms [1.000/0.059]
1000
Case 13.4.12Pass
976 ms [1.000/0.051]
1000
Case 13.4.13Pass
1435 ms [1.000/0.047]
1000
Case 13.4.14Pass
2350 ms [1.000/0.045]
1000
Case 13.4.15Pass
4051 ms [1.000/0.044]
1000
Case 13.4.16Pass
4005 ms [1.000/0.044]
1000
Case 13.4.17Pass
4504 ms [1.000/0.044]
1000
Case 13.4.18Pass
3954 ms [1.000/0.044]
1000
13 WebSocket Compression (different parameters)TooTallNate Java-WebSocket
13.5 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]
Case 13.5.1Pass
492 ms [1.000/0.985]
1000
Case 13.5.2Pass
525 ms [1.000/0.748]
1000
Case 13.5.3Pass
590 ms [1.000/0.521]
1000
Case 13.5.4Pass
577 ms [1.000/0.170]
1000
Case 13.5.5Pass
722 ms [1.000/0.075]
1000
Case 13.5.6Pass
816 ms [1.000/0.059]
1000
Case 13.5.7Pass
978 ms [1.000/0.051]
1000
Case 13.5.8Pass
1320 ms [1.000/0.047]
1000
Case 13.5.9Pass
2182 ms [1.000/0.045]
1000
Case 13.5.10Pass
3981 ms [1.000/0.044]
1000
Case 13.5.11Pass
823 ms [1.000/0.059]
1000
Case 13.5.12Pass
1042 ms [1.000/0.051]
1000
Case 13.5.13Pass
1456 ms [1.000/0.047]
1000
Case 13.5.14Pass
2339 ms [1.000/0.045]
1000
Case 13.5.15Pass
4093 ms [1.000/0.044]
1000
Case 13.5.16Pass
3879 ms [1.000/0.044]
1000
Case 13.5.17Pass
4201 ms [1.000/0.044]
1000
Case 13.5.18Pass
3777 ms [1.000/0.044]
1000
13 WebSocket Compression (different parameters)TooTallNate Java-WebSocket
13.6 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]
Case 13.6.1Pass
486 ms [1.000/0.985]
1000
Case 13.6.2Pass
519 ms [1.000/0.748]
1000
Case 13.6.3Pass
535 ms [1.000/0.521]
1000
Case 13.6.4Pass
543 ms [1.000/0.170]
1000
Case 13.6.5Pass
653 ms [1.000/0.075]
1000
Case 13.6.6Pass
712 ms [1.000/0.059]
1000
Case 13.6.7Pass
918 ms [1.000/0.051]
1000
Case 13.6.8Pass
1285 ms [1.000/0.047]
1000
Case 13.6.9Pass
2166 ms [1.000/0.045]
1000
Case 13.6.10Pass
3698 ms [1.000/0.044]
1000
Case 13.6.11Pass
773 ms [1.000/0.059]
1000
Case 13.6.12Pass
978 ms [1.000/0.051]
1000
Case 13.6.13Pass
1363 ms [1.000/0.047]
1000
Case 13.6.14Pass
2362 ms [1.000/0.045]
1000
Case 13.6.15Pass
4349 ms [1.000/0.044]
1000
Case 13.6.16Pass
4305 ms [1.000/0.044]
1000
Case 13.6.17Pass
4359 ms [1.000/0.044]
1000
Case 13.6.18Pass
4246 ms [1.000/0.044]
1000
13 WebSocket Compression (different parameters)TooTallNate Java-WebSocket
13.7 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]
Case 13.7.1Pass
612 ms [1.000/0.985]
1000
Case 13.7.2Pass
485 ms [1.000/0.748]
1000
Case 13.7.3Pass
537 ms [1.000/0.521]
1000
Case 13.7.4Pass
558 ms [1.000/0.170]
1000
Case 13.7.5Pass
870 ms [1.000/0.075]
1000
Case 13.7.6Pass
842 ms [1.000/0.059]
1000
Case 13.7.7Pass
1134 ms [1.000/0.051]
1000
Case 13.7.8Pass
1285 ms [1.000/0.047]
1000
Case 13.7.9Pass
2269 ms [1.000/0.045]
1000
Case 13.7.10Pass
3975 ms [1.000/0.044]
1000
Case 13.7.11Pass
960 ms [1.000/0.059]
1000
Case 13.7.12Pass
1079 ms [1.000/0.051]
1000
Case 13.7.13Pass
1434 ms [1.000/0.047]
1000
Case 13.7.14Pass
2523 ms [1.000/0.045]
1000
Case 13.7.15Pass
4308 ms [1.000/0.044]
1000
Case 13.7.16Pass
4000 ms [1.000/0.044]
1000
Case 13.7.17Pass
4446 ms [1.000/0.044]
1000
Case 13.7.18Pass
3730 ms [1.000/0.044]
1000
-

-
-
- -

Case 1.1.1

- Up -

Case Description

Send text message with payload 0.

-

Case Expectation

Receive echo'ed text message (with empty payload). Clean close with normal code.

-
- -

Case 1.1.2

- Up -

Case Description

Send text message message with payload of length 125.

-

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.

-
- -

Case 1.1.3

- Up -

Case Description

Send text message message with payload of length 126.

-

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.

-
- -

Case 1.1.4

- Up -

Case Description

Send text message message with payload of length 127.

-

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.

-
- -

Case 1.1.5

- Up -

Case Description

Send text message message with payload of length 128.

-

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.

-
- -

Case 1.1.6

- Up -

Case Description

Send text message message with payload of length 65535.

-

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.

-
- -

Case 1.1.7

- Up -

Case Description

Send text message message with payload of length 65536.

-

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.

-
- -

Case 1.1.8

- Up -

Case Description

Send text message message with payload of length 65536. Sent out data in chops of 997 octets.

-

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.

-
- -

Case 1.2.1

- Up -

Case Description

Send binary message with payload 0.

-

Case Expectation

Receive echo'ed binary message (with empty payload). Clean close with normal code.

-
- -

Case 1.2.2

- Up -

Case Description

Send binary message message with payload of length 125.

-

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.

-
- -

Case 1.2.3

- Up -

Case Description

Send binary message message with payload of length 126.

-

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.

-
- -

Case 1.2.4

- Up -

Case Description

Send binary message message with payload of length 127.

-

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.

-
- -

Case 1.2.5

- Up -

Case Description

Send binary message message with payload of length 128.

-

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.

-
- -

Case 1.2.6

- Up -

Case Description

Send binary message message with payload of length 65535.

-

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.

-
- -

Case 1.2.7

- Up -

Case Description

Send binary message message with payload of length 65536.

-

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.

-
- -

Case 1.2.8

- Up -

Case Description

Send binary message message with payload of length 65536. Sent out data in chops of 997 octets.

-

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.

-
- -

Case 2.1

- Up -

Case Description

Send ping without payload.

-

Case Expectation

Pong (with empty payload) is sent in reply to Ping. Clean close with normal code.

-
- -

Case 2.2

- Up -

Case Description

Send ping with small text payload.

-

Case Expectation

Pong with payload echo'ed is sent in reply to Ping. Clean close with normal code.

-
- -

Case 2.3

- Up -

Case Description

Send ping with small binary (non UTF-8) payload.

-

Case Expectation

Pong with payload echo'ed is sent in reply to Ping. Clean close with normal code.

-
- -

Case 2.4

- Up -

Case Description

Send ping with binary payload of 125 octets.

-

Case Expectation

Pong with payload echo'ed is sent in reply to Ping. Clean close with normal code.

-
- -

Case 2.5

- Up -

Case Description

Send ping with binary payload of 126 octets.

-

Case Expectation

Connection is failed immediately (1002/Protocol Error), since control frames are only allowed to have payload up to and including 125 octets..

-
- -

Case 2.6

- Up -

Case Description

Send ping with binary payload of 125 octets, send in octet-wise chops.

-

Case Expectation

Pong with payload echo'ed is sent in reply to Ping. Implementations must be TCP clean. Clean close with normal code.

-
- -

Case 2.7

- Up -

Case Description

Send unsolicited pong without payload. Verify nothing is received. Clean close with normal code.

-

Case Expectation

Nothing.

-
- -

Case 2.8

- Up -

Case Description

Send unsolicited pong with payload. Verify nothing is received. Clean close with normal code.

-

Case Expectation

Nothing.

-
- -

Case 2.9

- Up -

Case Description

Send unsolicited pong with payload. Send ping with payload. Verify pong for ping is received.

-

Case Expectation

Nothing in reply to own Pong, but Pong with payload echo'ed in reply to Ping. Clean close with normal code.

-
- -

Case 2.10

- Up -

Case Description

Send 10 Pings with payload.

-

Case Expectation

Pongs for our Pings with all the payloads. Note: This is not required by the Spec .. but we check for this behaviour anyway. Clean close with normal code.

-
- -

Case 2.11

- Up -

Case Description

Send 10 Pings with payload. Send out octets in octet-wise chops.

-

Case Expectation

Pongs for our Pings with all the payloads. Note: This is not required by the Spec .. but we check for this behaviour anyway. Clean close with normal code.

-
- -

Case 3.1

- Up -

Case Description

Send small text message with RSV = 1.

-

Case Expectation

The connection is failed immediately (1002/protocol error), since RSV must be 0, when no extension defining RSV meaning has been negotiated.

-
- -

Case 3.2

- Up -

Case Description

Send small text message, then send again with RSV = 2, then send Ping.

-

Case Expectation

Echo for first message is received, but then connection is failed immediately, since RSV must be 0, when no extension defining RSV meaning has been negotiated. The Pong is not received.

-
- -

Case 3.3

- Up -

Case Description

Send small text message, then send again with RSV = 3, then send Ping. Octets are sent in frame-wise chops. Octets are sent in octet-wise chops.

-

Case Expectation

Echo for first message is received, but then connection is failed immediately, since RSV must be 0, when no extension defining RSV meaning has been negotiated. The Pong is not received.

-
- -

Case 3.4

- Up -

Case Description

Send small text message, then send again with RSV = 4, then send Ping. Octets are sent in octet-wise chops.

-

Case Expectation

Echo for first message is received, but then connection is failed immediately, since RSV must be 0, when no extension defining RSV meaning has been negotiated. The Pong is not received.

-
- -

Case 3.5

- Up -

Case Description

Send small binary message with RSV = 5.

-

Case Expectation

The connection is failed immediately, since RSV must be 0.

-
- -

Case 3.6

- Up -

Case Description

Send Ping with RSV = 6.

-

Case Expectation

The connection is failed immediately, since RSV must be 0.

-
- -

Case 3.7

- Up -

Case Description

Send Close with RSV = 7.

-

Case Expectation

The connection is failed immediately, since RSV must be 0.

-
- -

Case 4.1.1

- Up -

Case Description

Send frame with reserved non-control Opcode = 3.

-

Case Expectation

The connection is failed immediately.

-
- -

Case 4.1.2

- Up -

Case Description

Send frame with reserved non-control Opcode = 4 and non-empty payload.

-

Case Expectation

The connection is failed immediately.

-
- -

Case 4.1.3

- Up -

Case Description

Send small text message, then send frame with reserved non-control Opcode = 5, then send Ping.

-

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.

-
- -

Case 4.1.4

- Up -

Case Description

Send small text message, then send frame with reserved non-control Opcode = 6 and non-empty payload, then send Ping.

-

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.

-
- -

Case 4.1.5

- Up -

Case Description

Send small text message, then send frame with reserved non-control Opcode = 7 and non-empty payload, then send Ping.

-

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.

-
- -

Case 4.2.1

- Up -

Case Description

Send frame with reserved control Opcode = 11.

-

Case Expectation

The connection is failed immediately.

-
- -

Case 4.2.2

- Up -

Case Description

Send frame with reserved control Opcode = 12 and non-empty payload.

-

Case Expectation

The connection is failed immediately.

-
- -

Case 4.2.3

- Up -

Case Description

Send small text message, then send frame with reserved control Opcode = 13, then send Ping.

-

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.

-
- -

Case 4.2.4

- Up -

Case Description

Send small text message, then send frame with reserved control Opcode = 14 and non-empty payload, then send Ping.

-

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.

-
- -

Case 4.2.5

- Up -

Case Description

Send small text message, then send frame with reserved control Opcode = 15 and non-empty payload, then send Ping.

-

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.

-
- -

Case 5.1

- Up -

Case Description

Send Ping fragmented into 2 fragments.

-

Case Expectation

Connection is failed immediately, since control message MUST NOT be fragmented.

-
- -

Case 5.2

- Up -

Case Description

Send Pong fragmented into 2 fragments.

-

Case Expectation

Connection is failed immediately, since control message MUST NOT be fragmented.

-
- -

Case 5.3

- Up -

Case Description

Send text Message fragmented into 2 fragments.

-

Case Expectation

Message is processed and echo'ed back to us.

-
- -

Case 5.4

- Up -

Case Description

Send text Message fragmented into 2 fragments, octets are sent in frame-wise chops.

-

Case Expectation

Message is processed and echo'ed back to us.

-
- -

Case 5.5

- Up -

Case Description

Send text Message fragmented into 2 fragments, octets are sent in octet-wise chops.

-

Case Expectation

Message is processed and echo'ed back to us.

-
- -

Case 5.6

- Up -

Case Description

Send text Message fragmented into 2 fragments, one ping with payload in-between.

-

Case Expectation

A pong is received, then the message is echo'ed back to us.

-
- -

Case 5.7

- Up -

Case Description

Send text Message fragmented into 2 fragments, one ping with payload in-between. Octets are sent in frame-wise chops.

-

Case Expectation

A pong is received, then the message is echo'ed back to us.

-
- -

Case 5.8

- Up -

Case Description

Send text Message fragmented into 2 fragments, one ping with payload in-between. Octets are sent in octet-wise chops.

-

Case Expectation

A pong is received, then the message is echo'ed back to us.

-
- -

Case 5.9

- Up -

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = true, where there is nothing to continue, sent in one chop.

-

Case Expectation

The connection is failed immediately, since there is no message to continue.

-
- -

Case 5.10

- Up -

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = true, where there is nothing to continue, sent in per-frame chops.

-

Case Expectation

The connection is failed immediately, since there is no message to continue.

-
- -

Case 5.11

- Up -

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = true, where there is nothing to continue, sent in octet-wise chops.

-

Case Expectation

The connection is failed immediately, since there is no message to continue.

-
- -

Case 5.12

- Up -

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = false, where there is nothing to continue, sent in one chop.

-

Case Expectation

The connection is failed immediately, since there is no message to continue.

-
- -

Case 5.13

- Up -

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = false, where there is nothing to continue, sent in per-frame chops.

-

Case Expectation

The connection is failed immediately, since there is no message to continue.

-
- -

Case 5.14

- Up -

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = false, where there is nothing to continue, sent in octet-wise chops.

-

Case Expectation

The connection is failed immediately, since there is no message to continue.

-
- -

Case 5.15

- Up -

Case Description

Send text Message fragmented into 2 fragments, then Continuation Frame with FIN = false where there is nothing to continue, then unfragmented Text Message, all sent in one chop.

-

Case Expectation

The connection is failed immediately, since there is no message to continue.

-
- -

Case 5.16

- Up -

Case Description

Repeated 2x: Continuation Frame with FIN = false (where there is nothing to continue), then text Message fragmented into 2 fragments.

-

Case Expectation

The connection is failed immediately, since there is no message to continue.

-
- -

Case 5.17

- Up -

Case Description

Repeated 2x: Continuation Frame with FIN = true (where there is nothing to continue), then text Message fragmented into 2 fragments.

-

Case Expectation

The connection is failed immediately, since there is no message to continue.

-
- -

Case 5.18

- Up -

Case Description

Send text Message fragmented into 2 fragments, with both frame opcodes set to text, sent in one chop.

-

Case Expectation

The connection is failed immediately, since all data frames after the initial data frame must have opcode 0.

-
- -

Case 5.19

- Up -

Case Description

A fragmented text message is sent in multiple frames. After - sending the first 2 frames of the text message, a Ping is sent. Then we wait 1s, - then we send 2 more text fragments, another Ping and then the final text fragment. - Everything is legal.

-

Case Expectation

The peer immediately answers the first Ping before - it has received the last text message fragment. The peer pong's back the Ping's - payload exactly, and echo's the payload of the fragmented message back to us.

-
- -

Case 5.20

- Up -

Case Description

Same as Case 5.19, but send all frames with SYNC = True. - Note, this does not change the octets sent in any way, only how the stream - is chopped up on the wire.

-

Case Expectation

Same as Case 5.19. Implementations must be agnostic to how - octet stream is chopped up on wire (must be TCP clean).

-
- -

Case 6.1.1

- Up -

Case Description

Send text message of length 0.

-

Case Expectation

A message is echo'ed back to us (with empty payload).

-
- -

Case 6.1.2

- Up -

Case Description

Send fragmented text message, 3 fragments each of length 0.

-

Case Expectation

A message is echo'ed back to us (with empty payload).

-
- -

Case 6.1.3

- Up -

Case Description

Send fragmented text message, 3 fragments, first and last of length 0, middle non-empty.

-

Case Expectation

A message is echo'ed back to us (with payload = payload of middle fragment).

-
- -

Case 6.2.1

- Up -

Case Description

Send a valid UTF-8 text message in one fragment.

MESSAGE:
Hello-µ@ßöäüàá-UTF-8!!
48656c6c6f2dc2b540c39fc3b6c3a4c3bcc3a0c3a12d5554462d382121

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.2.2

- Up -

Case Description

Send a valid UTF-8 text message in two fragments, fragmented on UTF-8 code point boundary.

MESSAGE FRAGMENT 1:
Hello-µ@ßöä
48656c6c6f2dc2b540c39fc3b6c3a4

MESSAGE FRAGMENT 2:
üàá-UTF-8!!
c3bcc3a0c3a12d5554462d382121

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.2.3

- Up -

Case Description

Send a valid UTF-8 text message in fragments of 1 octet, resulting in frames ending on positions which are not code point ends.

MESSAGE:
Hello-µ@ßöäüàá-UTF-8!!
48656c6c6f2dc2b540c39fc3b6c3a4c3bcc3a0c3a12d5554462d382121

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.2.4

- Up -

Case Description

Send a valid UTF-8 text message in fragments of 1 octet, resulting in frames ending on positions which are not code point ends.

MESSAGE:
κόσμε
cebae1bdb9cf83cebcceb5

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.3.1

- Up -

Case Description

Send invalid UTF-8 text message unfragmented.

MESSAGE:
cebae1bdb9cf83cebcceb5eda080656469746564

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.3.2

- Up -

Case Description

Send invalid UTF-8 text message in fragments of 1 octet, resulting in frames ending on positions which are not code point ends.

MESSAGE:
cebae1bdb9cf83cebcceb5eda080656469746564

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.4.1

- Up -

Case Description

Send invalid UTF-8 text message in 3 fragments (frames). -First frame payload is valid, then wait, then 2nd frame which contains the payload making the sequence invalid, then wait, then 3rd frame with rest. -Note that PART1 and PART3 are valid UTF-8 in themselves, PART2 is a 0x110000 encoded as in the UTF-8 integer encoding scheme, but the codepoint is invalid (out of range). -

MESSAGE PARTS:
-PART1 = cebae1bdb9cf83cebcceb5
-PART2 = f4908080
-PART3 = 656469746564
-

-

Case Expectation

The first frame is accepted, we expect to timeout on the first wait. The 2nd frame should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.

-
- -

Case 6.4.2

- Up -

Case Description

Same as Case 6.4.1, but in 2nd frame, we send only up to and including the octet making the complete payload invalid. -

MESSAGE PARTS:
-PART1 = cebae1bdb9cf83cebcceb5f4
-PART2 = 90
-PART3 = 8080656469746564
-

-

Case Expectation

The first frame is accepted, we expect to timeout on the first wait. The 2nd frame should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.

-
- -

Case 6.4.3

- Up -

Case Description

Same as Case 6.4.1, but we send message not in 3 frames, but in 3 chops of the same message frame. -

MESSAGE PARTS:
-PART1 = cebae1bdb9cf83cebcceb5
-PART2 = f4908080
-PART3 = 656469746564
-

-

Case Expectation

The first chop is accepted, we expect to timeout on the first wait. The 2nd chop should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.

-
- -

Case 6.4.4

- Up -

Case Description

Same as Case 6.4.2, but we send message not in 3 frames, but in 3 chops of the same message frame. -

MESSAGE PARTS:
-PART1 = cebae1bdb9cf83cebcceb5f4
-PART2 = 90
-PART3 =
-

-

Case Expectation

The first chop is accepted, we expect to timeout on the first wait. The 2nd chop should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.

-
- -

Case 6.5.1

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x68656c6c6f24776f726c64

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.5.2

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x68656c6c6fc2a2776f726c64

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.5.3

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x68656c6c6fe282ac776f726c64

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.5.4

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x68656c6c6ff0a4ada2776f726c64

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.5.5

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83cebcceb5

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.6.1

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xce

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.6.2

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xceba

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.6.3

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xcebae1

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.6.4

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xcebae1bd

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.6.5

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.6.6

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.6.7

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.6.8

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83ce

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.6.9

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83cebc

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.6.10

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83cebcce

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.6.11

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83cebcceb5

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.7.1

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x00

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.7.2

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xc280

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.7.3

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xe0a080

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.7.4

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf0908080

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.8.1

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf888808080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.8.2

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc8480808080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.9.1

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x7f

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.9.2

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xdfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.9.3

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.9.4

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf48fbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.10.1

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf7bfbfbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.10.2

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfbbfbfbfbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.10.3

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfdbfbfbfbfbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.11.1

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xed9fbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.11.2

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xee8080

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.11.3

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbd

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.11.4

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf48fbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.11.5

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf4908080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.12.1

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.12.2

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.12.3

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80bf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.12.4

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80bf80

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.12.5

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80bf80bf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.12.6

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80bf80bf80

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.12.7

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80bf80bf80bf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.12.8

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbe

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.13.1

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc020c120c220c320c420c520c620c720c820c920ca20cb20cc20cd20ce20cf20d020d120d220d320d420d520d620d720d820d920da20db20dc20dd20de20

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.13.2

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xe020e120e220e320e420e520e620e720e820e920ea20eb20ec20ed20ee20

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.13.3

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf020f120f220f320f420f520f620

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.13.4

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf820f920fa20

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.13.5

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc20

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.14.1

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc0

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.14.2

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xe080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.14.3

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf08080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.14.4

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf8808080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.14.5

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc80808080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.14.6

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xdf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.14.7

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xefbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.14.8

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf7bfbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.14.9

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfbbfbfbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.14.10

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfdbfbfbfbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.15.1

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc0e080f08080f8808080fc80808080dfefbff7bfbffbbfbfbffdbfbfbfbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.16.1

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfe

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.16.2

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xff

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.16.3

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfefeffff

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.17.1

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc0af

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.17.2

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xe080af

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.17.3

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf08080af

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.17.4

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf8808080af

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.17.5

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc80808080af

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.18.1

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc1bf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.18.2

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xe09fbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.18.3

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf08fbfbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.18.4

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf887bfbfbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.18.5

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc83bfbfbfbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.19.1

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.19.2

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xe08080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.19.3

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf0808080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.19.4

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf880808080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.19.5

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc8080808080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.20.1

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xeda080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.20.2

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedadbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.20.3

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedae80

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.20.4

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedafbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.20.5

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedb080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.20.6

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedbe80

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.20.7

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedbfbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.21.1

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xeda080edb080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.21.2

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xeda080edbfbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.21.3

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedadbfedb080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.21.4

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedadbfedbfbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.21.5

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedae80edb080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.21.6

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedae80edbfbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.21.7

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedafbfedb080

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.21.8

- Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedafbfedbfbf

-

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.

-
- -

Case 6.22.1

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.2

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.3

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf09fbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.4

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf09fbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.5

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf0afbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.6

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf0afbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.7

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf0bfbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.8

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf0bfbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.9

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf18fbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.10

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf18fbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.11

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf19fbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.12

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf19fbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.13

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf1afbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.14

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf1afbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.15

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf1bfbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.16

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf1bfbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.17

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf28fbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.18

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf28fbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.19

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf29fbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.20

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf29fbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.21

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf2afbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.22

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf2afbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.23

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf2bfbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.24

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf2bfbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.25

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf38fbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.26

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf38fbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.27

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf39fbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.28

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf39fbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.29

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf3afbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.30

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf3afbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.31

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf3bfbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.32

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf3bfbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.33

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf48fbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.22.34

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf48fbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.23.1

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfb9

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.23.2

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfba

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.23.3

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbb

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.23.4

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbc

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.23.5

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbd

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.23.6

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbe

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 6.23.7

- Up -

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbf

-

Case Expectation

The message is echo'ed back to us.

-
- -

Case 7.1.1

- Up -

Case Description

Send a message followed by a close frame

-

Case Expectation

Echoed message followed by clean close with normal code.

-
- -

Case 7.1.2

- Up -

Case Description

Send two close frames

-

Case Expectation

Clean close with normal code. Second close frame ignored.

-
- -

Case 7.1.3

- Up -

Case Description

Send a ping after close message

-

Case Expectation

Clean close with normal code, no pong.

-
- -

Case 7.1.4

- Up -

Case Description

Send text message after sending a close frame.

-

Case Expectation

Clean close with normal code. Text message ignored.

-
- -

Case 7.1.5

- Up -

Case Description

Send message fragment1 followed by close then fragment

-

Case Expectation

Clean close with normal code.

-
- -

Case 7.1.6

- Up -

Case Description

Send 256K message followed by close then a ping

-

Case Expectation

Case outcome depends on implementation defined close behavior. Message and close frame are sent back to back. If the close frame is processed before the text message write is complete (as can happen in asynchronous processing models) the close frame is processed first and the text message may not be received or may only be partially recieved.

-
- -

Case 7.3.1

- Up -

Case Description

Send a close frame with payload length 0 (no close code, no close reason)

-

Case Expectation

Clean close with normal code.

-
- -

Case 7.3.2

- Up -

Case Description

Send a close frame with payload length 1

-

Case Expectation

Clean close with protocol error or drop TCP.

-
- -

Case 7.3.3

- Up -

Case Description

Send a close frame with payload length 2 (regular close with a code)

-

Case Expectation

Clean close with normal code.

-
- -

Case 7.3.4

- Up -

Case Description

Send a close frame with close code and close reason

-

Case Expectation

Clean close with normal code.

-
- -

Case 7.3.5

- Up -

Case Description

Send a close frame with close code and close reason of maximum length (123)

-

Case Expectation

Clean close with normal code.

-
- -

Case 7.3.6

- Up -

Case Description

Send a close frame with close code and close reason which is too long (124) - total frame payload 126 octets

-

Case Expectation

Clean close with protocol error code or dropped TCP connection.

-
- -

Case 7.5.1

- Up -

Case Description

Send a close frame with invalid UTF8 payload

-

Case Expectation

Clean close with protocol error or invalid utf8 code or dropped TCP.

-
- -

Case 7.7.1

- Up -

Case Description

Send close with valid close code 1000

-

Case Expectation

Clean close with normal or echoed code

-
- -

Case 7.7.2

- Up -

Case Description

Send close with valid close code 1001

-

Case Expectation

Clean close with normal or echoed code

-
- -

Case 7.7.3

- Up -

Case Description

Send close with valid close code 1002

-

Case Expectation

Clean close with normal or echoed code

-
- -

Case 7.7.4

- Up -

Case Description

Send close with valid close code 1003

-

Case Expectation

Clean close with normal or echoed code

-
- -

Case 7.7.5

- Up -

Case Description

Send close with valid close code 1007

-

Case Expectation

Clean close with normal or echoed code

-
- -

Case 7.7.6

- Up -

Case Description

Send close with valid close code 1008

-

Case Expectation

Clean close with normal or echoed code

-
- -

Case 7.7.7

- Up -

Case Description

Send close with valid close code 1009

-

Case Expectation

Clean close with normal or echoed code

-
- -

Case 7.7.8

- Up -

Case Description

Send close with valid close code 1010

-

Case Expectation

Clean close with normal or echoed code

-
- -

Case 7.7.9

- Up -

Case Description

Send close with valid close code 1011

-

Case Expectation

Clean close with normal or echoed code

-
- -

Case 7.7.10

- Up -

Case Description

Send close with valid close code 3000

-

Case Expectation

Clean close with normal or echoed code

-
- -

Case 7.7.11

- Up -

Case Description

Send close with valid close code 3999

-

Case Expectation

Clean close with normal or echoed code

-
- -

Case 7.7.12

- Up -

Case Description

Send close with valid close code 4000

-

Case Expectation

Clean close with normal or echoed code

-
- -

Case 7.7.13

- Up -

Case Description

Send close with valid close code 4999

-

Case Expectation

Clean close with normal or echoed code

-
- -

Case 7.9.1

- Up -

Case Description

Send close with invalid close code 0

-

Case Expectation

Clean close with protocol error code or drop TCP

-
- -

Case 7.9.2

- Up -

Case Description

Send close with invalid close code 999

-

Case Expectation

Clean close with protocol error code or drop TCP

-
- -

Case 7.9.3

- Up -

Case Description

Send close with invalid close code 1004

-

Case Expectation

Clean close with protocol error code or drop TCP

-
- -

Case 7.9.4

- Up -

Case Description

Send close with invalid close code 1005

-

Case Expectation

Clean close with protocol error code or drop TCP

-
- -

Case 7.9.5

- Up -

Case Description

Send close with invalid close code 1006

-

Case Expectation

Clean close with protocol error code or drop TCP

-
- -

Case 7.9.6

- Up -

Case Description

Send close with invalid close code 1016

-

Case Expectation

Clean close with protocol error code or drop TCP

-
- -

Case 7.9.7

- Up -

Case Description

Send close with invalid close code 1100

-

Case Expectation

Clean close with protocol error code or drop TCP

-
- -

Case 7.9.8

- Up -

Case Description

Send close with invalid close code 2000

-

Case Expectation

Clean close with protocol error code or drop TCP

-
- -

Case 7.9.9

- Up -

Case Description

Send close with invalid close code 2999

-

Case Expectation

Clean close with protocol error code or drop TCP

-
- -

Case 7.13.1

- Up -

Case Description

Send close with close code 5000

-

Case Expectation

Actual events are undefined by the spec.

-
- -

Case 7.13.2

- Up -

Case Description

Send close with close code 65536

-

Case Expectation

Actual events are undefined by the spec.

-
- -

Case 9.1.1

- Up -

Case Description

Send text message message with payload of length 64 * 2**10 (64k).

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.1.2

- Up -

Case Description

Send text message message with payload of length 256 * 2**10 (256k).

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.1.3

- Up -

Case Description

Send text message message with payload of length 1 * 2**20 (1M).

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.1.4

- Up -

Case Description

Send text message message with payload of length 4 * 2**20 (4M).

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.1.5

- Up -

Case Description

Send text message message with payload of length 8 * 2**20 (8M).

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.1.6

- Up -

Case Description

Send text message message with payload of length 16 * 2**20 (16M).

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.2.1

- Up -

Case Description

Send binary message message with payload of length 64 * 2**10 (64k).

-

Case Expectation

Receive echo'ed binary message (with payload as sent).

-
- -

Case 9.2.2

- Up -

Case Description

Send binary message message with payload of length 256 * 2**10 (256k).

-

Case Expectation

Receive echo'ed binary message (with payload as sent).

-
- -

Case 9.2.3

- Up -

Case Description

Send binary message message with payload of length 1 * 2**20 (1M).

-

Case Expectation

Receive echo'ed binary message (with payload as sent).

-
- -

Case 9.2.4

- Up -

Case Description

Send binary message message with payload of length 4 * 2**20 (4M).

-

Case Expectation

Receive echo'ed binary message (with payload as sent).

-
- -

Case 9.2.5

- Up -

Case Description

Send binary message message with payload of length 8 * 2**20 (16M).

-

Case Expectation

Receive echo'ed binary message (with payload as sent).

-
- -

Case 9.2.6

- Up -

Case Description

Send binary message message with payload of length 16 * 2**20 (16M).

-

Case Expectation

Receive echo'ed binary message (with payload as sent).

-
- -

Case 9.3.1

- Up -

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 64.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.3.2

- Up -

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 256.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.3.3

- Up -

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 1k.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.3.4

- Up -

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 4k.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.3.5

- Up -

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 16k.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.3.6

- Up -

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 64k.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.3.7

- Up -

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 256k.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.3.8

- Up -

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 1M.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.3.9

- Up -

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (8M). Sent out in fragments of 4M.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.4.1

- Up -

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 64.

-

Case Expectation

Receive echo'ed binary message (with payload as sent).

-
- -

Case 9.4.2

- Up -

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 256.

-

Case Expectation

Receive echo'ed binary message (with payload as sent).

-
- -

Case 9.4.3

- Up -

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 1k.

-

Case Expectation

Receive echo'ed binary message (with payload as sent).

-
- -

Case 9.4.4

- Up -

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 4k.

-

Case Expectation

Receive echo'ed binary message (with payload as sent).

-
- -

Case 9.4.5

- Up -

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 16k.

-

Case Expectation

Receive echo'ed binary message (with payload as sent).

-
- -

Case 9.4.6

- Up -

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 64k.

-

Case Expectation

Receive echo'ed binary message (with payload as sent).

-
- -

Case 9.4.7

- Up -

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 256k.

-

Case Expectation

Receive echo'ed binary message (with payload as sent).

-
- -

Case 9.4.8

- Up -

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 1M.

-

Case Expectation

Receive echo'ed binary message (with payload as sent).

-
- -

Case 9.4.9

- Up -

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 4M.

-

Case Expectation

Receive echo'ed binary message (with payload as sent).

-
- -

Case 9.5.1

- Up -

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 64 octets.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.5.2

- Up -

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 128 octets.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.5.3

- Up -

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 256 octets.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.5.4

- Up -

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 512 octets.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.5.5

- Up -

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 1024 octets.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.5.6

- Up -

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 2048 octets.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.6.1

- Up -

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 64 octets.

-

Case Expectation

Receive echo'ed binary message (with payload as sent).

-
- -

Case 9.6.2

- Up -

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 128 octets.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.6.3

- Up -

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 256 octets.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.6.4

- Up -

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 512 octets.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.6.5

- Up -

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 1024 octets.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.6.6

- Up -

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 2048 octets.

-

Case Expectation

Receive echo'ed text message (with payload as sent).

-
- -

Case 9.7.1

- Up -

Case Description

Send 1000 text messages of payload size 0 to measure implementation/network RTT (round trip time) / latency.

-

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 9.7.2

- Up -

Case Description

Send 1000 text messages of payload size 16 to measure implementation/network RTT (round trip time) / latency.

-

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 9.7.3

- Up -

Case Description

Send 1000 text messages of payload size 64 to measure implementation/network RTT (round trip time) / latency.

-

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 9.7.4

- Up -

Case Description

Send 1000 text messages of payload size 256 to measure implementation/network RTT (round trip time) / latency.

-

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 120 secs.

-
- -

Case 9.7.5

- Up -

Case Description

Send 1000 text messages of payload size 1024 to measure implementation/network RTT (round trip time) / latency.

-

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 240 secs.

-
- -

Case 9.7.6

- Up -

Case Description

Send 1000 text messages of payload size 4096 to measure implementation/network RTT (round trip time) / latency.

-

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 9.8.1

- Up -

Case Description

Send 1000 binary messages of payload size 0 to measure implementation/network RTT (round trip time) / latency.

-

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 9.8.2

- Up -

Case Description

Send 1000 binary messages of payload size 16 to measure implementation/network RTT (round trip time) / latency.

-

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 9.8.3

- Up -

Case Description

Send 1000 binary messages of payload size 64 to measure implementation/network RTT (round trip time) / latency.

-

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 9.8.4

- Up -

Case Description

Send 1000 binary messages of payload size 256 to measure implementation/network RTT (round trip time) / latency.

-

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 120 secs.

-
- -

Case 9.8.5

- Up -

Case Description

Send 1000 binary messages of payload size 1024 to measure implementation/network RTT (round trip time) / latency.

-

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 240 secs.

-
- -

Case 9.8.6

- Up -

Case Description

Send 1000 binary messages of payload size 4096 to measure implementation/network RTT (round trip time) / latency.

-

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 10.1.1

- Up -

Case Description

Send text message with payload of length 65536 auto-fragmented with autoFragmentSize = 1300.

-

Case Expectation

Receive echo'ed text message (with payload as sent and transmitted frame counts as expected). Clean close with normal code.

-
- -

Case 12.1.1

- Up -

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 12.1.2

- Up -

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 12.1.3

- Up -

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

-
- -

Case 12.1.4

- Up -

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

-
- -

Case 12.1.5

- Up -

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.1.6

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.1.7

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.1.8

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.1.9

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.1.10

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.1.11

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.1.12

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.1.13

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.1.14

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.1.15

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.1.16

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.1.17

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.1.18

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.2.1

- Up -

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 12.2.2

- Up -

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 12.2.3

- Up -

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

-
- -

Case 12.2.4

- Up -

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

-
- -

Case 12.2.5

- Up -

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.2.6

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.2.7

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.2.8

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.2.9

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.2.10

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.2.11

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.2.12

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.2.13

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.2.14

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.2.15

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.2.16

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.2.17

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.2.18

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.3.1

- Up -

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 12.3.2

- Up -

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 12.3.3

- Up -

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

-
- -

Case 12.3.4

- Up -

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

-
- -

Case 12.3.5

- Up -

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.3.6

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.3.7

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.3.8

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.3.9

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.3.10

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.3.11

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.3.12

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.3.13

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.3.14

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.3.15

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.3.16

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.3.17

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.3.18

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.4.1

- Up -

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 12.4.2

- Up -

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 12.4.3

- Up -

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

-
- -

Case 12.4.4

- Up -

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

-
- -

Case 12.4.5

- Up -

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.4.6

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.4.7

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.4.8

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.4.9

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.4.10

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.4.11

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.4.12

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.4.13

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.4.14

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.4.15

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.4.16

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.4.17

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.4.18

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.5.1

- Up -

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 12.5.2

- Up -

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 12.5.3

- Up -

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

-
- -

Case 12.5.4

- Up -

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

-
- -

Case 12.5.5

- Up -

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.5.6

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.5.7

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.5.8

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.5.9

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.5.10

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.5.11

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.5.12

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.5.13

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.5.14

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.5.15

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.5.16

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.5.17

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 12.5.18

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use default permessage-deflate offer.

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.1.1

- Up -

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 13.1.2

- Up -

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 13.1.3

- Up -

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

-
- -

Case 13.1.4

- Up -

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

-
- -

Case 13.1.5

- Up -

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.1.6

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.1.7

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.1.8

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.1.9

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.1.10

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.1.11

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.1.12

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.1.13

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.1.14

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.1.15

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.1.16

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.1.17

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.1.18

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.2.1

- Up -

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 13.2.2

- Up -

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 13.2.3

- Up -

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

-
- -

Case 13.2.4

- Up -

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

-
- -

Case 13.2.5

- Up -

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.2.6

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.2.7

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.2.8

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.2.9

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.2.10

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.2.11

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.2.12

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.2.13

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.2.14

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.2.15

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.2.16

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.2.17

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.2.18

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.3.1

- Up -

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 13.3.2

- Up -

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 13.3.3

- Up -

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

-
- -

Case 13.3.4

- Up -

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

-
- -

Case 13.3.5

- Up -

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.3.6

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.3.7

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.3.8

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.3.9

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.3.10

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.3.11

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.3.12

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.3.13

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.3.14

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.3.15

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.3.16

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.3.17

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.3.18

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.4.1

- Up -

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 13.4.2

- Up -

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 13.4.3

- Up -

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

-
- -

Case 13.4.4

- Up -

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

-
- -

Case 13.4.5

- Up -

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.4.6

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.4.7

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.4.8

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.4.9

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.4.10

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.4.11

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.4.12

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.4.13

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.4.14

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.4.15

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.4.16

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.4.17

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.4.18

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.5.1

- Up -

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 13.5.2

- Up -

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 13.5.3

- Up -

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

-
- -

Case 13.5.4

- Up -

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

-
- -

Case 13.5.5

- Up -

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.5.6

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.5.7

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.5.8

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.5.9

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.5.10

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.5.11

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.5.12

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.5.13

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.5.14

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.5.15

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.5.16

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.5.17

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.5.18

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.6.1

- Up -

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 13.6.2

- Up -

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 13.6.3

- Up -

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

-
- -

Case 13.6.4

- Up -

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

-
- -

Case 13.6.5

- Up -

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.6.6

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.6.7

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.6.8

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.6.9

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.6.10

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.6.11

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.6.12

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.6.13

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.6.14

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.6.15

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.6.16

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.6.17

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.6.18

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.7.1

- Up -

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 13.7.2

- Up -

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.

-
- -

Case 13.7.3

- Up -

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.

-
- -

Case 13.7.4

- Up -

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.

-
- -

Case 13.7.5

- Up -

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.7.6

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.7.7

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.7.8

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.7.9

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.7.10

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.7.11

- Up -

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.7.12

- Up -

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.7.13

- Up -

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.7.14

- Up -

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.7.15

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.7.16

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.7.17

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
- -

Case 13.7.18

- Up -

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

-

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.

-
-

- - From 48a35cea4be68ec8532f3a066c58b5195091095a Mon Sep 17 00:00:00 2001 From: haruntuncay Date: Tue, 7 May 2019 18:01:14 +0300 Subject: [PATCH 013/165] Update PerMessageDeflateExtension to use Deflater.SYNC_FLUSH option. --- .../PerMessageDeflateExtension.java | 45 +++++++++---------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index 5f92f87a8..296a20b76 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -26,28 +26,19 @@ public class PerMessageDeflateExtension extends CompressionExtension { private static final String CLIENT_NO_CONTEXT_TAKEOVER = "client_no_context_takeover"; private static final String SERVER_MAX_WINDOW_BITS = "server_max_window_bits"; private static final String CLIENT_MAX_WINDOW_BITS = "client_max_window_bits"; - private static final boolean serverNoContextTakeover = true; - private static final boolean clientNoContextTakeover = true; private static final int serverMaxWindowBits = 1 << 15; private static final int clientMaxWindowBits = 1 << 15; private static final byte[] TAIL_BYTES = {0x00, 0x00, (byte)0xFF, (byte)0xFF}; private static final int BUFFER_SIZE = 1 << 10; + private boolean serverNoContextTakeover = true; + private boolean clientNoContextTakeover = false; + // For WebSocketServers, this variable holds the extension parameters that the peer client has requested. // For WebSocketClients, this variable holds the extension parameters that client himself has requested. private Map requestedParameters = new LinkedHashMap(); - - /** - * A message to send can be fragmented and if the message is first compressed in it's entirety and then fragmented, - * those fragments can refer to backref-lengths from previous fragments. (up-to 32,768 bytes) - * In order to support this behavior, and Inflater must hold on to the previously uncompressed data - * until all the fragments of a message has been sent. - * Therefore, the - * @see #inflater must be an instance variable rather than a local variables in - * @see PerMessageDeflateExtension#decodeFrame(Framedata) so that it can retain the uncompressed data between multiple calls to - * @see PerMessageDeflateExtension#decodeFrame(Framedata). - */ private Inflater inflater = new Inflater(true); + private Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); /* An endpoint uses the following algorithm to decompress a message. @@ -86,7 +77,9 @@ We can check the getRemaining() method to see whether the data we supplied has b if(inputFrame.isFin()) { decompress(TAIL_BYTES, output); - inflater = new Inflater(true); + // If context takeover is disabled, inflater can be reset. + if(clientNoContextTakeover) + inflater = new Inflater(true); } } catch (DataFormatException e) { throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, e.getMessage()); @@ -120,19 +113,15 @@ public void encodeFrame(Framedata inputFrame) { if(!(inputFrame instanceof ContinuousFrame)) ((DataFrame) inputFrame).setRSV1(true); - Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); deflater.setInput(inputFrame.getPayloadData().array()); - deflater.finish(); - // Compressed output buffer. ByteArrayOutputStream output = new ByteArrayOutputStream(); // Temporary buffer to hold compressed output. byte[] buffer = new byte[1024]; int bytesCompressed; - while((bytesCompressed = deflater.deflate(buffer)) > 0) { + while((bytesCompressed = deflater.deflate(buffer, 0, buffer.length, Deflater.SYNC_FLUSH)) > 0) { output.write(buffer, 0, bytesCompressed); } - deflater.end(); byte outputBytes[] = output.toByteArray(); int outputLength = outputBytes.length; @@ -143,8 +132,15 @@ public void encodeFrame(Framedata inputFrame) { To simulate removal, we just pass 4 bytes less to the new payload if the frame is final and outputBytes ends with 0x00 0x00 0xff 0xff. */ - if(inputFrame.isFin() && endsWithTail(outputBytes)) - outputLength -= TAIL_BYTES.length; + if(inputFrame.isFin()) { + if(endsWithTail(outputBytes)) + outputLength -= TAIL_BYTES.length; + + if(serverNoContextTakeover) { + deflater.end(); + deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); + } + } // Set frames payload to the new compressed data. ((FramedataImpl1) inputFrame).setPayload(ByteBuffer.wrap(outputBytes, 0, outputLength)); @@ -174,7 +170,8 @@ public boolean acceptProvidedExtensionAsServer(String inputExtension) { // Holds parameters that peer client has sent. Map headers = extensionData.getExtensionParameters(); requestedParameters.putAll(headers); - // After this point, parameters can be used if necessary, but for now they are not used. + if(requestedParameters.containsKey(CLIENT_NO_CONTEXT_TAKEOVER)) + clientNoContextTakeover = true; return true; } @@ -209,7 +206,9 @@ public String getProvidedExtensionAsClient() { @Override public String getProvidedExtensionAsServer() { - return EXTENSION_REGISTERED_NAME + "; " + SERVER_NO_CONTEXT_TAKEOVER + "; " + CLIENT_NO_CONTEXT_TAKEOVER; + return EXTENSION_REGISTERED_NAME + + "; " + SERVER_NO_CONTEXT_TAKEOVER + + (clientNoContextTakeover ? "; " + CLIENT_NO_CONTEXT_TAKEOVER : ""); } @Override From 5cbe530e7ebedc3c81f22794990fb9e7d05c5fea Mon Sep 17 00:00:00 2001 From: haruntuncay Date: Wed, 20 Nov 2019 21:47:48 +0300 Subject: [PATCH 014/165] Add ability to customize ping messages with custom data, see issue#941 --- .../org/java_websocket/WebSocketAdapter.java | 15 +++ .../org/java_websocket/WebSocketImpl.java | 16 +-- .../org/java_websocket/WebSocketListener.java | 8 ++ .../java_websocket/issues/Issue941Test.java | 104 ++++++++++++++++++ 4 files changed, 133 insertions(+), 10 deletions(-) create mode 100644 src/test/java/org/java_websocket/issues/Issue941Test.java diff --git a/src/main/java/org/java_websocket/WebSocketAdapter.java b/src/main/java/org/java_websocket/WebSocketAdapter.java index 00e6a9fa6..294162be0 100644 --- a/src/main/java/org/java_websocket/WebSocketAdapter.java +++ b/src/main/java/org/java_websocket/WebSocketAdapter.java @@ -40,6 +40,8 @@ **/ public abstract class WebSocketAdapter implements WebSocketListener { + private PingFrame pingFrame; + /** * This default implementation does not do anything. Go ahead and overwrite it. * @@ -85,4 +87,17 @@ public void onWebsocketPing( WebSocket conn, Framedata f ) { public void onWebsocketPong( WebSocket conn, Framedata f ) { //To overwrite } + + /** + * Default implementation for onPreparePing, returns a (cached) PingFrame that has no application data. + * + * @see org.java_websocket.WebSocketListener#onPreparePing(WebSocket) + * @return PingFrame to be sent. + */ + @Override + public PingFrame onPreparePing(WebSocket conn) { + if(pingFrame == null) + pingFrame = new PingFrame(); + return pingFrame; + } } diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index c291a12ff..89c878d97 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -161,11 +161,6 @@ public class WebSocketImpl implements WebSocket { */ private final Object synchronizeWriteObject = new Object(); - /** - * Attribute to cache a ping frame - */ - private PingFrame pingFrame; - /** * Attribute to store connection attachment * @since 1.3.7 @@ -658,11 +653,12 @@ public void sendFrame( Framedata framedata ) { send( Collections.singletonList( framedata ) ); } - public void sendPing() { - if( pingFrame == null ) { - pingFrame = new PingFrame(); - } - sendFrame( pingFrame ); + public void sendPing() throws NullPointerException { + // Gets a PingFrame from WebSocketListener(wsl) and sends it. + PingFrame pingFrame = wsl.onPreparePing(this); + if(pingFrame == null) + throw new NullPointerException("onPreparePing(WebSocket) returned null. PingFrame to sent can't be null."); + sendFrame(pingFrame); } @Override diff --git a/src/main/java/org/java_websocket/WebSocketListener.java b/src/main/java/org/java_websocket/WebSocketListener.java index 0a270ca73..b05812664 100644 --- a/src/main/java/org/java_websocket/WebSocketListener.java +++ b/src/main/java/org/java_websocket/WebSocketListener.java @@ -32,6 +32,7 @@ import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.framing.CloseFrame; import org.java_websocket.framing.Framedata; +import org.java_websocket.framing.PingFrame; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.Handshakedata; import org.java_websocket.handshake.ServerHandshake; @@ -169,6 +170,13 @@ public interface WebSocketListener { */ void onWebsocketPing( WebSocket conn, Framedata f ); + /** + * Called just before a ping frame is sent, in order to allow users to customize their ping frame data. + * + * @return PingFrame to be sent. + */ + PingFrame onPreparePing(WebSocket conn ); + /** * Called when a pong frame is received. * diff --git a/src/test/java/org/java_websocket/issues/Issue941Test.java b/src/test/java/org/java_websocket/issues/Issue941Test.java new file mode 100644 index 000000000..53785deb5 --- /dev/null +++ b/src/test/java/org/java_websocket/issues/Issue941Test.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2010-2019 Nathan Rajlich + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.java_websocket.issues; + +import org.java_websocket.WebSocket; +import org.java_websocket.client.WebSocketClient; +import org.java_websocket.framing.Framedata; +import org.java_websocket.framing.PingFrame; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.handshake.ServerHandshake; +import org.java_websocket.server.WebSocketServer; +import org.java_websocket.util.SocketUtil; +import org.junit.Test; + +import java.net.InetSocketAddress; +import java.net.URI; +import java.nio.ByteBuffer; +import java.util.concurrent.CountDownLatch; + +import static org.junit.Assert.assertArrayEquals; + +public class Issue941Test { + + private CountDownLatch pingLatch = new CountDownLatch(1); + private CountDownLatch pongLatch = new CountDownLatch(1); + private byte[] pingBuffer, receivedPingBuffer, pongBuffer; + + @Test + public void testIssue() throws Exception { + int port = SocketUtil.getAvailablePort(); + WebSocketClient client = new WebSocketClient(new URI( "ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { } + @Override + public void onMessage(String message) { } + @Override + public void onClose(int code, String reason, boolean remote) { } + @Override + public void onError(Exception ex) { } + @Override + public PingFrame onPreparePing(WebSocket conn) { + PingFrame frame = new PingFrame(); + pingBuffer = new byte[]{1,2,3,4,5,6,7,8,9,10}; + frame.setPayload(ByteBuffer.wrap(pingBuffer)); + return frame; + } + @Override + public void onWebsocketPong(WebSocket conn, Framedata f) { + pongBuffer = f.getPayloadData().array(); + pongLatch.countDown(); + } + }; + + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { } + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { } + @Override + public void onMessage(WebSocket conn, String message) { } + @Override + public void onError(WebSocket conn, Exception ex) { } + @Override + public void onStart() { } + @Override + public void onWebsocketPing(WebSocket conn, Framedata f) { + receivedPingBuffer = f.getPayloadData().array(); + super.onWebsocketPing(conn, f); + pingLatch.countDown(); + } + }; + + server.start(); + client.connectBlocking(); + client.setConnectionLostTimeout(1); + pingLatch.await(); + assertArrayEquals(pingBuffer, receivedPingBuffer); + pongLatch.await(); + assertArrayEquals(pingBuffer, pongBuffer); + } +} From d64295e09ebf4183ff49c67dfec8bcf12c0bc307 Mon Sep 17 00:00:00 2001 From: haruntuncay Date: Thu, 21 Nov 2019 22:41:36 +0300 Subject: [PATCH 015/165] Apply requested changes --- src/main/java/org/java_websocket/WebSocketAdapter.java | 3 ++- src/main/java/org/java_websocket/WebSocketListener.java | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/WebSocketAdapter.java b/src/main/java/org/java_websocket/WebSocketAdapter.java index 294162be0..050d9ec26 100644 --- a/src/main/java/org/java_websocket/WebSocketAdapter.java +++ b/src/main/java/org/java_websocket/WebSocketAdapter.java @@ -90,8 +90,9 @@ public void onWebsocketPong( WebSocket conn, Framedata f ) { /** * Default implementation for onPreparePing, returns a (cached) PingFrame that has no application data. - * * @see org.java_websocket.WebSocketListener#onPreparePing(WebSocket) + * + * @param conn The WebSocket connection from which the ping frame will be sent. * @return PingFrame to be sent. */ @Override diff --git a/src/main/java/org/java_websocket/WebSocketListener.java b/src/main/java/org/java_websocket/WebSocketListener.java index b05812664..ed1038d17 100644 --- a/src/main/java/org/java_websocket/WebSocketListener.java +++ b/src/main/java/org/java_websocket/WebSocketListener.java @@ -173,6 +173,7 @@ public interface WebSocketListener { /** * Called just before a ping frame is sent, in order to allow users to customize their ping frame data. * + * @param conn The WebSocket connection from which the ping frame will be sent. * @return PingFrame to be sent. */ PingFrame onPreparePing(WebSocket conn ); From f427b64c37de44f750a34a57b17496ca67754325 Mon Sep 17 00:00:00 2001 From: Marcel Prestel Date: Mon, 6 Jan 2020 16:11:45 +0000 Subject: [PATCH 016/165] Create new github actions (#931) * Create action * Create actions * Delete pushtobranch.yml * Update ci.yml * Delete stale.yml --- .github/workflows/ci.yml | 26 ++++++++++++++++++++++++++ sonar-project.properties | 6 ++++++ 2 files changed, 32 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 sonar-project.properties diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..544d474cd --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,26 @@ +name: Continuous Integration + +on: [push] + +jobs: + Build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - name: Set up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: Build + run: mvn -DskipTests package --file pom.xml + + Test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - name: Set up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: Test + run: mvn test --file pom.xml diff --git a/sonar-project.properties b/sonar-project.properties new file mode 100644 index 000000000..32d17639a --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1,6 @@ +sonar.organization=marci4-github +sonar.projectKey=org.java-websocket:Java-WebSocket + +# relative paths to source directories. More details and properties are described +# in https://sonarcloud.io/documentation/project-administration/narrowing-the-focus/ +sonar.sources=src/main/java/org/java_websocket From cc030e3c07a75f0db0a001d1e2ce52c2101e9776 Mon Sep 17 00:00:00 2001 From: olivierayache Date: Thu, 9 Jan 2020 18:31:56 +0100 Subject: [PATCH 017/165] Use socket isConnected() method rather than isBound() before connect to server. Fixes #962 --- .../client/WebSocketClient.java | 2 +- .../java_websocket/issues/AllIssueTests.java | 3 +- .../java_websocket/issues/Issue962Test.java | 143 ++++++++++++++++++ 3 files changed, 146 insertions(+), 2 deletions(-) create mode 100644 src/test/java/org/java_websocket/issues/Issue962Test.java diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index c88f258fa..756e57211 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -457,7 +457,7 @@ public void run() { socket.setTcpNoDelay( isTcpNoDelay() ); socket.setReuseAddress( isReuseAddr() ); - if (!socket.isBound()) { + if (!socket.isConnected()) { InetSocketAddress addr = new InetSocketAddress(dnsResolver.resolve(uri), this.getPort()); socket.connect(addr, connectTimeout); } diff --git a/src/test/java/org/java_websocket/issues/AllIssueTests.java b/src/test/java/org/java_websocket/issues/AllIssueTests.java index 3e6fb5b4d..3be0995af 100644 --- a/src/test/java/org/java_websocket/issues/AllIssueTests.java +++ b/src/test/java/org/java_websocket/issues/AllIssueTests.java @@ -42,7 +42,8 @@ org.java_websocket.issues.Issue764Test.class, org.java_websocket.issues.Issue765Test.class, org.java_websocket.issues.Issue825Test.class, - org.java_websocket.issues.Issue834Test.class + org.java_websocket.issues.Issue834Test.class, + org.java_websocket.issues.Issue962Test.class }) /** * Start all tests for issues diff --git a/src/test/java/org/java_websocket/issues/Issue962Test.java b/src/test/java/org/java_websocket/issues/Issue962Test.java new file mode 100644 index 000000000..09263fff2 --- /dev/null +++ b/src/test/java/org/java_websocket/issues/Issue962Test.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2010-2019 Olivier Ayache + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ +package org.java_websocket.issues; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.UnknownHostException; +import javax.net.SocketFactory; +import org.java_websocket.WebSocket; +import org.java_websocket.client.WebSocketClient; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.handshake.ServerHandshake; +import org.java_websocket.server.WebSocketServer; +import org.java_websocket.util.SocketUtil; +import org.junit.Assert; +import org.junit.Test; + +public class Issue962Test { + + private static class TestSocketFactory extends SocketFactory { + + private final SocketFactory socketFactory = SocketFactory.getDefault(); + private final String bindingAddress; + + public TestSocketFactory(String bindingAddress) { + this.bindingAddress = bindingAddress; + } + + @Override + public Socket createSocket() throws IOException { + Socket socket = socketFactory.createSocket(); + socket.bind(new InetSocketAddress(bindingAddress, 0)); + return socket; + } + + @Override + public Socket createSocket(String string, int i) throws IOException, UnknownHostException { + Socket socket = socketFactory.createSocket(string, i); + socket.bind(new InetSocketAddress(bindingAddress, 0)); + return socket; + } + + @Override + public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException, UnknownHostException { + throw new UnsupportedOperationException(); + } + + @Override + public Socket createSocket(InetAddress ia, int i) throws IOException { + Socket socket = socketFactory.createSocket(ia, i); + socket.bind(new InetSocketAddress(bindingAddress, 0)); + return socket; + } + + @Override + public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException { + throw new UnsupportedOperationException(); + } + + } + + @Test + public void testIssue() throws IOException, URISyntaxException, InterruptedException { + int port = SocketUtil.getAvailablePort(); + WebSocketClient client = new WebSocketClient(new URI("ws://127.0.0.1:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + } + + @Override + public void onMessage(String message) { + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + Assert.fail(ex.toString() + " sould not occur"); + } + }; + + String bindingAddress = "127.0.0.1"; + + client.setSocketFactory(new TestSocketFactory(bindingAddress)); + + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } + + @Override + public void onMessage(WebSocket conn, String message) { + } + + @Override + public void onError(WebSocket conn, Exception ex) { + } + + @Override + public void onStart() { + } + }; + + server.start(); + client.connectBlocking(); + Assert.assertEquals(bindingAddress, client.getSocket().getLocalAddress().getHostAddress()); + Assert.assertNotEquals(0, client.getSocket().getLocalPort()); + Assert.assertTrue(client.getSocket().isConnected()); + } + +} From 6db8973f9ee87daf24ee00ca4234084a72ee779a Mon Sep 17 00:00:00 2001 From: amykytchyn Date: Fri, 17 Jan 2020 14:28:04 +0200 Subject: [PATCH 018/165] Set up to date copyright year value Fixes #966 --- LICENSE | 2 +- src/main/example/ChatClient.java | 2 +- src/main/example/ChatServer.java | 2 +- src/main/example/ChatServerAttachmentExample.java | 2 +- src/main/example/CustomHeaderClientExample.java | 2 +- src/main/example/ExampleClient.java | 2 +- src/main/example/FragmentedFramesExample.java | 2 +- src/main/example/ProxyClientExample.java | 2 +- src/main/example/ReconnectClientExample.java | 2 +- src/main/example/SSLClientExample.java | 2 +- src/main/example/SSLServerCustomWebsocketFactoryExample.java | 2 +- src/main/example/SSLServerExample.java | 2 +- src/main/example/SSLServerLetsEncryptExample.java | 2 +- src/main/example/SecWebSocketProtocolClientExample.java | 2 +- src/main/example/ServerAdditionalHeaderExample.java | 2 +- src/main/example/ServerRejectHandshakeExample.java | 2 +- src/main/example/ServerStressTest.java | 2 +- src/main/example/TwoWaySSLServerExample.java | 2 +- src/main/java/org/java_websocket/AbstractWebSocket.java | 2 +- .../java/org/java_websocket/AbstractWrappedByteChannel.java | 2 +- src/main/java/org/java_websocket/SSLSocketChannel.java | 2 +- src/main/java/org/java_websocket/SSLSocketChannel2.java | 2 +- src/main/java/org/java_websocket/SocketChannelIOHelper.java | 2 +- src/main/java/org/java_websocket/WebSocket.java | 2 +- src/main/java/org/java_websocket/WebSocketAdapter.java | 2 +- src/main/java/org/java_websocket/WebSocketFactory.java | 2 +- src/main/java/org/java_websocket/WebSocketImpl.java | 2 +- src/main/java/org/java_websocket/WebSocketListener.java | 2 +- src/main/java/org/java_websocket/WebSocketServerFactory.java | 2 +- src/main/java/org/java_websocket/WrappedByteChannel.java | 2 +- src/main/java/org/java_websocket/client/DnsResolver.java | 2 +- src/main/java/org/java_websocket/client/WebSocketClient.java | 2 +- src/main/java/org/java_websocket/client/package-info.java | 2 +- src/main/java/org/java_websocket/drafts/Draft.java | 2 +- src/main/java/org/java_websocket/drafts/Draft_6455.java | 2 +- src/main/java/org/java_websocket/drafts/package-info.java | 2 +- src/main/java/org/java_websocket/enums/package-info.java | 2 +- .../java/org/java_websocket/exceptions/IncompleteException.java | 2 +- .../java_websocket/exceptions/IncompleteHandshakeException.java | 2 +- .../org/java_websocket/exceptions/InvalidDataException.java | 2 +- .../org/java_websocket/exceptions/InvalidFrameException.java | 2 +- .../java_websocket/exceptions/InvalidHandshakeException.java | 2 +- .../org/java_websocket/exceptions/LimitExceededException.java | 2 +- .../org/java_websocket/exceptions/NotSendableException.java | 2 +- .../exceptions/WebsocketNotConnectedException.java | 2 +- src/main/java/org/java_websocket/exceptions/package-info.java | 2 +- .../org/java_websocket/extensions/CompressionExtension.java | 2 +- .../java/org/java_websocket/extensions/DefaultExtension.java | 2 +- src/main/java/org/java_websocket/extensions/IExtension.java | 2 +- src/main/java/org/java_websocket/extensions/package-info.java | 2 +- src/main/java/org/java_websocket/framing/BinaryFrame.java | 2 +- src/main/java/org/java_websocket/framing/CloseFrame.java | 2 +- src/main/java/org/java_websocket/framing/ContinuousFrame.java | 2 +- src/main/java/org/java_websocket/framing/ControlFrame.java | 2 +- src/main/java/org/java_websocket/framing/DataFrame.java | 2 +- src/main/java/org/java_websocket/framing/Framedata.java | 2 +- src/main/java/org/java_websocket/framing/FramedataImpl1.java | 2 +- src/main/java/org/java_websocket/framing/PingFrame.java | 2 +- src/main/java/org/java_websocket/framing/PongFrame.java | 2 +- src/main/java/org/java_websocket/framing/TextFrame.java | 2 +- src/main/java/org/java_websocket/framing/package-info.java | 2 +- src/main/java/org/java_websocket/handshake/ClientHandshake.java | 2 +- .../org/java_websocket/handshake/ClientHandshakeBuilder.java | 2 +- .../java/org/java_websocket/handshake/HandshakeBuilder.java | 2 +- .../java/org/java_websocket/handshake/HandshakeImpl1Client.java | 2 +- .../java/org/java_websocket/handshake/HandshakeImpl1Server.java | 2 +- src/main/java/org/java_websocket/handshake/Handshakedata.java | 2 +- .../java/org/java_websocket/handshake/HandshakedataImpl1.java | 2 +- src/main/java/org/java_websocket/handshake/ServerHandshake.java | 2 +- .../org/java_websocket/handshake/ServerHandshakeBuilder.java | 2 +- src/main/java/org/java_websocket/handshake/package-info.java | 2 +- src/main/java/org/java_websocket/interfaces/ISSLChannel.java | 2 +- src/main/java/org/java_websocket/interfaces/package-info.java | 2 +- src/main/java/org/java_websocket/protocols/IProtocol.java | 2 +- src/main/java/org/java_websocket/protocols/Protocol.java | 2 +- src/main/java/org/java_websocket/protocols/package-info.java | 2 +- .../java_websocket/server/CustomSSLWebSocketServerFactory.java | 2 +- .../java_websocket/server/DefaultSSLWebSocketServerFactory.java | 2 +- .../java_websocket/server/DefaultWebSocketServerFactory.java | 2 +- .../server/SSLParametersWebSocketServerFactory.java | 2 +- src/main/java/org/java_websocket/server/WebSocketServer.java | 2 +- src/main/java/org/java_websocket/server/package-info.java | 2 +- src/main/java/org/java_websocket/util/Base64.java | 2 +- src/main/java/org/java_websocket/util/ByteBufferUtils.java | 2 +- src/main/java/org/java_websocket/util/Charsetfunctions.java | 2 +- src/main/java/org/java_websocket/util/NamedThreadFactory.java | 2 +- src/main/java/org/java_websocket/util/package-info.java | 2 +- src/test/java/org/java_websocket/AllTests.java | 2 +- .../org/java_websocket/autobahn/AutobahnServerResultsTest.java | 2 +- src/test/java/org/java_websocket/client/AllClientTests.java | 2 +- src/test/java/org/java_websocket/client/AttachmentTest.java | 2 +- src/test/java/org/java_websocket/drafts/AllDraftTests.java | 2 +- src/test/java/org/java_websocket/drafts/Draft_6455Test.java | 2 +- .../java/org/java_websocket/example/AutobahnClientTest.java | 2 +- .../java/org/java_websocket/example/AutobahnSSLServerTest.java | 2 +- .../java/org/java_websocket/example/AutobahnServerTest.java | 2 +- .../java/org/java_websocket/exceptions/AllExceptionsTests.java | 2 +- .../org/java_websocket/exceptions/IncompleteExceptionTest.java | 2 +- .../exceptions/IncompleteHandshakeExceptionTest.java | 2 +- .../org/java_websocket/exceptions/InvalidDataExceptionTest.java | 2 +- .../java_websocket/exceptions/InvalidEncodingExceptionTest.java | 2 +- .../java_websocket/exceptions/InvalidFrameExceptionTest.java | 2 +- .../exceptions/InvalidHandshakeExceptionTest.java | 2 +- .../java_websocket/exceptions/LimitExceededExceptionTest.java | 2 +- .../org/java_websocket/exceptions/NotSendableExceptionTest.java | 2 +- .../exceptions/WebsocketNotConnectedExceptionTest.java | 2 +- .../java/org/java_websocket/extensions/AllExtensionTests.java | 2 +- .../org/java_websocket/extensions/DefaultExtensionTest.java | 2 +- src/test/java/org/java_websocket/framing/AllFramingTests.java | 2 +- src/test/java/org/java_websocket/framing/BinaryFrameTest.java | 2 +- src/test/java/org/java_websocket/framing/CloseFrameTest.java | 2 +- .../java/org/java_websocket/framing/ContinuousFrameTest.java | 2 +- .../java/org/java_websocket/framing/FramedataImpl1Test.java | 2 +- src/test/java/org/java_websocket/framing/PingFrameTest.java | 2 +- src/test/java/org/java_websocket/framing/PongFrameTest.java | 2 +- src/test/java/org/java_websocket/framing/TextFrameTest.java | 2 +- src/test/java/org/java_websocket/issues/AllIssueTests.java | 2 +- src/test/java/org/java_websocket/issues/Issue256Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue580Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue598Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue609Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue621Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue661Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue666Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue677Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue713Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue732Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue764Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue765Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue811Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue825Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue847Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue855Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue879Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue890Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue941Test.java | 2 +- src/test/java/org/java_websocket/issues/Issue962Test.java | 2 +- src/test/java/org/java_websocket/misc/AllMiscTests.java | 2 +- .../org/java_websocket/misc/OpeningHandshakeRejectionTest.java | 2 +- .../java/org/java_websocket/protocols/AllProtocolTests.java | 2 +- .../java_websocket/protocols/ProtoclHandshakeRejectionTest.java | 2 +- src/test/java/org/java_websocket/protocols/ProtocolTest.java | 2 +- src/test/java/org/java_websocket/server/AllServerTests.java | 2 +- .../java/org/java_websocket/server/WebSocketServerTest.java | 2 +- src/test/java/org/java_websocket/util/Base64Test.java | 2 +- src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java | 2 +- src/test/java/org/java_websocket/util/CharsetfunctionsTest.java | 2 +- src/test/java/org/java_websocket/util/KeyUtils.java | 2 +- src/test/java/org/java_websocket/util/SSLContextUtil.java | 2 +- src/test/java/org/java_websocket/util/SocketUtil.java | 2 +- src/test/java/org/java_websocket/util/ThreadCheck.java | 2 +- 151 files changed, 151 insertions(+), 151 deletions(-) diff --git a/LICENSE b/LICENSE index b6a6cac5c..bc4515cc6 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ - Copyright (c) 2010-2019 Nathan Rajlich + Copyright (c) 2010-2020 Nathan Rajlich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation diff --git a/src/main/example/ChatClient.java b/src/main/example/ChatClient.java index 4c6619e42..9a210592e 100644 --- a/src/main/example/ChatClient.java +++ b/src/main/example/ChatClient.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/example/ChatServer.java b/src/main/example/ChatServer.java index 40a0d9597..d12029117 100644 --- a/src/main/example/ChatServer.java +++ b/src/main/example/ChatServer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/example/ChatServerAttachmentExample.java b/src/main/example/ChatServerAttachmentExample.java index 920a57ae7..3b7b2d528 100644 --- a/src/main/example/ChatServerAttachmentExample.java +++ b/src/main/example/ChatServerAttachmentExample.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/example/CustomHeaderClientExample.java b/src/main/example/CustomHeaderClientExample.java index 775d5f89e..5f2c2818c 100644 --- a/src/main/example/CustomHeaderClientExample.java +++ b/src/main/example/CustomHeaderClientExample.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/example/ExampleClient.java b/src/main/example/ExampleClient.java index 8e617e320..c71343a0f 100644 --- a/src/main/example/ExampleClient.java +++ b/src/main/example/ExampleClient.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/example/FragmentedFramesExample.java b/src/main/example/FragmentedFramesExample.java index 792e015f8..aeb2cd868 100644 --- a/src/main/example/FragmentedFramesExample.java +++ b/src/main/example/FragmentedFramesExample.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/example/ProxyClientExample.java b/src/main/example/ProxyClientExample.java index 78b7b4469..fbd5a8a64 100644 --- a/src/main/example/ProxyClientExample.java +++ b/src/main/example/ProxyClientExample.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/example/ReconnectClientExample.java b/src/main/example/ReconnectClientExample.java index 96a07a901..ee607e47b 100644 --- a/src/main/example/ReconnectClientExample.java +++ b/src/main/example/ReconnectClientExample.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/example/SSLClientExample.java b/src/main/example/SSLClientExample.java index 74e2d9384..705bf9d10 100644 --- a/src/main/example/SSLClientExample.java +++ b/src/main/example/SSLClientExample.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/example/SSLServerCustomWebsocketFactoryExample.java b/src/main/example/SSLServerCustomWebsocketFactoryExample.java index dca5cbe0a..8f5aecd47 100644 --- a/src/main/example/SSLServerCustomWebsocketFactoryExample.java +++ b/src/main/example/SSLServerCustomWebsocketFactoryExample.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/example/SSLServerExample.java b/src/main/example/SSLServerExample.java index 5cfe723ee..9d8d8565c 100644 --- a/src/main/example/SSLServerExample.java +++ b/src/main/example/SSLServerExample.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/example/SSLServerLetsEncryptExample.java b/src/main/example/SSLServerLetsEncryptExample.java index 693ff8932..10e61340f 100644 --- a/src/main/example/SSLServerLetsEncryptExample.java +++ b/src/main/example/SSLServerLetsEncryptExample.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/example/SecWebSocketProtocolClientExample.java b/src/main/example/SecWebSocketProtocolClientExample.java index 38f35558b..45b99d114 100644 --- a/src/main/example/SecWebSocketProtocolClientExample.java +++ b/src/main/example/SecWebSocketProtocolClientExample.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/example/ServerAdditionalHeaderExample.java b/src/main/example/ServerAdditionalHeaderExample.java index 403faeede..b284abd5b 100644 --- a/src/main/example/ServerAdditionalHeaderExample.java +++ b/src/main/example/ServerAdditionalHeaderExample.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/example/ServerRejectHandshakeExample.java b/src/main/example/ServerRejectHandshakeExample.java index 16744d407..de312851e 100644 --- a/src/main/example/ServerRejectHandshakeExample.java +++ b/src/main/example/ServerRejectHandshakeExample.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/example/ServerStressTest.java b/src/main/example/ServerStressTest.java index 967be1318..e641a0eb3 100644 --- a/src/main/example/ServerStressTest.java +++ b/src/main/example/ServerStressTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/example/TwoWaySSLServerExample.java b/src/main/example/TwoWaySSLServerExample.java index dc477db62..d3e1413c1 100644 --- a/src/main/example/TwoWaySSLServerExample.java +++ b/src/main/example/TwoWaySSLServerExample.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/AbstractWebSocket.java b/src/main/java/org/java_websocket/AbstractWebSocket.java index fd0a3323c..63947b16a 100644 --- a/src/main/java/org/java_websocket/AbstractWebSocket.java +++ b/src/main/java/org/java_websocket/AbstractWebSocket.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/AbstractWrappedByteChannel.java b/src/main/java/org/java_websocket/AbstractWrappedByteChannel.java index 350b14dd4..093c99350 100644 --- a/src/main/java/org/java_websocket/AbstractWrappedByteChannel.java +++ b/src/main/java/org/java_websocket/AbstractWrappedByteChannel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/SSLSocketChannel.java b/src/main/java/org/java_websocket/SSLSocketChannel.java index a3cfd3de3..feeeaaa02 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/SSLSocketChannel2.java b/src/main/java/org/java_websocket/SSLSocketChannel2.java index 75a56c68a..b70289ed9 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel2.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel2.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/SocketChannelIOHelper.java b/src/main/java/org/java_websocket/SocketChannelIOHelper.java index 16b5e273c..ba1575288 100644 --- a/src/main/java/org/java_websocket/SocketChannelIOHelper.java +++ b/src/main/java/org/java_websocket/SocketChannelIOHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/WebSocket.java b/src/main/java/org/java_websocket/WebSocket.java index 559ef8977..c4d0441c7 100644 --- a/src/main/java/org/java_websocket/WebSocket.java +++ b/src/main/java/org/java_websocket/WebSocket.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/WebSocketAdapter.java b/src/main/java/org/java_websocket/WebSocketAdapter.java index 050d9ec26..9281c259c 100644 --- a/src/main/java/org/java_websocket/WebSocketAdapter.java +++ b/src/main/java/org/java_websocket/WebSocketAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/WebSocketFactory.java b/src/main/java/org/java_websocket/WebSocketFactory.java index 4743c6d90..8a2bcc022 100644 --- a/src/main/java/org/java_websocket/WebSocketFactory.java +++ b/src/main/java/org/java_websocket/WebSocketFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index 89c878d97..c4b56e6fa 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/WebSocketListener.java b/src/main/java/org/java_websocket/WebSocketListener.java index ed1038d17..23cdaef59 100644 --- a/src/main/java/org/java_websocket/WebSocketListener.java +++ b/src/main/java/org/java_websocket/WebSocketListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/WebSocketServerFactory.java b/src/main/java/org/java_websocket/WebSocketServerFactory.java index ed604c0ab..c8deaa2c8 100644 --- a/src/main/java/org/java_websocket/WebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/WebSocketServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/WrappedByteChannel.java b/src/main/java/org/java_websocket/WrappedByteChannel.java index baefac51a..06c2f0b4f 100644 --- a/src/main/java/org/java_websocket/WrappedByteChannel.java +++ b/src/main/java/org/java_websocket/WrappedByteChannel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/client/DnsResolver.java b/src/main/java/org/java_websocket/client/DnsResolver.java index 016f811b8..77b1823d8 100644 --- a/src/main/java/org/java_websocket/client/DnsResolver.java +++ b/src/main/java/org/java_websocket/client/DnsResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 756e57211..05b83976a 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/client/package-info.java b/src/main/java/org/java_websocket/client/package-info.java index 5e58a067a..e6d799d5f 100644 --- a/src/main/java/org/java_websocket/client/package-info.java +++ b/src/main/java/org/java_websocket/client/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/drafts/Draft.java b/src/main/java/org/java_websocket/drafts/Draft.java index 693320a01..77d5d19bb 100644 --- a/src/main/java/org/java_websocket/drafts/Draft.java +++ b/src/main/java/org/java_websocket/drafts/Draft.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index 126f154d9..335e5cf84 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/drafts/package-info.java b/src/main/java/org/java_websocket/drafts/package-info.java index 2fab8a024..13114293e 100644 --- a/src/main/java/org/java_websocket/drafts/package-info.java +++ b/src/main/java/org/java_websocket/drafts/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/enums/package-info.java b/src/main/java/org/java_websocket/enums/package-info.java index af5890e05..a5c997ea9 100644 --- a/src/main/java/org/java_websocket/enums/package-info.java +++ b/src/main/java/org/java_websocket/enums/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/exceptions/IncompleteException.java b/src/main/java/org/java_websocket/exceptions/IncompleteException.java index 71fd7cb3f..6f95e3845 100644 --- a/src/main/java/org/java_websocket/exceptions/IncompleteException.java +++ b/src/main/java/org/java_websocket/exceptions/IncompleteException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/exceptions/IncompleteHandshakeException.java b/src/main/java/org/java_websocket/exceptions/IncompleteHandshakeException.java index 4cc0b9eb6..0125ae342 100644 --- a/src/main/java/org/java_websocket/exceptions/IncompleteHandshakeException.java +++ b/src/main/java/org/java_websocket/exceptions/IncompleteHandshakeException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/exceptions/InvalidDataException.java b/src/main/java/org/java_websocket/exceptions/InvalidDataException.java index 48d7c727d..ec79a1625 100644 --- a/src/main/java/org/java_websocket/exceptions/InvalidDataException.java +++ b/src/main/java/org/java_websocket/exceptions/InvalidDataException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/exceptions/InvalidFrameException.java b/src/main/java/org/java_websocket/exceptions/InvalidFrameException.java index 7525ba443..336fef91b 100644 --- a/src/main/java/org/java_websocket/exceptions/InvalidFrameException.java +++ b/src/main/java/org/java_websocket/exceptions/InvalidFrameException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/exceptions/InvalidHandshakeException.java b/src/main/java/org/java_websocket/exceptions/InvalidHandshakeException.java index 523d7ac6f..7aa6881e0 100644 --- a/src/main/java/org/java_websocket/exceptions/InvalidHandshakeException.java +++ b/src/main/java/org/java_websocket/exceptions/InvalidHandshakeException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/exceptions/LimitExceededException.java b/src/main/java/org/java_websocket/exceptions/LimitExceededException.java index cc9fc3726..9642a77d3 100644 --- a/src/main/java/org/java_websocket/exceptions/LimitExceededException.java +++ b/src/main/java/org/java_websocket/exceptions/LimitExceededException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/exceptions/NotSendableException.java b/src/main/java/org/java_websocket/exceptions/NotSendableException.java index dffc0a40b..4ec9a1a64 100644 --- a/src/main/java/org/java_websocket/exceptions/NotSendableException.java +++ b/src/main/java/org/java_websocket/exceptions/NotSendableException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/exceptions/WebsocketNotConnectedException.java b/src/main/java/org/java_websocket/exceptions/WebsocketNotConnectedException.java index 0d0682fbd..3818af06a 100644 --- a/src/main/java/org/java_websocket/exceptions/WebsocketNotConnectedException.java +++ b/src/main/java/org/java_websocket/exceptions/WebsocketNotConnectedException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/exceptions/package-info.java b/src/main/java/org/java_websocket/exceptions/package-info.java index f43d72fe2..2b5d13621 100644 --- a/src/main/java/org/java_websocket/exceptions/package-info.java +++ b/src/main/java/org/java_websocket/exceptions/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/extensions/CompressionExtension.java b/src/main/java/org/java_websocket/extensions/CompressionExtension.java index 4b49efa93..703a7d0cf 100644 --- a/src/main/java/org/java_websocket/extensions/CompressionExtension.java +++ b/src/main/java/org/java_websocket/extensions/CompressionExtension.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/extensions/DefaultExtension.java b/src/main/java/org/java_websocket/extensions/DefaultExtension.java index 39a224594..4bad78b45 100644 --- a/src/main/java/org/java_websocket/extensions/DefaultExtension.java +++ b/src/main/java/org/java_websocket/extensions/DefaultExtension.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/extensions/IExtension.java b/src/main/java/org/java_websocket/extensions/IExtension.java index 471664c7f..b7236f2d8 100644 --- a/src/main/java/org/java_websocket/extensions/IExtension.java +++ b/src/main/java/org/java_websocket/extensions/IExtension.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/extensions/package-info.java b/src/main/java/org/java_websocket/extensions/package-info.java index 1af680b18..2a3338b7c 100644 --- a/src/main/java/org/java_websocket/extensions/package-info.java +++ b/src/main/java/org/java_websocket/extensions/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/framing/BinaryFrame.java b/src/main/java/org/java_websocket/framing/BinaryFrame.java index c3b15a6f7..bd0125991 100644 --- a/src/main/java/org/java_websocket/framing/BinaryFrame.java +++ b/src/main/java/org/java_websocket/framing/BinaryFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/framing/CloseFrame.java b/src/main/java/org/java_websocket/framing/CloseFrame.java index d9db7c30a..61e85fbdd 100644 --- a/src/main/java/org/java_websocket/framing/CloseFrame.java +++ b/src/main/java/org/java_websocket/framing/CloseFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/framing/ContinuousFrame.java b/src/main/java/org/java_websocket/framing/ContinuousFrame.java index b905a05ce..7e8738278 100644 --- a/src/main/java/org/java_websocket/framing/ContinuousFrame.java +++ b/src/main/java/org/java_websocket/framing/ContinuousFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/framing/ControlFrame.java b/src/main/java/org/java_websocket/framing/ControlFrame.java index d19225a00..fd088df65 100644 --- a/src/main/java/org/java_websocket/framing/ControlFrame.java +++ b/src/main/java/org/java_websocket/framing/ControlFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/framing/DataFrame.java b/src/main/java/org/java_websocket/framing/DataFrame.java index b6446d5bf..0a3ada56e 100644 --- a/src/main/java/org/java_websocket/framing/DataFrame.java +++ b/src/main/java/org/java_websocket/framing/DataFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/framing/Framedata.java b/src/main/java/org/java_websocket/framing/Framedata.java index 8b3276d22..03074dbdd 100644 --- a/src/main/java/org/java_websocket/framing/Framedata.java +++ b/src/main/java/org/java_websocket/framing/Framedata.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/framing/FramedataImpl1.java b/src/main/java/org/java_websocket/framing/FramedataImpl1.java index e8abe159f..21122fdeb 100644 --- a/src/main/java/org/java_websocket/framing/FramedataImpl1.java +++ b/src/main/java/org/java_websocket/framing/FramedataImpl1.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/framing/PingFrame.java b/src/main/java/org/java_websocket/framing/PingFrame.java index 5d03cd44e..fc60b9390 100644 --- a/src/main/java/org/java_websocket/framing/PingFrame.java +++ b/src/main/java/org/java_websocket/framing/PingFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/framing/PongFrame.java b/src/main/java/org/java_websocket/framing/PongFrame.java index f3789cfbe..31f5eb397 100644 --- a/src/main/java/org/java_websocket/framing/PongFrame.java +++ b/src/main/java/org/java_websocket/framing/PongFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/framing/TextFrame.java b/src/main/java/org/java_websocket/framing/TextFrame.java index a172e3ea6..8dc77f181 100644 --- a/src/main/java/org/java_websocket/framing/TextFrame.java +++ b/src/main/java/org/java_websocket/framing/TextFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/framing/package-info.java b/src/main/java/org/java_websocket/framing/package-info.java index 916cb9107..d5d73d161 100644 --- a/src/main/java/org/java_websocket/framing/package-info.java +++ b/src/main/java/org/java_websocket/framing/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/handshake/ClientHandshake.java b/src/main/java/org/java_websocket/handshake/ClientHandshake.java index 6548ebd7a..2108b913c 100644 --- a/src/main/java/org/java_websocket/handshake/ClientHandshake.java +++ b/src/main/java/org/java_websocket/handshake/ClientHandshake.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/handshake/ClientHandshakeBuilder.java b/src/main/java/org/java_websocket/handshake/ClientHandshakeBuilder.java index f8f71a83c..ea69a4395 100644 --- a/src/main/java/org/java_websocket/handshake/ClientHandshakeBuilder.java +++ b/src/main/java/org/java_websocket/handshake/ClientHandshakeBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/handshake/HandshakeBuilder.java b/src/main/java/org/java_websocket/handshake/HandshakeBuilder.java index 865e9005f..949f307f3 100644 --- a/src/main/java/org/java_websocket/handshake/HandshakeBuilder.java +++ b/src/main/java/org/java_websocket/handshake/HandshakeBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/handshake/HandshakeImpl1Client.java b/src/main/java/org/java_websocket/handshake/HandshakeImpl1Client.java index 635ecbaf2..f8b64e961 100644 --- a/src/main/java/org/java_websocket/handshake/HandshakeImpl1Client.java +++ b/src/main/java/org/java_websocket/handshake/HandshakeImpl1Client.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/handshake/HandshakeImpl1Server.java b/src/main/java/org/java_websocket/handshake/HandshakeImpl1Server.java index 0df101075..9df98d64d 100644 --- a/src/main/java/org/java_websocket/handshake/HandshakeImpl1Server.java +++ b/src/main/java/org/java_websocket/handshake/HandshakeImpl1Server.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/handshake/Handshakedata.java b/src/main/java/org/java_websocket/handshake/Handshakedata.java index cc88a4bbe..f2746095b 100644 --- a/src/main/java/org/java_websocket/handshake/Handshakedata.java +++ b/src/main/java/org/java_websocket/handshake/Handshakedata.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/handshake/HandshakedataImpl1.java b/src/main/java/org/java_websocket/handshake/HandshakedataImpl1.java index 55e10448d..4eb0654e4 100644 --- a/src/main/java/org/java_websocket/handshake/HandshakedataImpl1.java +++ b/src/main/java/org/java_websocket/handshake/HandshakedataImpl1.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/handshake/ServerHandshake.java b/src/main/java/org/java_websocket/handshake/ServerHandshake.java index cfdba8dd9..c3e79b856 100644 --- a/src/main/java/org/java_websocket/handshake/ServerHandshake.java +++ b/src/main/java/org/java_websocket/handshake/ServerHandshake.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/handshake/ServerHandshakeBuilder.java b/src/main/java/org/java_websocket/handshake/ServerHandshakeBuilder.java index 3c2f7b1d1..49acc755e 100644 --- a/src/main/java/org/java_websocket/handshake/ServerHandshakeBuilder.java +++ b/src/main/java/org/java_websocket/handshake/ServerHandshakeBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/handshake/package-info.java b/src/main/java/org/java_websocket/handshake/package-info.java index c2afc9edb..c9ba3c6fe 100644 --- a/src/main/java/org/java_websocket/handshake/package-info.java +++ b/src/main/java/org/java_websocket/handshake/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/interfaces/ISSLChannel.java b/src/main/java/org/java_websocket/interfaces/ISSLChannel.java index 6afd9b839..6bfb6d5fa 100644 --- a/src/main/java/org/java_websocket/interfaces/ISSLChannel.java +++ b/src/main/java/org/java_websocket/interfaces/ISSLChannel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/interfaces/package-info.java b/src/main/java/org/java_websocket/interfaces/package-info.java index 88dfa849d..b70dbc174 100644 --- a/src/main/java/org/java_websocket/interfaces/package-info.java +++ b/src/main/java/org/java_websocket/interfaces/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/protocols/IProtocol.java b/src/main/java/org/java_websocket/protocols/IProtocol.java index 6722a6c53..03ebe5a24 100644 --- a/src/main/java/org/java_websocket/protocols/IProtocol.java +++ b/src/main/java/org/java_websocket/protocols/IProtocol.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/protocols/Protocol.java b/src/main/java/org/java_websocket/protocols/Protocol.java index f5cc34009..4c3ba70f1 100644 --- a/src/main/java/org/java_websocket/protocols/Protocol.java +++ b/src/main/java/org/java_websocket/protocols/Protocol.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/protocols/package-info.java b/src/main/java/org/java_websocket/protocols/package-info.java index 22de9e68a..52016edd1 100644 --- a/src/main/java/org/java_websocket/protocols/package-info.java +++ b/src/main/java/org/java_websocket/protocols/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/server/CustomSSLWebSocketServerFactory.java b/src/main/java/org/java_websocket/server/CustomSSLWebSocketServerFactory.java index e10d252ec..a5900c2ab 100644 --- a/src/main/java/org/java_websocket/server/CustomSSLWebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/server/CustomSSLWebSocketServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java b/src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java index 7ac8a92c4..0874287e7 100644 --- a/src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/server/DefaultWebSocketServerFactory.java b/src/main/java/org/java_websocket/server/DefaultWebSocketServerFactory.java index 81ab7ec66..ec2e75767 100644 --- a/src/main/java/org/java_websocket/server/DefaultWebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/server/DefaultWebSocketServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/server/SSLParametersWebSocketServerFactory.java b/src/main/java/org/java_websocket/server/SSLParametersWebSocketServerFactory.java index 322131df1..3f78a9976 100644 --- a/src/main/java/org/java_websocket/server/SSLParametersWebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/server/SSLParametersWebSocketServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 07c7417ce..a8d8e3468 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/server/package-info.java b/src/main/java/org/java_websocket/server/package-info.java index 7a19d08d5..0676bafe6 100644 --- a/src/main/java/org/java_websocket/server/package-info.java +++ b/src/main/java/org/java_websocket/server/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/util/Base64.java b/src/main/java/org/java_websocket/util/Base64.java index 6bb63da8a..ceda3a577 100644 --- a/src/main/java/org/java_websocket/util/Base64.java +++ b/src/main/java/org/java_websocket/util/Base64.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/util/ByteBufferUtils.java b/src/main/java/org/java_websocket/util/ByteBufferUtils.java index 79e1a0367..ec02831fe 100644 --- a/src/main/java/org/java_websocket/util/ByteBufferUtils.java +++ b/src/main/java/org/java_websocket/util/ByteBufferUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/util/Charsetfunctions.java b/src/main/java/org/java_websocket/util/Charsetfunctions.java index cb5c4ed25..a131f5497 100644 --- a/src/main/java/org/java_websocket/util/Charsetfunctions.java +++ b/src/main/java/org/java_websocket/util/Charsetfunctions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/util/NamedThreadFactory.java b/src/main/java/org/java_websocket/util/NamedThreadFactory.java index 7d1154972..8e1b5dde9 100644 --- a/src/main/java/org/java_websocket/util/NamedThreadFactory.java +++ b/src/main/java/org/java_websocket/util/NamedThreadFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/main/java/org/java_websocket/util/package-info.java b/src/main/java/org/java_websocket/util/package-info.java index 4e1d894b3..af4d1afe2 100644 --- a/src/main/java/org/java_websocket/util/package-info.java +++ b/src/main/java/org/java_websocket/util/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/AllTests.java b/src/test/java/org/java_websocket/AllTests.java index 4de86a186..5ec33618e 100644 --- a/src/test/java/org/java_websocket/AllTests.java +++ b/src/test/java/org/java_websocket/AllTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/autobahn/AutobahnServerResultsTest.java b/src/test/java/org/java_websocket/autobahn/AutobahnServerResultsTest.java index 94c9a76c6..db7bafde1 100644 --- a/src/test/java/org/java_websocket/autobahn/AutobahnServerResultsTest.java +++ b/src/test/java/org/java_websocket/autobahn/AutobahnServerResultsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/client/AllClientTests.java b/src/test/java/org/java_websocket/client/AllClientTests.java index bec0ca926..ffc13457c 100644 --- a/src/test/java/org/java_websocket/client/AllClientTests.java +++ b/src/test/java/org/java_websocket/client/AllClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/client/AttachmentTest.java b/src/test/java/org/java_websocket/client/AttachmentTest.java index 1a2b2e1ef..fcccca865 100644 --- a/src/test/java/org/java_websocket/client/AttachmentTest.java +++ b/src/test/java/org/java_websocket/client/AttachmentTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/drafts/AllDraftTests.java b/src/test/java/org/java_websocket/drafts/AllDraftTests.java index f652f0eeb..c26179d8a 100644 --- a/src/test/java/org/java_websocket/drafts/AllDraftTests.java +++ b/src/test/java/org/java_websocket/drafts/AllDraftTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/drafts/Draft_6455Test.java b/src/test/java/org/java_websocket/drafts/Draft_6455Test.java index e544f936b..cbf41cedb 100644 --- a/src/test/java/org/java_websocket/drafts/Draft_6455Test.java +++ b/src/test/java/org/java_websocket/drafts/Draft_6455Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/example/AutobahnClientTest.java b/src/test/java/org/java_websocket/example/AutobahnClientTest.java index 54801e833..2707d7a2f 100644 --- a/src/test/java/org/java_websocket/example/AutobahnClientTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnClientTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java b/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java index 558de1bc9..6122fc8ab 100644 --- a/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/example/AutobahnServerTest.java b/src/test/java/org/java_websocket/example/AutobahnServerTest.java index 61eb4291c..bb2e10051 100644 --- a/src/test/java/org/java_websocket/example/AutobahnServerTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnServerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/exceptions/AllExceptionsTests.java b/src/test/java/org/java_websocket/exceptions/AllExceptionsTests.java index 15240ee2f..b50ef409a 100644 --- a/src/test/java/org/java_websocket/exceptions/AllExceptionsTests.java +++ b/src/test/java/org/java_websocket/exceptions/AllExceptionsTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java b/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java index 57b7cb78a..4a643fb13 100644 --- a/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java b/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java index a9d1266bd..a0bf81048 100644 --- a/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java index f8e3faf62..04e7693b3 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java index 46a9cad13..903c81ee7 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java index 9ab7994f8..f6e26878c 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java index 6bd7e5cc0..9e15e699f 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java b/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java index 3928fbc85..b8bde9f09 100644 --- a/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java b/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java index e17eef12f..e674eab01 100644 --- a/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java b/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java index 172a7eef1..f7f3b76ad 100644 --- a/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/extensions/AllExtensionTests.java b/src/test/java/org/java_websocket/extensions/AllExtensionTests.java index ea4b27d5e..736d1eb3f 100644 --- a/src/test/java/org/java_websocket/extensions/AllExtensionTests.java +++ b/src/test/java/org/java_websocket/extensions/AllExtensionTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java b/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java index 07adf81b1..d409d2a82 100644 --- a/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/framing/AllFramingTests.java b/src/test/java/org/java_websocket/framing/AllFramingTests.java index 1c5863ed8..900e3f395 100644 --- a/src/test/java/org/java_websocket/framing/AllFramingTests.java +++ b/src/test/java/org/java_websocket/framing/AllFramingTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/framing/BinaryFrameTest.java b/src/test/java/org/java_websocket/framing/BinaryFrameTest.java index ff0a9ce6a..994660652 100644 --- a/src/test/java/org/java_websocket/framing/BinaryFrameTest.java +++ b/src/test/java/org/java_websocket/framing/BinaryFrameTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/framing/CloseFrameTest.java b/src/test/java/org/java_websocket/framing/CloseFrameTest.java index efd498fe2..1246e926c 100644 --- a/src/test/java/org/java_websocket/framing/CloseFrameTest.java +++ b/src/test/java/org/java_websocket/framing/CloseFrameTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java b/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java index 7127d375f..a6ea68e11 100644 --- a/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java +++ b/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java b/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java index cb421eeec..fbfaa256e 100644 --- a/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java +++ b/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/framing/PingFrameTest.java b/src/test/java/org/java_websocket/framing/PingFrameTest.java index ae72defc2..2056d31b0 100644 --- a/src/test/java/org/java_websocket/framing/PingFrameTest.java +++ b/src/test/java/org/java_websocket/framing/PingFrameTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/framing/PongFrameTest.java b/src/test/java/org/java_websocket/framing/PongFrameTest.java index 50d4b4197..03bb316ed 100644 --- a/src/test/java/org/java_websocket/framing/PongFrameTest.java +++ b/src/test/java/org/java_websocket/framing/PongFrameTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/framing/TextFrameTest.java b/src/test/java/org/java_websocket/framing/TextFrameTest.java index c14c237e6..433e89962 100644 --- a/src/test/java/org/java_websocket/framing/TextFrameTest.java +++ b/src/test/java/org/java_websocket/framing/TextFrameTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/AllIssueTests.java b/src/test/java/org/java_websocket/issues/AllIssueTests.java index 3be0995af..f763d04e4 100644 --- a/src/test/java/org/java_websocket/issues/AllIssueTests.java +++ b/src/test/java/org/java_websocket/issues/AllIssueTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue256Test.java b/src/test/java/org/java_websocket/issues/Issue256Test.java index 7c908e224..f0556a765 100644 --- a/src/test/java/org/java_websocket/issues/Issue256Test.java +++ b/src/test/java/org/java_websocket/issues/Issue256Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue580Test.java b/src/test/java/org/java_websocket/issues/Issue580Test.java index bcbd59111..b196d7c6a 100644 --- a/src/test/java/org/java_websocket/issues/Issue580Test.java +++ b/src/test/java/org/java_websocket/issues/Issue580Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue598Test.java b/src/test/java/org/java_websocket/issues/Issue598Test.java index 69abc9432..50095ff3b 100644 --- a/src/test/java/org/java_websocket/issues/Issue598Test.java +++ b/src/test/java/org/java_websocket/issues/Issue598Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue609Test.java b/src/test/java/org/java_websocket/issues/Issue609Test.java index 4e94ac6f7..3e605fd92 100644 --- a/src/test/java/org/java_websocket/issues/Issue609Test.java +++ b/src/test/java/org/java_websocket/issues/Issue609Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue621Test.java b/src/test/java/org/java_websocket/issues/Issue621Test.java index 693afea8d..a76256a7a 100644 --- a/src/test/java/org/java_websocket/issues/Issue621Test.java +++ b/src/test/java/org/java_websocket/issues/Issue621Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue661Test.java b/src/test/java/org/java_websocket/issues/Issue661Test.java index 9ae994146..cf5ba5bc8 100644 --- a/src/test/java/org/java_websocket/issues/Issue661Test.java +++ b/src/test/java/org/java_websocket/issues/Issue661Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue666Test.java b/src/test/java/org/java_websocket/issues/Issue666Test.java index afc213bd2..872ced59b 100644 --- a/src/test/java/org/java_websocket/issues/Issue666Test.java +++ b/src/test/java/org/java_websocket/issues/Issue666Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue677Test.java b/src/test/java/org/java_websocket/issues/Issue677Test.java index 0be76941f..4a56957cf 100644 --- a/src/test/java/org/java_websocket/issues/Issue677Test.java +++ b/src/test/java/org/java_websocket/issues/Issue677Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue713Test.java b/src/test/java/org/java_websocket/issues/Issue713Test.java index 6f23a2583..6ed2f2e13 100644 --- a/src/test/java/org/java_websocket/issues/Issue713Test.java +++ b/src/test/java/org/java_websocket/issues/Issue713Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue732Test.java b/src/test/java/org/java_websocket/issues/Issue732Test.java index 26ed4ec80..15a13f426 100644 --- a/src/test/java/org/java_websocket/issues/Issue732Test.java +++ b/src/test/java/org/java_websocket/issues/Issue732Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue764Test.java b/src/test/java/org/java_websocket/issues/Issue764Test.java index 78120bf65..b0d265286 100644 --- a/src/test/java/org/java_websocket/issues/Issue764Test.java +++ b/src/test/java/org/java_websocket/issues/Issue764Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue765Test.java b/src/test/java/org/java_websocket/issues/Issue765Test.java index 42c81fa56..b6fc39ffc 100644 --- a/src/test/java/org/java_websocket/issues/Issue765Test.java +++ b/src/test/java/org/java_websocket/issues/Issue765Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue811Test.java b/src/test/java/org/java_websocket/issues/Issue811Test.java index e7e3c7f32..c6ebca0bd 100644 --- a/src/test/java/org/java_websocket/issues/Issue811Test.java +++ b/src/test/java/org/java_websocket/issues/Issue811Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue825Test.java b/src/test/java/org/java_websocket/issues/Issue825Test.java index 9c3c54939..b427e8fa2 100644 --- a/src/test/java/org/java_websocket/issues/Issue825Test.java +++ b/src/test/java/org/java_websocket/issues/Issue825Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue847Test.java b/src/test/java/org/java_websocket/issues/Issue847Test.java index f1034020b..b2f7ffd04 100644 --- a/src/test/java/org/java_websocket/issues/Issue847Test.java +++ b/src/test/java/org/java_websocket/issues/Issue847Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue855Test.java b/src/test/java/org/java_websocket/issues/Issue855Test.java index 2e27f29d1..ca681ad09 100644 --- a/src/test/java/org/java_websocket/issues/Issue855Test.java +++ b/src/test/java/org/java_websocket/issues/Issue855Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue879Test.java b/src/test/java/org/java_websocket/issues/Issue879Test.java index bd30cf99d..97bcfa333 100644 --- a/src/test/java/org/java_websocket/issues/Issue879Test.java +++ b/src/test/java/org/java_websocket/issues/Issue879Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue890Test.java b/src/test/java/org/java_websocket/issues/Issue890Test.java index 45d42d389..06d5db5dc 100644 --- a/src/test/java/org/java_websocket/issues/Issue890Test.java +++ b/src/test/java/org/java_websocket/issues/Issue890Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue941Test.java b/src/test/java/org/java_websocket/issues/Issue941Test.java index 53785deb5..25d53dc15 100644 --- a/src/test/java/org/java_websocket/issues/Issue941Test.java +++ b/src/test/java/org/java_websocket/issues/Issue941Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/issues/Issue962Test.java b/src/test/java/org/java_websocket/issues/Issue962Test.java index 09263fff2..f5927b81f 100644 --- a/src/test/java/org/java_websocket/issues/Issue962Test.java +++ b/src/test/java/org/java_websocket/issues/Issue962Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Olivier Ayache + * Copyright (c) 2010-2020 Olivier Ayache * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/misc/AllMiscTests.java b/src/test/java/org/java_websocket/misc/AllMiscTests.java index 8d71c6238..19ca884e5 100644 --- a/src/test/java/org/java_websocket/misc/AllMiscTests.java +++ b/src/test/java/org/java_websocket/misc/AllMiscTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java b/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java index 2708e9fd5..05e40f28f 100644 --- a/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java +++ b/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/protocols/AllProtocolTests.java b/src/test/java/org/java_websocket/protocols/AllProtocolTests.java index bcfd31f7c..03d5eaad8 100644 --- a/src/test/java/org/java_websocket/protocols/AllProtocolTests.java +++ b/src/test/java/org/java_websocket/protocols/AllProtocolTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java b/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java index ebc0b97bd..6ee3d89b3 100644 --- a/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java +++ b/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/protocols/ProtocolTest.java b/src/test/java/org/java_websocket/protocols/ProtocolTest.java index 7fb80cf85..faf32891c 100644 --- a/src/test/java/org/java_websocket/protocols/ProtocolTest.java +++ b/src/test/java/org/java_websocket/protocols/ProtocolTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/server/AllServerTests.java b/src/test/java/org/java_websocket/server/AllServerTests.java index 08392976b..4009a6b40 100644 --- a/src/test/java/org/java_websocket/server/AllServerTests.java +++ b/src/test/java/org/java_websocket/server/AllServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/server/WebSocketServerTest.java b/src/test/java/org/java_websocket/server/WebSocketServerTest.java index fcc17f91b..d7ab804f6 100644 --- a/src/test/java/org/java_websocket/server/WebSocketServerTest.java +++ b/src/test/java/org/java_websocket/server/WebSocketServerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/util/Base64Test.java b/src/test/java/org/java_websocket/util/Base64Test.java index 48499326a..c6d43378e 100644 --- a/src/test/java/org/java_websocket/util/Base64Test.java +++ b/src/test/java/org/java_websocket/util/Base64Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java b/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java index fa152b98e..12476b508 100644 --- a/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java +++ b/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java b/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java index e228a67d0..2ecc7b22c 100644 --- a/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java +++ b/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/util/KeyUtils.java b/src/test/java/org/java_websocket/util/KeyUtils.java index eb5bf9a01..8644d0098 100644 --- a/src/test/java/org/java_websocket/util/KeyUtils.java +++ b/src/test/java/org/java_websocket/util/KeyUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/util/SSLContextUtil.java b/src/test/java/org/java_websocket/util/SSLContextUtil.java index 9f56913a4..7d7d186d7 100644 --- a/src/test/java/org/java_websocket/util/SSLContextUtil.java +++ b/src/test/java/org/java_websocket/util/SSLContextUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/util/SocketUtil.java b/src/test/java/org/java_websocket/util/SocketUtil.java index 8f9c7c12f..65ca57bd7 100644 --- a/src/test/java/org/java_websocket/util/SocketUtil.java +++ b/src/test/java/org/java_websocket/util/SocketUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation diff --git a/src/test/java/org/java_websocket/util/ThreadCheck.java b/src/test/java/org/java_websocket/util/ThreadCheck.java index 3e9c56abd..a23f72b86 100644 --- a/src/test/java/org/java_websocket/util/ThreadCheck.java +++ b/src/test/java/org/java_websocket/util/ThreadCheck.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation From 7890fffd204aa1d81d16554dac86dc80eac845d0 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 19 Jan 2020 19:03:07 +0100 Subject: [PATCH 019/165] Added test for #900 Overwrite channel to always throw IOException --- .../org/java_websocket/WebSocketImpl.java | 2 +- .../java_websocket/issues/Issue900Test.java | 155 ++++++++++++++++++ 2 files changed, 156 insertions(+), 1 deletion(-) create mode 100644 src/test/java/org/java_websocket/issues/Issue900Test.java diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index a40669754..5c8e1a47d 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -512,7 +512,7 @@ public synchronized void closeConnection( int code, String message, boolean remo try { channel.close(); } catch ( IOException e ) { - if( e.getMessage().equals( "Broken pipe" ) ) { + if( e.getMessage() != null && e.getMessage().equals( "Broken pipe" ) ) { log.trace( "Caught IOException: Broken pipe during closeConnection()", e ); } else { log.error("Exception during channel.close()", e); diff --git a/src/test/java/org/java_websocket/issues/Issue900Test.java b/src/test/java/org/java_websocket/issues/Issue900Test.java new file mode 100644 index 000000000..5c8c11d13 --- /dev/null +++ b/src/test/java/org/java_websocket/issues/Issue900Test.java @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2010-2020 Nathan Rajlich + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +package org.java_websocket.issues; + +import org.java_websocket.WebSocket; +import org.java_websocket.WebSocketImpl; +import org.java_websocket.WrappedByteChannel; +import org.java_websocket.client.WebSocketClient; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.handshake.ServerHandshake; +import org.java_websocket.server.WebSocketServer; +import org.java_websocket.util.SocketUtil; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.net.InetSocketAddress; +import java.net.URI; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.concurrent.CountDownLatch; + +public class Issue900Test { + + CountDownLatch countServerDownLatch = new CountDownLatch(1); + CountDownLatch countCloseCallsDownLatch = new CountDownLatch(1); + + @Test(timeout = 2000) + public void testIssue() throws Exception { + int port = SocketUtil.getAvailablePort(); + final WebSocketClient client = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + + } + + @Override + public void onMessage(String message) { + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + + } + }; + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + countCloseCallsDownLatch.countDown(); + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + }; + new Thread(server).start(); + countServerDownLatch.await(); + client.connectBlocking(); + WebSocketImpl websocketImpl = (WebSocketImpl)new ArrayList(server.getConnections()).get(0); + websocketImpl.setChannel(new ExceptionThrowingByteChannel()); + server.broadcast("test"); + countCloseCallsDownLatch.await(); + } + class ExceptionThrowingByteChannel implements WrappedByteChannel { + + @Override + public boolean isNeedWrite() { + return false; + } + + @Override + public void writeMore() throws IOException { + throw new IOException(); + } + + @Override + public boolean isNeedRead() { + return false; + } + + @Override + public int readMore(ByteBuffer dst) throws IOException { + throw new IOException(); + } + + @Override + public boolean isBlocking() { + return false; + } + + @Override + public int read(ByteBuffer dst) throws IOException { + throw new IOException(); + } + + @Override + public int write(ByteBuffer src) throws IOException { + throw new IOException(); + } + + @Override + public boolean isOpen() { + return false; + } + + @Override + public void close() throws IOException { + throw new IOException(); + } + } +} From 992da3d4f9ae40568690616bd39b7fbfc2d9b40a Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 19 Jan 2020 19:04:25 +0100 Subject: [PATCH 020/165] Update WrappedIOException.java Adjust year --- .../java/org/java_websocket/exceptions/WrappedIOException.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/exceptions/WrappedIOException.java b/src/main/java/org/java_websocket/exceptions/WrappedIOException.java index 075de883e..4603ad85a 100644 --- a/src/main/java/org/java_websocket/exceptions/WrappedIOException.java +++ b/src/main/java/org/java_websocket/exceptions/WrappedIOException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Nathan Rajlich + * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation From 99220bcde130da9153352a880c22afc2dc8c3f63 Mon Sep 17 00:00:00 2001 From: Victor Toni Date: Mon, 20 Jan 2020 09:09:41 +0100 Subject: [PATCH 021/165] Made loggers non-static to support deployment in containers For reference see: http://slf4j.org/faq.html#declared_static https://cwiki.apache.org/confluence/display/COMMONS/Logging+StaticLog Signed-off-by: Victor Toni --- .../java/org/java_websocket/AbstractWebSocket.java | 2 +- .../java/org/java_websocket/SSLSocketChannel.java | 2 +- .../java/org/java_websocket/SSLSocketChannel2.java | 12 ++++++------ src/main/java/org/java_websocket/WebSocketImpl.java | 2 +- .../java/org/java_websocket/drafts/Draft_6455.java | 2 +- .../org/java_websocket/server/WebSocketServer.java | 6 +++--- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/java_websocket/AbstractWebSocket.java b/src/main/java/org/java_websocket/AbstractWebSocket.java index 63947b16a..d39c898ec 100644 --- a/src/main/java/org/java_websocket/AbstractWebSocket.java +++ b/src/main/java/org/java_websocket/AbstractWebSocket.java @@ -48,7 +48,7 @@ public abstract class AbstractWebSocket extends WebSocketAdapter { * * @since 1.4.0 */ - private static final Logger log = LoggerFactory.getLogger(AbstractWebSocket.class); + private final Logger log = LoggerFactory.getLogger(AbstractWebSocket.class); /** * Attribute which allows you to deactivate the Nagle's algorithm diff --git a/src/main/java/org/java_websocket/SSLSocketChannel.java b/src/main/java/org/java_websocket/SSLSocketChannel.java index feeeaaa02..044f8b07e 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel.java @@ -70,7 +70,7 @@ public class SSLSocketChannel implements WrappedByteChannel, ByteChannel, ISSLCh * * @since 1.4.0 */ - private static final Logger log = LoggerFactory.getLogger(SSLSocketChannel.class); + private final Logger log = LoggerFactory.getLogger(SSLSocketChannel.class); /** * The underlaying socket channel diff --git a/src/main/java/org/java_websocket/SSLSocketChannel2.java b/src/main/java/org/java_websocket/SSLSocketChannel2.java index 07df1364e..e2fb0acc0 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel2.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel2.java @@ -55,17 +55,17 @@ */ public class SSLSocketChannel2 implements ByteChannel, WrappedByteChannel, ISSLChannel { + /** + * This object is used to feed the {@link SSLEngine}'s wrap and unwrap methods during the handshake phase. + **/ + protected static ByteBuffer emptybuffer = ByteBuffer.allocate( 0 ); + /** * Logger instance * * @since 1.4.0 */ - private static final Logger log = LoggerFactory.getLogger(SSLSocketChannel2.class); - - /** - * This object is used to feed the {@link SSLEngine}'s wrap and unwrap methods during the handshake phase. - **/ - protected static ByteBuffer emptybuffer = ByteBuffer.allocate( 0 ); + private final Logger log = LoggerFactory.getLogger(SSLSocketChannel2.class); protected ExecutorService exec; diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index c4b56e6fa..cb7644fac 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -85,7 +85,7 @@ public class WebSocketImpl implements WebSocket { * * @since 1.4.0 */ - private static final Logger log = LoggerFactory.getLogger(WebSocketImpl.class); + private final Logger log = LoggerFactory.getLogger(WebSocketImpl.class); /** * Queue of buffers that need to be sent to the client. diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index 335e5cf84..f80172bff 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -86,7 +86,7 @@ public class Draft_6455 extends Draft { * * @since 1.4.0 */ - private static final Logger log = LoggerFactory.getLogger(Draft_6455.class); + private final Logger log = LoggerFactory.getLogger(Draft_6455.class); /** * Attribute for the used extension in this draft diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index a8d8e3468..cd3ac8842 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -64,14 +64,14 @@ */ public abstract class WebSocketServer extends AbstractWebSocket implements Runnable { + private static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); + /** * Logger instance * * @since 1.4.0 */ - private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class); - - private static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); + private final Logger log = LoggerFactory.getLogger(WebSocketServer.class); /** * Holds the list of active WebSocket connections. "Active" means WebSocket From cc64b39b8ef56a19ca1c98476ea20b1ff35767c1 Mon Sep 17 00:00:00 2001 From: Victor Toni Date: Mon, 20 Jan 2020 09:14:02 +0100 Subject: [PATCH 022/165] Removed unused imports Signed-off-by: Victor Toni --- src/main/java/org/java_websocket/server/WebSocketServer.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index cd3ac8842..be346bf94 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -46,13 +46,11 @@ import org.java_websocket.*; import org.java_websocket.drafts.Draft; -import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.WebsocketNotConnectedException; import org.java_websocket.framing.CloseFrame; import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.Handshakedata; -import org.java_websocket.handshake.ServerHandshakeBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; From 6636d3272dceb364afac34311cff5749deccc49d Mon Sep 17 00:00:00 2001 From: Victor Toni Date: Mon, 20 Jan 2020 09:14:41 +0100 Subject: [PATCH 023/165] Fixed small documentation typo in `SSLSocketChannel` Signed-off-by: Victor Toni --- src/main/java/org/java_websocket/SSLSocketChannel.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/SSLSocketChannel.java b/src/main/java/org/java_websocket/SSLSocketChannel.java index 044f8b07e..ed8a797d2 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel.java @@ -73,7 +73,7 @@ public class SSLSocketChannel implements WrappedByteChannel, ByteChannel, ISSLCh private final Logger log = LoggerFactory.getLogger(SSLSocketChannel.class); /** - * The underlaying socket channel + * The underlying socket channel */ private final SocketChannel socketChannel; From 5b889a42fcc9c7e09649732feb564abb676e9b5c Mon Sep 17 00:00:00 2001 From: Victor Toni Date: Mon, 20 Jan 2020 10:14:02 +0100 Subject: [PATCH 024/165] Centralized dependency version management by using version properties Signed-off-by: Victor Toni --- pom.xml | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/pom.xml b/pom.xml index a2122a2b1..46a8e1d58 100644 --- a/pom.xml +++ b/pom.xml @@ -12,6 +12,20 @@ UTF-8 1.7.25 + + + 4.12 + 20180813 + + + 3.7.0 + 1.6 + 3.0.2 + 2.10.3 + 3.1.0 + 3.0.0 + 1.6.8 + @@ -33,7 +47,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.7.0 + ${maven.compiler.plugin.version} 1.6 1.6 @@ -55,7 +69,7 @@ org.apache.maven.plugins maven-gpg-plugin - 1.6 + ${maven.gpg.plugin.version} sign-artifacts @@ -69,7 +83,7 @@ org.sonatype.plugins nexus-staging-maven-plugin - 1.6.8 + ${nexus.staging.maven.plugin.version} true ossrh @@ -79,7 +93,7 @@ org.apache.maven.plugins maven-source-plugin - 2.4 + ${maven.source.plugin.version} attach-sources @@ -92,7 +106,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 2.10.2 + ${maven.javadoc.plugin.version} attach-javadocs @@ -122,7 +136,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.1.0 + ${maven.shade.plugin.version} package @@ -146,7 +160,7 @@ org.apache.maven.plugins maven-source-plugin - 3.0.0 + ${maven.source.plugin.version} attach-sources @@ -159,7 +173,7 @@ org.apache.maven.plugins maven-jar-plugin - 3.0.2 + ${maven.jar.plugin.version} @@ -171,7 +185,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 2.10.3 + ${maven.javadoc.plugin.version} attach-javadocs @@ -184,7 +198,7 @@ org.apache.maven.plugins maven-gpg-plugin - 1.6 + ${maven.gpg.plugin.version} sign-artifacts @@ -224,13 +238,13 @@ junit junit - 4.12 + ${junit.version} test org.json json - 20180813 + ${org.json.version} test From dab84f032f67068cc83ffbaa1efcf1d667d4ca86 Mon Sep 17 00:00:00 2001 From: Victor Toni Date: Mon, 20 Jan 2020 10:55:13 +0100 Subject: [PATCH 025/165] Moved dependencies and plugins to `dependencyManagement` / `pluginManagement` Signed-off-by: Victor Toni --- pom.xml | 165 ++++++++++++++++++++++++++++++++------------------------ 1 file changed, 96 insertions(+), 69 deletions(-) diff --git a/pom.xml b/pom.xml index 46a8e1d58..f0ee58953 100644 --- a/pom.xml +++ b/pom.xml @@ -40,18 +40,109 @@ https://github.com/TooTallNate/Java-WebSocket/issues GitHub Issues + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + slf4j-simple + ${slf4j.version} + test + + + junit + junit + ${junit.version} + test + + + org.json + json + ${org.json.version} + test + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.plugin.version} + + 1.6 + 1.6 + + + + org.apache.maven.plugins + maven-gpg-plugin + ${maven.gpg.plugin.version} + + + sign-artifacts + verify + + sign + + + + + + org.apache.maven.plugins + maven-jar-plugin + ${maven.jar.plugin.version} + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven.javadoc.plugin.version} + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-shade-plugin + ${maven.shade.plugin.version} + + + org.apache.maven.plugins + maven-source-plugin + ${maven.source.plugin.version} + + + attach-sources + + jar-no-fork + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + ${nexus.staging.maven.plugin.version} + + + src/main/java src/test/java org.apache.maven.plugins maven-compiler-plugin - ${maven.compiler.plugin.version} - - 1.6 - 1.6 - @@ -69,21 +160,10 @@ org.apache.maven.plugins maven-gpg-plugin - ${maven.gpg.plugin.version} - - - sign-artifacts - verify - - sign - - - org.sonatype.plugins nexus-staging-maven-plugin - ${nexus.staging.maven.plugin.version} true ossrh @@ -93,28 +173,10 @@ org.apache.maven.plugins maven-source-plugin - ${maven.source.plugin.version} - - - attach-sources - - jar-no-fork - - - org.apache.maven.plugins maven-javadoc-plugin - ${maven.javadoc.plugin.version} - - - attach-javadocs - - jar - - - @@ -128,7 +190,6 @@ org.slf4j slf4j-simple - ${slf4j.version} @@ -136,7 +197,6 @@ org.apache.maven.plugins maven-shade-plugin - ${maven.shade.plugin.version} package @@ -160,20 +220,10 @@ org.apache.maven.plugins maven-source-plugin - ${maven.source.plugin.version} - - - attach-sources - - jar-no-fork - - - org.apache.maven.plugins maven-jar-plugin - ${maven.jar.plugin.version} @@ -185,29 +235,10 @@ org.apache.maven.plugins maven-javadoc-plugin - ${maven.javadoc.plugin.version} - - - attach-javadocs - - jar - - - org.apache.maven.plugins maven-gpg-plugin - ${maven.gpg.plugin.version} - - - sign-artifacts - verify - - sign - - - @@ -227,24 +258,20 @@ org.slf4j slf4j-api - ${slf4j.version} org.slf4j slf4j-simple - ${slf4j.version} test junit junit - ${junit.version} test org.json json - ${org.json.version} test From ba248d47ea172b6db0d93ba53b5e9494f168c031 Mon Sep 17 00:00:00 2001 From: Victor Toni Date: Mon, 20 Jan 2020 13:42:20 +0100 Subject: [PATCH 026/165] Added `bnd-maven-plugin` to provide OSGi metadata in `MANIFEST.MF` Signed-off-by: Victor Toni --- pom.xml | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/pom.xml b/pom.xml index f0ee58953..e968d2940 100644 --- a/pom.xml +++ b/pom.xml @@ -18,6 +18,7 @@ 20180813 + 4.3.1 3.7.0 1.6 3.0.2 @@ -71,6 +72,26 @@ + + biz.aQute.bnd + bnd-maven-plugin + ${bnd.maven.plugin.version} + + + + bnd-process + + + + + + + org.apache.maven.plugins maven-compiler-plugin @@ -98,6 +119,11 @@ org.apache.maven.plugins maven-jar-plugin ${maven.jar.plugin.version} + + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + org.apache.maven.plugins @@ -140,6 +166,10 @@ src/main/java src/test/java + + biz.aQute.bnd + bnd-maven-plugin + org.apache.maven.plugins maven-compiler-plugin @@ -157,6 +187,10 @@ + + biz.aQute.bnd + bnd-maven-plugin + org.apache.maven.plugins maven-gpg-plugin @@ -194,6 +228,10 @@ + + biz.aQute.bnd + bnd-maven-plugin + org.apache.maven.plugins maven-shade-plugin From 6dfa525091037076ba0d93e1bd6148295756dac5 Mon Sep 17 00:00:00 2001 From: Victor Toni Date: Mon, 20 Jan 2020 13:43:51 +0100 Subject: [PATCH 027/165] Added IDs for developers in `pom.xml` to get rid of warnings of `bnd-maven-plugin` Signed-off-by: Victor Toni --- pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pom.xml b/pom.xml index e968d2940..f07640a82 100644 --- a/pom.xml +++ b/pom.xml @@ -315,11 +315,13 @@ + TooTallNate Nathan Rajlich https://github.com/TooTallNate nathan@tootallnate.net + marci4 Marcel Prestel https://github.com/marci4 admin@marci4.de From 72aebe1d2ff5ce84d116db4caa9c7a8f4bbed8b1 Mon Sep 17 00:00:00 2001 From: marci4 Date: Mon, 20 Jan 2020 20:21:50 +0100 Subject: [PATCH 028/165] Rework after review --- .../java_websocket/issues/Issue900Test.java | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/test/java/org/java_websocket/issues/Issue900Test.java b/src/test/java/org/java_websocket/issues/Issue900Test.java index 5c8c11d13..c528534ea 100644 --- a/src/test/java/org/java_websocket/issues/Issue900Test.java +++ b/src/test/java/org/java_websocket/issues/Issue900Test.java @@ -37,8 +37,6 @@ import org.junit.Test; import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.net.URI; import java.nio.ByteBuffer; @@ -47,8 +45,8 @@ public class Issue900Test { - CountDownLatch countServerDownLatch = new CountDownLatch(1); - CountDownLatch countCloseCallsDownLatch = new CountDownLatch(1); + CountDownLatch serverStartLatch = new CountDownLatch(1); + CountDownLatch closeCalledLatch = new CountDownLatch(1); @Test(timeout = 2000) public void testIssue() throws Exception { @@ -79,7 +77,7 @@ public void onOpen(WebSocket conn, ClientHandshake handshake) { @Override public void onClose(WebSocket conn, int code, String reason, boolean remote) { - countCloseCallsDownLatch.countDown(); + closeCalledLatch.countDown(); } @Override @@ -94,22 +92,22 @@ public void onError(WebSocket conn, Exception ex) { @Override public void onStart() { - countServerDownLatch.countDown(); + serverStartLatch.countDown(); } }; new Thread(server).start(); - countServerDownLatch.await(); + serverStartLatch.await(); client.connectBlocking(); WebSocketImpl websocketImpl = (WebSocketImpl)new ArrayList(server.getConnections()).get(0); websocketImpl.setChannel(new ExceptionThrowingByteChannel()); server.broadcast("test"); - countCloseCallsDownLatch.await(); + closeCalledLatch.await(); } class ExceptionThrowingByteChannel implements WrappedByteChannel { @Override public boolean isNeedWrite() { - return false; + return true; } @Override @@ -119,7 +117,7 @@ public void writeMore() throws IOException { @Override public boolean isNeedRead() { - return false; + return true; } @Override From 1e8e1def60b7574422ef0cbef79375ff466247bd Mon Sep 17 00:00:00 2001 From: marci4 Date: Thu, 12 Mar 2020 22:12:17 +0100 Subject: [PATCH 029/165] Update Changelog --- CHANGELOG.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2168713fc..08df0c50f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,49 @@ # Change log +## Version Release 1.4.1 (2020/03/12) + +#### Bugs Fixed + +* [Issue 940](https://github.com/TooTallNate/Java-WebSocket/issues/940) - WebSocket handshake fails over WSS, if client uses TLS False Start ([PR 943](https://github.com/TooTallNate/Java-WebSocket/pull/943)) +* [Issue 921](https://github.com/TooTallNate/Java-WebSocket/issues/921) - ConcurrentModificationException when looping connections +* [Issue 905](https://github.com/TooTallNate/Java-WebSocket/issues/905) - IOException wrapped in InternalError not handled properly ([PR 901](https://github.com/TooTallNate/Java-WebSocket/pull/901)) +* [Issue 900](https://github.com/TooTallNate/Java-WebSocket/issues/900) - OnClose is not called when client disconnect ([PR 914](https://github.com/TooTallNate/Java-WebSocket/pull/914)) +* [Issue 869](https://github.com/TooTallNate/Java-WebSocket/issues/869) - Lost connection detection is sensitive to changes in system time ([PR 878](https://github.com/TooTallNate/Java-WebSocket/pull/878)) +* [Issue 665](https://github.com/TooTallNate/Java-WebSocket/issues/665) - Data read with end of SSL handshake is discarded ([PR 943](https://github.com/TooTallNate/Java-WebSocket/pull/943)) +* [PR 943](https://github.com/TooTallNate/Java-WebSocket/pull/943) - Merge pull request #943 from da-als/master +* [PR 922](https://github.com/TooTallNate/Java-WebSocket/pull/922) - Fix ConcurrentModificationException when iterating through connection +* [PR 914](https://github.com/TooTallNate/Java-WebSocket/pull/914) - Merge pull request #914 from marci4/Issue900 +* [PR 902](https://github.com/TooTallNate/Java-WebSocket/pull/902) - ConcurrentModificationException when using broadcast +* [PR 901](https://github.com/TooTallNate/Java-WebSocket/pull/901) - fix when proxy tunneling failed (IOException is hidden) JDK-8173 +* [PR 878](https://github.com/TooTallNate/Java-WebSocket/pull/878) - Replace TimerTask with ScheduledExecutorService + +#### New Features + +* [Issue 969](https://github.com/TooTallNate/Java-WebSocket/issues/969) - Loggers should be declared non-static ([PR 970](https://github.com/TooTallNate/Java-WebSocket/pull/970)) +* [Issue 962](https://github.com/TooTallNate/Java-WebSocket/issues/962) - Improvements in socket connect to server ([PR 964](https://github.com/TooTallNate/Java-WebSocket/pull/964)) +* [Issue 941](https://github.com/TooTallNate/Java-WebSocket/issues/941) - How to send customized ping message on connectionLostTimeout interval ([PR 944](https://github.com/TooTallNate/Java-WebSocket/pull/944)) +* [Issue 890](https://github.com/TooTallNate/Java-WebSocket/issues/890) - Would like to get SSLSession from WebSocket on server to examine client certificates ([PR 893](https://github.com/TooTallNate/Java-WebSocket/pull/893)) +* [Issue 865](https://github.com/TooTallNate/Java-WebSocket/issues/865) - Append new headers to the client when reconnecting +* [Issue 859](https://github.com/TooTallNate/Java-WebSocket/issues/859) - Hot wo specify a custom DNS Resolver ([PR 906](https://github.com/TooTallNate/Java-WebSocket/pull/906)) +* [PR 971](https://github.com/TooTallNate/Java-WebSocket/pull/971) - Enabled OSGi metadata in MANIFST-MF for created JAR +* [PR 964](https://github.com/TooTallNate/Java-WebSocket/pull/964) - Use socket isConnected() method rather than isBound() +* [PR 944](https://github.com/TooTallNate/Java-WebSocket/pull/944) - Add ability to customize ping messages with custom data +* [PR 906](https://github.com/TooTallNate/Java-WebSocket/pull/906) - Implemented a custom DNS resolver, see #859 +* [PR 893](https://github.com/TooTallNate/Java-WebSocket/pull/893) - Provide a way to access the SSLSession of a websocket instance +* [PR 868](https://github.com/TooTallNate/Java-WebSocket/pull/868) - Add a way to put additional headers to handshake for connecting/reconnecting, see #865 + +#### Refactoring + +* [Issue 907](https://github.com/TooTallNate/Java-WebSocket/issues/907) - build fails with Gradle 5+ ([PR 908](https://github.com/TooTallNate/Java-WebSocket/pull/908)) +* [Issue 869](https://github.com/TooTallNate/Java-WebSocket/issues/869) - Lost connection detection is sensitive to changes in system time ([PR 878](https://github.com/TooTallNate/Java-WebSocket/pull/878)) +* [PR 970](https://github.com/TooTallNate/Java-WebSocket/pull/970) - Made loggers non-static to support deployment in containers +* [PR 931](https://github.com/TooTallNate/Java-WebSocket/pull/931) - Create new github actions +* [PR 908](https://github.com/TooTallNate/Java-WebSocket/pull/908) - Remove outdated 'wrapper' task from build.gradle (#907) +* [PR 878](https://github.com/TooTallNate/Java-WebSocket/pull/878) - Replace TimerTask with ScheduledExecutorService +* [PR 874](https://github.com/TooTallNate/Java-WebSocket/pull/874) - Update dependencies + +In this release 14 issues and 17 pull requests were closed. + ## Version Release 1.4.0 (2019/02/19) #### Breaking Changes From d34401993ef4097f6b471d7600e3cce45c1b6ff5 Mon Sep 17 00:00:00 2001 From: marci4 Date: Thu, 12 Mar 2020 22:24:34 +0100 Subject: [PATCH 030/165] Release of 1.4.1 --- README.markdown | 7 +++---- pom.xml | 6 +++--- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/README.markdown b/README.markdown index 937e0ba9f..8501dcb08 100644 --- a/README.markdown +++ b/README.markdown @@ -29,7 +29,7 @@ To use maven add this dependency to your pom.xml: org.java-websocket Java-WebSocket - 1.4.0 + 1.4.1 ``` @@ -40,7 +40,7 @@ mavenCentral() ``` Then you can just add the latest version to your build. ```xml -compile "org.java-websocket:Java-WebSocket:1.4.0" +compile "org.java-websocket:Java-WebSocket:1.4.1" ``` #### Logging @@ -109,8 +109,7 @@ Minimum Required JDK `Java-WebSocket` is known to work with: - * Java 1.6 and higher - * Android 4.0 and higher + * Java 1.7 and higher Other JRE implementations may work as well, but haven't been tested. diff --git a/pom.xml b/pom.xml index f07640a82..8f809397a 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.java-websocket Java-WebSocket jar - 1.4.1-SNAPSHOT + 1.5.0-SNAPSHOT Java-WebSocket A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket @@ -97,8 +97,8 @@ maven-compiler-plugin ${maven.compiler.plugin.version} - 1.6 - 1.6 + 1.7 + 1.7 From 315f5554e9779b0a38f55e157bc017a0875ba892 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 29 Mar 2020 20:00:11 +0200 Subject: [PATCH 031/165] Adjust path for keystore --- keystore.jks | Bin 2251 -> 0 bytes src/main/example/SSLClientExample.java | 2 +- ...SLServerCustomWebsocketFactoryExample.java | 2 +- src/main/example/SSLServerExample.java | 2 +- src/main/example/TwoWaySSLServerExample.java | 2 +- .../example/AutobahnSSLServerTest.java | 2 +- src/test/java/org/java_websocket/keystore.jks | Bin 2251 -> 2057 bytes 7 files changed, 5 insertions(+), 5 deletions(-) delete mode 100644 keystore.jks diff --git a/keystore.jks b/keystore.jks deleted file mode 100644 index 743add50e6fe50f8e00c182085024bab565743b2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2251 zcmc&#_fr#y5>7%ANa&zIATd%^YC;K3kRsB9R4IZW<`~JyE{AI?(F_t`?&@H06;7U{_X5ugx@^E z{7EeAqH;Mn699k!FfrgG3=b482L*zGvLJpS5CQu|>lMdZZ4Q-QTUKZSkYw$? zMhlIp<#S^$aw%#k?oOW3TvBLh>NmuzM1x_YOXFjxij_r5{np@3eKpuSn7TT1+upaZCGT|jzX_htTF19C(MM`-S0n+AT20&jL2`mb?)vtmC18jWjK7Pb%j!Y z%Jha!+(57)YCfj4(Li{nbY)2HG~m%?<~P>>r#ibyyD`8_teman9=Il2y> z&_YZ6o_&%C1UL;9MNjEQSB&SE(~=_3)gHWc&_&ret;)>zIQfv|y`L(s8hEVZN`8;b zs}(Ix4c<%{)gi({3obJwIsW_#n~R%`It*$|$9XSVZ+-?0NGt;nS7!QV%%ST z{YjUl`0(?<2@msou^uhWt=xkIF8I8gUg9;y9e2;1pfjd`T)l<6(LSOQAN}e@dm`Q# zU@S~Mv-#YT*T-(pg))F2Mh#vTr)VclaeQ!*)!Nq%O$F7q>`p)EMym(HZ5<1!BSYy5 zI{7L@{|I-imza;J=ySC$k?S9Yi(HMS3QK!zI!x~4BGx}x>DLJ!it|HaJA6%EHF(Ym z=;!ft#A$lTg_e%B6i)4P%kV^hq^swb)Zadzjk=prrlS2#qqkblEsPdKE`xW=RlKz; zl$8^Q4?02K=fu+PTvOCMmqIdM-DA`U^d^_7(c^N^hlRX9lJ+Q**1Jbmf6;D^x!VqI zH7wuT@r{&8dO?3<7cZAqXV^l?cknZwYTC|>ax7skMk$?tSd4Bo_B)%s{<0tpmzkin zJ|T4iu+{fh{ESU^8x`#%4Ii<>GCTCV=;5I3F}szCR)ddrpX>MYenlhhUaG=M?T z@601y8*=98h{20eq^Qy}v8^aK={)Rw`nWO_DJwRcs4AqHUo(9{{F6Yv ze3xn5X5|W{2XkyFKxABX9;jdQ?#ET9X^jHC=9<_nFOr>y7b~6YkkXz0$8|uJG0= z7HcYvBp{PGs|8OPYEs2rs2c<&2UZq3UKGBHx~xHD{lA z#3(>baWKTbrih39khq?UnCz$P9X9R$2aqVWXsajLMK`_#7syT2U8~P_HY3jPI=#CDu-;A7IK}TCiZ@(`QU4ObupJt?(azZgVP5sMv{GJLrg7T zxSDSuHXs1_SR8}KpjZ<}@qmTECyF&ji`aQPnr_>!8S$=CG#7?XzWcX`tleUX2n5(W za#~a}ZQ@U4wM9bHa^d{-dG-BP@~Cor`mI_^BFgSCQ+HH7PGzsA5FMWOy-{zwu4r!X zHEEjjWI>@e?mbU~rugx&V7CJFJskF^Z*fp5+4{$7&n0G3xY{-T8FTiQPe;v;I)nCG zszQd8S)KBPb3|^TQo*SgsYjB#*{aLtW<@4fy?9&4XI4wV?0J}f5~_M3EN>!Yw`C*nWW|cSX@6q%Ld@#tynx__ z*y&0hL#pcsUb;_BgYqQBP4sFu*35LEo6qk#{-uh9F#dstrSXR8MPa6W`5#6NE-8V3 TbVxP^)z0WRV9e@BRsR14Jt){6 diff --git a/src/main/example/SSLClientExample.java b/src/main/example/SSLClientExample.java index 705bf9d10..b82a7e3fd 100644 --- a/src/main/example/SSLClientExample.java +++ b/src/main/example/SSLClientExample.java @@ -83,7 +83,7 @@ public static void main( String[] args ) throws Exception { // load up the key store String STORETYPE = "JKS"; - String KEYSTORE = "keystore.jks"; + String KEYSTORE = String.format("src%1$stest%1$1sjava%1$1sorg%1$1sjava_websocket%1$1skeystore.jks", File.separator); String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; diff --git a/src/main/example/SSLServerCustomWebsocketFactoryExample.java b/src/main/example/SSLServerCustomWebsocketFactoryExample.java index 8f5aecd47..1b62189ba 100644 --- a/src/main/example/SSLServerCustomWebsocketFactoryExample.java +++ b/src/main/example/SSLServerCustomWebsocketFactoryExample.java @@ -52,7 +52,7 @@ public static void main(String[] args) throws Exception { // load up the key store String STORETYPE = "JKS"; - String KEYSTORE = "keystore.jks"; + String KEYSTORE = String.format("src%1$stest%1$1sjava%1$1sorg%1$1sjava_websocket%1$1skeystore.jks", File.separator); String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; diff --git a/src/main/example/SSLServerExample.java b/src/main/example/SSLServerExample.java index 9d8d8565c..0062fb057 100644 --- a/src/main/example/SSLServerExample.java +++ b/src/main/example/SSLServerExample.java @@ -48,7 +48,7 @@ public static void main( String[] args ) throws Exception { // load up the key store String STORETYPE = "JKS"; - String KEYSTORE = "keystore.jks"; + String KEYSTORE = String.format("src%1$stest%1$1sjava%1$1sorg%1$1sjava_websocket%1$1skeystore.jks", File.separator); String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; diff --git a/src/main/example/TwoWaySSLServerExample.java b/src/main/example/TwoWaySSLServerExample.java index d3e1413c1..e8a548418 100644 --- a/src/main/example/TwoWaySSLServerExample.java +++ b/src/main/example/TwoWaySSLServerExample.java @@ -51,7 +51,7 @@ public static void main( String[] args ) throws Exception { // load up the key store String STORETYPE = "JKS"; - String KEYSTORE = "keystore.jks"; + String KEYSTORE = String.format("src%1$stest%1$1sjava%1$1sorg%1$1sjava_websocket%1$1skeystore.jks", File.separator); String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; diff --git a/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java b/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java index 6122fc8ab..9d92c100d 100644 --- a/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java @@ -102,7 +102,7 @@ public static void main( String[] args ) throws UnknownHostException { try { // load up the key store String STORETYPE = "JKS"; - String KEYSTORE = "keystore.jks"; + String KEYSTORE = String.format("src%1$stest%1$1sjava%1$1sorg%1$1sjava_websocket%1$1skeystore.jks", File.separator); String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; diff --git a/src/test/java/org/java_websocket/keystore.jks b/src/test/java/org/java_websocket/keystore.jks index 743add50e6fe50f8e00c182085024bab565743b2..2ff34420d7e2f3213c0f21ad5106bf01ca02cd98 100644 GIT binary patch delta 2049 zcmZvdc{J3I0>x)D_B~6omwlTh%1&h|Q5bu&OJtoesJ_NeBKj$5vhUN3NG1|eIW<`u z%VR_}Gqy?1L^2Jbc+T&i_s%=-kNd~H=iGnpAD=rcohJqCEblCXKp@DT!2d}2QhZp* zrKou9<-H_PLH^3=>sywr@ z=x?JMS)haram2i^l*fb}Q8i%|pZ$KZLpj5gXcD{WcCItb8s%=A%Tpz|R~a{7oO?8-(xN1^qp(_-3H(yH~wHyMwF!Km?n(U}r9_IKo56HA2N zxxXaY0uMCkgd=Z0s29_ zFJ(HO z{l*>c9JCF30Et2^fkN*G=jYXTd$U~Egdbn?z^h7chR!Nx&qV&-IDy?XeWsKeZM-=O z7hVy8jd6TQC{BH!43CPNRhP?EIub`?e|&^JLYr3n3zf&!r^En;ZiKQJtuV?rbQ8hj z&Lykx$kq%Q!OnS+)R|^BW}Tb&D$51 z>pkB0J2lWyJP3uw0QUnf`2F%&@gNJXK&||{44X8qM&zsCU-ZYnYQ4otl{@H zbagWUH4bw+|bM8sN18ZJELm)tcAYv;Zt2TC6H^%{{~aYCi{LCMGW ze_2-3V#HGUDy{Jux~3aVbzX{upIbN^%6t$xpV4O*VhbW~J!uva)VB|z0~xKkTn(SB zx$}w}XR&sb2Sg@V<`!%Tg+ggzA_OuH2<1!is!M%&*JSEn@#y1x+IkG3EJqmT#$8g&$DhD0Jw{T0N~|84(&?XEvu19+CYY&{i?wv@;wYL*oY-tsQC-Ym(N z>#;9Kb)8FULWArcUyGeEZ|w}_@WkXSf|m~YQcY5fqLmfCP9AfKX*y`zbr~o6bgPBU zb!Q+BbZfBlli>;B!VL>2t}6MT8c!Hy1?Y z08_)F=`?GD=h3QZ&dUUDC20q`I2vvx{Mf=)SNjxk%Z5a|Yx@iDn$diEM{KFjwYvf_ z=zDC{(*66$yzwydB}E~A;qpy9huFPrSo)<}x3owjomJPV9r5IKs2@W+X7`w3m9k~d zOV>+tCUOk*W2duK1pM@$i*z|mr#{xQ&g<+nk8Tb@(YKKyK=K0vz|Q{fAgvj@2R`B#raaDfb6! zR>W}+a}0+S19T>2bU)N87k^3|U}mM9`PO@RTq}jAg2sTAQq6U+77yCq{_Fx|MDmj9 zCXM38GK3UwAMb7Y1bR03N>#sL(kH#bc6qHo5;PfWDVY@(==1)F^@ciu)V6-j*oL1u zt^C{x$7GXUf@Rg##SrBJPnOqV-Przg9A2~AoHyI9Yb#cm&kt-Ec8`3r%Tl^Vn`6z^ bSN?zqQYbA-w$t__7njH{vr)3NGgAKs8^gNw literal 2251 zcmc&#_fr#y5>7%ANa&zIATd%^YC;K3kRsB9R4IZW<`~JyE{AI?(F_t`?&@H06;7U{_X5ugx@^E z{7EeAqH;Mn699k!FfrgG3=b482L*zGvLJpS5CQu|>lMdZZ4Q-QTUKZSkYw$? zMhlIp<#S^$aw%#k?oOW3TvBLh>NmuzM1x_YOXFjxij_r5{np@3eKpuSn7TT1+upaZCGT|jzX_htTF19C(MM`-S0n+AT20&jL2`mb?)vtmC18jWjK7Pb%j!Y z%Jha!+(57)YCfj4(Li{nbY)2HG~m%?<~P>>r#ibyyD`8_teman9=Il2y> z&_YZ6o_&%C1UL;9MNjEQSB&SE(~=_3)gHWc&_&ret;)>zIQfv|y`L(s8hEVZN`8;b zs}(Ix4c<%{)gi({3obJwIsW_#n~R%`It*$|$9XSVZ+-?0NGt;nS7!QV%%ST z{YjUl`0(?<2@msou^uhWt=xkIF8I8gUg9;y9e2;1pfjd`T)l<6(LSOQAN}e@dm`Q# zU@S~Mv-#YT*T-(pg))F2Mh#vTr)VclaeQ!*)!Nq%O$F7q>`p)EMym(HZ5<1!BSYy5 zI{7L@{|I-imza;J=ySC$k?S9Yi(HMS3QK!zI!x~4BGx}x>DLJ!it|HaJA6%EHF(Ym z=;!ft#A$lTg_e%B6i)4P%kV^hq^swb)Zadzjk=prrlS2#qqkblEsPdKE`xW=RlKz; zl$8^Q4?02K=fu+PTvOCMmqIdM-DA`U^d^_7(c^N^hlRX9lJ+Q**1Jbmf6;D^x!VqI zH7wuT@r{&8dO?3<7cZAqXV^l?cknZwYTC|>ax7skMk$?tSd4Bo_B)%s{<0tpmzkin zJ|T4iu+{fh{ESU^8x`#%4Ii<>GCTCV=;5I3F}szCR)ddrpX>MYenlhhUaG=M?T z@601y8*=98h{20eq^Qy}v8^aK={)Rw`nWO_DJwRcs4AqHUo(9{{F6Yv ze3xn5X5|W{2XkyFKxABX9;jdQ?#ET9X^jHC=9<_nFOr>y7b~6YkkXz0$8|uJG0= z7HcYvBp{PGs|8OPYEs2rs2c<&2UZq3UKGBHx~xHD{lA z#3(>baWKTbrih39khq?UnCz$P9X9R$2aqVWXsajLMK`_#7syT2U8~P_HY3jPI=#CDu-;A7IK}TCiZ@(`QU4ObupJt?(azZgVP5sMv{GJLrg7T zxSDSuHXs1_SR8}KpjZ<}@qmTECyF&ji`aQPnr_>!8S$=CG#7?XzWcX`tleUX2n5(W za#~a}ZQ@U4wM9bHa^d{-dG-BP@~Cor`mI_^BFgSCQ+HH7PGzsA5FMWOy-{zwu4r!X zHEEjjWI>@e?mbU~rugx&V7CJFJskF^Z*fp5+4{$7&n0G3xY{-T8FTiQPe;v;I)nCG zszQd8S)KBPb3|^TQo*SgsYjB#*{aLtW<@4fy?9&4XI4wV?0J}f5~_M3EN>!Yw`C*nWW|cSX@6q%Ld@#tynx__ z*y&0hL#pcsUb;_BgYqQBP4sFu*35LEo6qk#{-uh9F#dstrSXR8MPa6W`5#6NE-8V3 TbVxP^)z0WRV9e@BRsR14Jt){6 From 455d09e8ff5d4f5ed6e2fcfb5e5af23d396a464e Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 29 Mar 2020 20:00:39 +0200 Subject: [PATCH 032/165] Add timeout for test --- src/test/java/org/java_websocket/issues/Issue962Test.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/java_websocket/issues/Issue962Test.java b/src/test/java/org/java_websocket/issues/Issue962Test.java index f5927b81f..1cc9b2984 100644 --- a/src/test/java/org/java_websocket/issues/Issue962Test.java +++ b/src/test/java/org/java_websocket/issues/Issue962Test.java @@ -85,7 +85,7 @@ public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throw } - @Test + @Test(timeout = 2000) public void testIssue() throws IOException, URISyntaxException, InterruptedException { int port = SocketUtil.getAvailablePort(); WebSocketClient client = new WebSocketClient(new URI("ws://127.0.0.1:" + port)) { @@ -103,7 +103,7 @@ public void onClose(int code, String reason, boolean remote) { @Override public void onError(Exception ex) { - Assert.fail(ex.toString() + " sould not occur"); + Assert.fail(ex.toString() + " should not occur"); } }; From 2dbe2d3c4a3ba63a0132a256ccefbfceb69531c9 Mon Sep 17 00:00:00 2001 From: marci4 Date: Mon, 13 Apr 2020 17:39:26 +0200 Subject: [PATCH 033/165] API for SSLParameters Enabled hostname validation by default --- .../client/WebSocketClient.java | 18 +- .../java_websocket/issues/Issue997Test.java | 174 ++++++++++++++++++ .../keystore_localhost_only.jks | Bin 0 -> 2036 bytes .../java_websocket/util/SSLContextUtil.java | 23 ++- 4 files changed, 212 insertions(+), 3 deletions(-) create mode 100644 src/test/java/org/java_websocket/issues/Issue997Test.java create mode 100644 src/test/java/org/java_websocket/keystore_localhost_only.jks diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 05b83976a..651a57600 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -449,7 +449,6 @@ public void run() { } else if( socket == null ) { socket = new Socket( proxy ); isNewSocket = true; - } else if( socket.isClosed() ) { throw new IOException(); } @@ -464,13 +463,19 @@ public void run() { // if the socket is set by others we don't apply any TLS wrapper if (isNewSocket && "wss".equals( uri.getScheme())) { - SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, null); SSLSocketFactory factory = sslContext.getSocketFactory(); socket = factory.createSocket(socket, uri.getHost(), getPort(), true); } + if (socket instanceof SSLSocket) { + SSLSocket sslSocket = (SSLSocket)socket; + SSLParameters sslParameters = sslSocket.getSSLParameters(); + onSetSSLParameters(sslParameters); + sslSocket.setSSLParameters(sslParameters); + } + istream = socket.getInputStream(); ostream = socket.getOutputStream(); @@ -511,6 +516,15 @@ public void run() { connectReadThread = null; } + /** + * Apply specific + * @param sslParameters the SSLParameters which will be used for the SSLSocket + */ + protected void onSetSSLParameters(SSLParameters sslParameters) { + // Make sure we perform hostname validation + sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); + } + /** * Extract the specified port * @return the specified port or the default port for the specific scheme diff --git a/src/test/java/org/java_websocket/issues/Issue997Test.java b/src/test/java/org/java_websocket/issues/Issue997Test.java new file mode 100644 index 000000000..431529699 --- /dev/null +++ b/src/test/java/org/java_websocket/issues/Issue997Test.java @@ -0,0 +1,174 @@ +package org.java_websocket.issues; + +/* + * Copyright (c) 2010-2020 Nathan Rajlich + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + + +import org.java_websocket.WebSocket; +import org.java_websocket.client.WebSocketClient; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.handshake.ServerHandshake; +import org.java_websocket.server.DefaultSSLWebSocketServerFactory; +import org.java_websocket.server.WebSocketServer; +import org.java_websocket.util.SSLContextUtil; +import org.java_websocket.util.SocketUtil; +import org.junit.Test; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLParameters; +import java.io.IOException; +import java.net.*; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.*; + +public class Issue997Test { + + @Test(timeout=2000) + public void test_localServer_ServerLocalhost_Client127_CheckActive() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), "HTTPS"); + assertFalse(client.onOpen); + assertTrue(client.onSSLError); + } + @Test(timeout=2000) + public void test_localServer_ServerLocalhost_Client127_CheckInactive() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), ""); + assertTrue(client.onOpen); + assertFalse(client.onSSLError); + } + + @Test(timeout=2000) + public void test_localServer_ServerLocalhost_ClientLocalhost_CheckActive() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), "HTTPS"); + assertTrue(client.onOpen); + assertFalse(client.onSSLError); + } + @Test(timeout=2000) + public void test_localServer_ServerLocalhost_ClientLocalhost_CheckInactive() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), ""); + assertTrue(client.onOpen); + assertFalse(client.onSSLError); + } + + + public SSLWebSocketClient testIssueWithLocalServer(String address, int port, SSLContext serverContext, SSLContext clientContext, String endpointIdentificationAlgorithm) throws IOException, URISyntaxException, InterruptedException { + CountDownLatch countServerDownLatch = new CountDownLatch(1); + SSLWebSocketClient client = new SSLWebSocketClient(address, port, endpointIdentificationAlgorithm); + WebSocketServer server = new SSLWebSocketServer(port, countServerDownLatch); + + server.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(serverContext)); + if (clientContext != null) { + client.setSocketFactory(clientContext.getSocketFactory()); + } + server.start(); + countServerDownLatch.await(); + client.connectBlocking(1, TimeUnit.SECONDS); + return client; + } + + + private static class SSLWebSocketClient extends WebSocketClient { + private final String endpointIdentificationAlgorithm; + public boolean onSSLError = false; + public boolean onOpen = false; + + public SSLWebSocketClient(String address, int port, String endpointIdentificationAlgorithm) throws URISyntaxException { + super(new URI("wss://"+ address + ':' +port)); + this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm; + } + + @Override + public void onOpen(ServerHandshake handshakedata) { + this.onOpen = true; + } + + @Override + public void onMessage(String message) { + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + if (ex instanceof SSLHandshakeException) { + this.onSSLError = true; + } + } + + @Override + protected void onSetSSLParameters(SSLParameters sslParameters) { + if (endpointIdentificationAlgorithm == null) { + super.onSetSSLParameters(sslParameters); + } else { + sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm); + } + } + + }; + + + private static class SSLWebSocketServer extends WebSocketServer { + private final CountDownLatch countServerDownLatch; + + + public SSLWebSocketServer(int port, CountDownLatch countServerDownLatch) { + super(new InetSocketAddress(port)); + this.countServerDownLatch = countServerDownLatch; + } + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + ex.printStackTrace(); + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + } +} diff --git a/src/test/java/org/java_websocket/keystore_localhost_only.jks b/src/test/java/org/java_websocket/keystore_localhost_only.jks new file mode 100644 index 0000000000000000000000000000000000000000..c18383b0b852a478610245c77297b62b69d737fa GIT binary patch literal 2036 zcmZ{kX*ARg8^-59V`m;@nMQU(5;Mr)HQ7z+K@lR$$l6Gn$53P)9$Sh?iLsMyo*J^u z$d;YZR1(w3PT6DZ+v_}E-oCsat`FCJ&V8TzT-Q0j!==L|5C{Z57VxjQZ~MEu-S+Vh zARJHd$cSrwAP_qkL1a5b{K3IknXHHlx`w{?@jQ%`Wk zR9UaYOj?KS5I$_^@d#`|Vwjh%|6Fv~mFcq})w8M@_QuqV>vJ(;K>|M&o}%}wOPG@M z*=gOs!dc7u5t*jJIi{A+^tg&|LK$c7pln?(nj~r4ALAqmA>@^E8i2M zl)}={TCtSNvNk732S-PAR_SHjp5RvO|4#Ai-67c?x%hpiIcZDTuVnPTDEK?i{v+NK z6MnCSTz{n;ZM2son2J-OyBJiaU-EFJGkKSjzn{St_g!dKJNb2Up?wGKX1oU7bncd9ii#pt}RF;=WyJ&isRR3l$N|+#fv?fCl!Z0^H3{Q zSnfL zhsr3c>Z8rMWwYpPmvZEnyd$`pC-v%T*9ZI}NClxfx9w8N!#MHL;9%sOlj4Bru;qTq z9@_v|**%?c5inB=DOnSBbXGbIgkTh>bAo=E@1j3Xr^FG5v=Q@`MXFeV{GE6l-#0TV z#4&{$L(e=|6TO=)L0vBTX@V=&QCZA)$GAoC?gnSf-raWZb=SYNp9t)5#B6BS8|_@FCl@4#!=C(RI4 zZ&iNWVl>Ln&^Z4yLwxOhS6AGf(pemq)AndDD+?8C=xY}YoAn{6m#-E}Xra8_O3KcB zw36PM3k=65Wmw8fMw3sm;C|Jhnljsx{*3~Ca{|ck(wfLoMLj3SdUI9vDG^5^=VNl6 z&gvQ~UObJ$q~m--{@O&N_QsSqN_j*Xx6pcF8)W?Dhq4fj+XJC<%Z z!19SvW)MueZrtT`J4|)Z+G$+Go`6G(-9movG_!d#<(Eh`8`D#1bu?}~coI;PJA+=IEj?RV zpyuT}S^8ccjCxrY3Qd!wGJ73F_Zzc#D|#6!?ne2C^TM%+YZ+-Rn7}K5wo|5s|C~Xv zD%@~I-e6$2CtjTa(}Ge~f-kt!4`_6Q$1k}+!p+Xl911Rr2%etES#oOCSDmW7UVhcJ z@QHbDaD}yfwOJ2VFCo60W+77(?i-0u4mXz&nmdmv7ULUk*r4J%7kH^iA>8b9Qr_2Q zGHXEd%DFGkgms6$ZqoLLHRI0eUoIbP7l$RbM&>UaWjCfiFy|E?la^}GMp8x%!u$k% zj=ZMdhsNA5)1`%>GM!6YG#`zT{K*z}X*HVi*-GI~`(J*j{P-7+?AKM#BXo{&S&ATn zix5O0DGve$z+g6)XhI|c%E7H1dogwk3IM$9AcQdT1VVrVV#@~M`yW&hk}#+`0->RS zL~3d3AT%9eP>tX1|Jfn}vcI1{rZ0pD@Pm#&-~kf>0JK-cwfv6@M@e8><)Rc0O3jA$H^e2LJFrGy074&D;%S{GEM&)`iz-L?AmvL0gKPo zK&dXp(kG2wUdLc_7*KQ0%fZiP`#4vL{g_p{Hs<^(Fi3Le{T4~hRC}|*u?B% zOP}jJwCOY3^>|G1k`CUEzqNDzAM(N_;~QPIpGfVxv@Zl?7Mhf*~4eE!7@6dpvvS&=#u3wCa0Oi~ANM_@??>GF{0}u}andCvJ z%$9@F!RKv9iFiE>4!kFZzvadVv*w!Z$vrb67d+Z*x}5LNo@e5s|LXgkJW%~9F6rhw zcGaZRWRwJHA|N3M8T4}LPAXvDCCyuTA!;Mt8rr`r+cFC8`Z_j}EY9Z3D9G;4nGo8$ z((9FcCp}5j&S*RK#)ic{OsUa^yr2`BJ^#4`k0L Date: Tue, 21 Apr 2020 22:34:52 +0200 Subject: [PATCH 034/165] Rework after review --- src/main/example/SSLClientExample.java | 3 ++- ...SSLServerCustomWebsocketFactoryExample.java | 3 ++- src/main/example/SSLServerExample.java | 3 ++- src/main/example/TwoWaySSLServerExample.java | 3 ++- .../java_websocket/client/WebSocketClient.java | 7 ++++--- .../example/AutobahnSSLServerTest.java | 3 ++- .../java_websocket/issues/Issue997Test.java | 18 +++++++++++++++--- .../java_websocket/util/SSLContextUtil.java | 5 +++-- 8 files changed, 32 insertions(+), 13 deletions(-) diff --git a/src/main/example/SSLClientExample.java b/src/main/example/SSLClientExample.java index b82a7e3fd..d85fb85a7 100644 --- a/src/main/example/SSLClientExample.java +++ b/src/main/example/SSLClientExample.java @@ -28,6 +28,7 @@ import java.io.FileInputStream; import java.io.InputStreamReader; import java.net.URI; +import java.nio.file.Paths; import java.security.KeyStore; import javax.net.ssl.KeyManagerFactory; @@ -83,7 +84,7 @@ public static void main( String[] args ) throws Exception { // load up the key store String STORETYPE = "JKS"; - String KEYSTORE = String.format("src%1$stest%1$1sjava%1$1sorg%1$1sjava_websocket%1$1skeystore.jks", File.separator); + String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks").toString(); String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; diff --git a/src/main/example/SSLServerCustomWebsocketFactoryExample.java b/src/main/example/SSLServerCustomWebsocketFactoryExample.java index 1b62189ba..3d834e027 100644 --- a/src/main/example/SSLServerCustomWebsocketFactoryExample.java +++ b/src/main/example/SSLServerCustomWebsocketFactoryExample.java @@ -32,6 +32,7 @@ import javax.net.ssl.TrustManagerFactory; import java.io.File; import java.io.FileInputStream; +import java.nio.file.Paths; import java.security.KeyStore; import java.util.ArrayList; import java.util.Arrays; @@ -52,7 +53,7 @@ public static void main(String[] args) throws Exception { // load up the key store String STORETYPE = "JKS"; - String KEYSTORE = String.format("src%1$stest%1$1sjava%1$1sorg%1$1sjava_websocket%1$1skeystore.jks", File.separator); + String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks").toString(); String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; diff --git a/src/main/example/SSLServerExample.java b/src/main/example/SSLServerExample.java index 0062fb057..a72f56b99 100644 --- a/src/main/example/SSLServerExample.java +++ b/src/main/example/SSLServerExample.java @@ -27,6 +27,7 @@ import java.io.File; import java.io.FileInputStream; +import java.nio.file.Paths; import java.security.KeyStore; import javax.net.ssl.KeyManagerFactory; @@ -48,7 +49,7 @@ public static void main( String[] args ) throws Exception { // load up the key store String STORETYPE = "JKS"; - String KEYSTORE = String.format("src%1$stest%1$1sjava%1$1sorg%1$1sjava_websocket%1$1skeystore.jks", File.separator); + String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks").toString(); String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; diff --git a/src/main/example/TwoWaySSLServerExample.java b/src/main/example/TwoWaySSLServerExample.java index e8a548418..694e43cda 100644 --- a/src/main/example/TwoWaySSLServerExample.java +++ b/src/main/example/TwoWaySSLServerExample.java @@ -33,6 +33,7 @@ import javax.net.ssl.TrustManagerFactory; import java.io.File; import java.io.FileInputStream; +import java.nio.file.Paths; import java.security.KeyStore; /** @@ -51,7 +52,7 @@ public static void main( String[] args ) throws Exception { // load up the key store String STORETYPE = "JKS"; - String KEYSTORE = String.format("src%1$stest%1$1sjava%1$1sorg%1$1sjava_websocket%1$1skeystore.jks", File.separator); + String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks").toString(); String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 651a57600..0bbcfe544 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -472,6 +472,8 @@ public void run() { if (socket instanceof SSLSocket) { SSLSocket sslSocket = (SSLSocket)socket; SSLParameters sslParameters = sslSocket.getSSLParameters(); + // Make sure we perform hostname validation + sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); onSetSSLParameters(sslParameters); sslSocket.setSSLParameters(sslParameters); } @@ -517,12 +519,11 @@ public void run() { } /** - * Apply specific + * Apply specific SSLParameters + * * @param sslParameters the SSLParameters which will be used for the SSLSocket */ protected void onSetSSLParameters(SSLParameters sslParameters) { - // Make sure we perform hostname validation - sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); } /** diff --git a/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java b/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java index 9d92c100d..290b3f8d3 100644 --- a/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java @@ -43,6 +43,7 @@ import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; +import java.nio.file.Paths; import java.security.KeyStore; import java.security.spec.ECField; import java.util.Collections; @@ -102,7 +103,7 @@ public static void main( String[] args ) throws UnknownHostException { try { // load up the key store String STORETYPE = "JKS"; - String KEYSTORE = String.format("src%1$stest%1$1sjava%1$1sorg%1$1sjava_websocket%1$1skeystore.jks", File.separator); + String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks").toString(); String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; diff --git a/src/test/java/org/java_websocket/issues/Issue997Test.java b/src/test/java/org/java_websocket/issues/Issue997Test.java index 431529699..0fc81bc28 100644 --- a/src/test/java/org/java_websocket/issues/Issue997Test.java +++ b/src/test/java/org/java_websocket/issues/Issue997Test.java @@ -67,6 +67,13 @@ public void test_localServer_ServerLocalhost_Client127_CheckInactive() throws Ce assertFalse(client.onSSLError); } + @Test(timeout=2000) + public void test_localServer_ServerLocalhost_Client127_CheckDefault() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), null); + assertFalse(client.onOpen); + assertTrue(client.onSSLError); + } + @Test(timeout=2000) public void test_localServer_ServerLocalhost_ClientLocalhost_CheckActive() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), "HTTPS"); @@ -80,6 +87,13 @@ public void test_localServer_ServerLocalhost_ClientLocalhost_CheckInactive() thr assertFalse(client.onSSLError); } + @Test(timeout=2000) + public void test_localServer_ServerLocalhost_ClientLocalhost_CheckDefault() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), null); + assertTrue(client.onOpen); + assertFalse(client.onSSLError); + } + public SSLWebSocketClient testIssueWithLocalServer(String address, int port, SSLContext serverContext, SSLContext clientContext, String endpointIdentificationAlgorithm) throws IOException, URISyntaxException, InterruptedException { CountDownLatch countServerDownLatch = new CountDownLatch(1); @@ -129,9 +143,7 @@ public void onError(Exception ex) { @Override protected void onSetSSLParameters(SSLParameters sslParameters) { - if (endpointIdentificationAlgorithm == null) { - super.onSetSSLParameters(sslParameters); - } else { + if (endpointIdentificationAlgorithm != null) { sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm); } } diff --git a/src/test/java/org/java_websocket/util/SSLContextUtil.java b/src/test/java/org/java_websocket/util/SSLContextUtil.java index 26c929c25..49caf0cba 100644 --- a/src/test/java/org/java_websocket/util/SSLContextUtil.java +++ b/src/test/java/org/java_websocket/util/SSLContextUtil.java @@ -32,6 +32,7 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; +import java.nio.file.Paths; import java.security.*; import java.security.cert.CertificateException; @@ -40,7 +41,7 @@ public class SSLContextUtil { public static SSLContext getContext() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException { // load up the key store String STORETYPE = "JKS"; - String KEYSTORE = String.format("src%1$stest%1$1sjava%1$1sorg%1$1sjava_websocket%1$1skeystore.jks", File.separator); + String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks").toString(); String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; @@ -62,7 +63,7 @@ public static SSLContext getContext() throws NoSuchAlgorithmException, KeyManage public static SSLContext getLocalhostOnlyContext() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException { // load up the key store String STORETYPE = "JKS"; - String KEYSTORE = String.format("src%1$stest%1$1sjava%1$1sorg%1$1sjava_websocket%1$1skeystore_localhost_only.jks", File.separator); + String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore_localhost_only.jks").toString(); String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; From 3ebbe21da698905c32ad58f03d70dfe93764e25d Mon Sep 17 00:00:00 2001 From: PhilipRoman Date: Wed, 22 Apr 2020 11:18:43 +0300 Subject: [PATCH 035/165] Allow user to specify max number of pending connections to a server Adds a field and two new methods to WebSocketServer: setMaxPendingConnections(int) and getMaxPendingConnections() and uses the value as a parameter when binding the server socket. --- .../server/WebSocketServer.java | 30 ++++++++++++++++--- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 32f3fdba0..961eda283 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -26,9 +26,7 @@ package org.java_websocket.server; import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.net.Socket; +import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedByInterruptException; @@ -108,6 +106,12 @@ public abstract class WebSocketServer extends AbstractWebSocket implements Runna private WebSocketServerFactory wsf = new DefaultWebSocketServerFactory(); + /** + * Attribute which allows you to configure the socket "backlog" parameter + * which determines how many client connections can be queued. + */ + private int maxPendingConnections = -1; + /** * Creates a WebSocketServer that will attempt to * listen on port WebSocketImpl.DEFAULT_PORT. @@ -308,6 +312,24 @@ public List getDraft() { return Collections.unmodifiableList( drafts ); } + /** + * Set the requested maximum number of pending connections on the socket. The exact semantics are implementation + * specific. The value provided should be greater than 0. If it is less than or equal to 0, then + * an implementation specific default will be used. This option will be passed as "backlog" parameter to {@link ServerSocket#bind(SocketAddress, int)} + */ + public void setMaxPendingConnections(int numberOfConnections) { + maxPendingConnections = numberOfConnections; + } + + /** + * Returns the currently configured maximum number of pending connections. + * + * @see #setMaxPendingConnections(int) + */ + public int getMaxPendingConnections() { + return maxPendingConnections; + } + // Runnable IMPLEMENTATION ///////////////////////////////////////////////// public void run() { if (!doEnsureSingleThread()) { @@ -505,7 +527,7 @@ private boolean doSetupSelectorAndServerThread() { ServerSocket socket = server.socket(); socket.setReceiveBufferSize( WebSocketImpl.RCVBUF ); socket.setReuseAddress( isReuseAddr() ); - socket.bind( address ); + socket.bind( address, getMaxPendingConnections() ); selector = Selector.open(); server.register( selector, server.validOps() ); startConnectionLostTimer(); From ca38a4b13bc424b9430f3ad812c7c9d57eb6b0a9 Mon Sep 17 00:00:00 2001 From: Philip John Roman <33231208+PhilipRoman@users.noreply.github.com> Date: Wed, 22 Apr 2020 14:48:55 +0300 Subject: [PATCH 036/165] Add "since 1.5.0" tag to new methods --- src/main/java/org/java_websocket/server/WebSocketServer.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 961eda283..f7349a6d7 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -109,6 +109,7 @@ public abstract class WebSocketServer extends AbstractWebSocket implements Runna /** * Attribute which allows you to configure the socket "backlog" parameter * which determines how many client connections can be queued. + * @since 1.5.0 */ private int maxPendingConnections = -1; @@ -316,6 +317,7 @@ public List getDraft() { * Set the requested maximum number of pending connections on the socket. The exact semantics are implementation * specific. The value provided should be greater than 0. If it is less than or equal to 0, then * an implementation specific default will be used. This option will be passed as "backlog" parameter to {@link ServerSocket#bind(SocketAddress, int)} + * @since 1.5.0 */ public void setMaxPendingConnections(int numberOfConnections) { maxPendingConnections = numberOfConnections; @@ -325,6 +327,7 @@ public void setMaxPendingConnections(int numberOfConnections) { * Returns the currently configured maximum number of pending connections. * * @see #setMaxPendingConnections(int) + * @since 1.5.0 */ public int getMaxPendingConnections() { return maxPendingConnections; From 1e2e89048f18f7143518de9c828ff7e95abf9876 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 26 Apr 2020 19:35:02 +0200 Subject: [PATCH 037/165] Update PerMessageDeflateExtensionTest.java Fix small test error --- .../extensions/PerMessageDeflateExtensionTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index d83072790..f1f665b60 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -108,7 +108,7 @@ public void testGetProvidedExtensionAsClient() { @Test public void testGetProvidedExtensionAsServer() { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertEquals( "permessage-deflate; server_no_context_takeover; client_no_context_takeover", + assertEquals( "permessage-deflate; server_no_context_takeover", deflateExtension.getProvidedExtensionAsServer() ); } From 046f24b2554cf2ab8c22a8e53fd3a4524e856ad5 Mon Sep 17 00:00:00 2001 From: marci4 Date: Thu, 7 May 2020 07:26:37 +0200 Subject: [PATCH 038/165] Update CHANGELOG.md --- CHANGELOG.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 08df0c50f..b65433bdd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,29 @@ # Change log +## Version Release 1.5.0 (2020/05/06) + +#### Breaking Changes + +This release requires API Level 1.7. + +#### Security + +This release contains a security fix for [CVE-2020-11050](https://nvd.nist.gov/vuln/detail/CVE-2020-11050). + +Take a look at the advisory [here](https://github.com/TooTallNate/Java-WebSocket/security/advisories/GHSA-gw55-jm4h-x339) for more information. + +#### New Features + +* [Issue 574](https://github.com/TooTallNate/Java-WebSocket/issues/574) - Implementation of per message deflate extension ([PR 866](https://github.com/TooTallNate/Java-WebSocket/pull/866)) +* [PR 866](https://github.com/TooTallNate/Java-WebSocket/pull/866) - Add PerMessageDeflate Extension support, see #574 +* [Issue 997](https://github.com/TooTallNate/Java-WebSocket/issues/997) - Access to SSLParameters used by the WebSocketClient ([PR 1000](https://github.com/TooTallNate/Java-WebSocket/pull/1000)) +* [Issue 574](https://github.com/TooTallNate/Java-WebSocket/issues/574) - Implementation of per message deflate extension ([PR 866](https://github.com/TooTallNate/Java-WebSocket/pull/866)) +* [PR 1001](https://github.com/TooTallNate/Java-WebSocket/pull/1001) - Allow user to specify max number of pending connections to a server +* [PR 1000](https://github.com/TooTallNate/Java-WebSocket/pull/1000) - SSLParameters for WebSocketClient +* [PR 866](https://github.com/TooTallNate/Java-WebSocket/pull/866) - Add PerMessageDeflate Extension support, see #574 + +In this release 3 issues and 4 pull requests were closed. + +############################################################################### ## Version Release 1.4.1 (2020/03/12) From fb6d234870e9d5aa5d0ca7b374575e61643b741f Mon Sep 17 00:00:00 2001 From: marci4 Date: Thu, 7 May 2020 07:34:59 +0200 Subject: [PATCH 039/165] Release of 1.5.0 --- README.markdown | 4 ++-- pom.xml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.markdown b/README.markdown index 8501dcb08..488414685 100644 --- a/README.markdown +++ b/README.markdown @@ -29,7 +29,7 @@ To use maven add this dependency to your pom.xml: org.java-websocket Java-WebSocket - 1.4.1 + 1.5.0 ``` @@ -40,7 +40,7 @@ mavenCentral() ``` Then you can just add the latest version to your build. ```xml -compile "org.java-websocket:Java-WebSocket:1.4.1" +compile "org.java-websocket:Java-WebSocket:1.5.0" ``` #### Logging diff --git a/pom.xml b/pom.xml index 8f809397a..46e8aa439 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.java-websocket Java-WebSocket jar - 1.5.0-SNAPSHOT + 1.5.1-SNAPSHOT Java-WebSocket A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket From e6f6bcb14964520c23af291fa7c90a430b650693 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 10 May 2020 17:06:48 +0200 Subject: [PATCH 040/165] Move setEndpointIdentificationAlgorithm inside onSetSSLParametersof #Fixes 1011 --- .../java/org/java_websocket/client/WebSocketClient.java | 6 ++++-- src/test/java/org/java_websocket/issues/Issue997Test.java | 2 ++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 0bbcfe544..303b6a9a6 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -472,8 +472,6 @@ public void run() { if (socket instanceof SSLSocket) { SSLSocket sslSocket = (SSLSocket)socket; SSLParameters sslParameters = sslSocket.getSSLParameters(); - // Make sure we perform hostname validation - sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); onSetSSLParameters(sslParameters); sslSocket.setSSLParameters(sslParameters); } @@ -520,10 +518,14 @@ public void run() { /** * Apply specific SSLParameters + * If you override this method make sure to always call super.onSetSSLParameters() to ensure the hostname validation is active * * @param sslParameters the SSLParameters which will be used for the SSLSocket */ protected void onSetSSLParameters(SSLParameters sslParameters) { + // If you run into problem (NoSuchMethodException), check out the wiki https://github.com/TooTallNate/Java-WebSocket/wiki/No-such-method-error-'setEndpointIdentificationAlgorithm' + // Perform hostname validation + sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); } /** diff --git a/src/test/java/org/java_websocket/issues/Issue997Test.java b/src/test/java/org/java_websocket/issues/Issue997Test.java index 0fc81bc28..493dd69b7 100644 --- a/src/test/java/org/java_websocket/issues/Issue997Test.java +++ b/src/test/java/org/java_websocket/issues/Issue997Test.java @@ -143,6 +143,8 @@ public void onError(Exception ex) { @Override protected void onSetSSLParameters(SSLParameters sslParameters) { + // Always call super to ensure hostname validation is active by default + super.onSetSSLParameters(sslParameters); if (endpointIdentificationAlgorithm != null) { sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm); } From 877ad764e5d01166d754e611a4139e816cc04d0d Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 10 May 2020 17:13:59 +0200 Subject: [PATCH 041/165] Update WebSocketClient.java --- src/main/java/org/java_websocket/client/WebSocketClient.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 303b6a9a6..4d735dee6 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -523,7 +523,7 @@ public void run() { * @param sslParameters the SSLParameters which will be used for the SSLSocket */ protected void onSetSSLParameters(SSLParameters sslParameters) { - // If you run into problem (NoSuchMethodException), check out the wiki https://github.com/TooTallNate/Java-WebSocket/wiki/No-such-method-error-'setEndpointIdentificationAlgorithm' + // If you run into problem on Android (NoSuchMethodException), check out the wiki https://github.com/TooTallNate/Java-WebSocket/wiki/No-such-method-error-setEndpointIdentificationAlgorithm // Perform hostname validation sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); } From 8c69e49c7249d0a9734a76bae421803582de9236 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 10 May 2020 22:22:41 +0200 Subject: [PATCH 042/165] Update CHANGELOG.md --- CHANGELOG.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b65433bdd..4b62db7b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,13 @@ # Change log + +## Version Release 1.5.1 (2020/05/10) + +#### Bugs Fixed + +* [Issue 1011](https://github.com/TooTallNate/Java-WebSocket/issues/1011) - Crash on Android due to missing method `setEndpointIdentificationAlgorithm` on 1.5.0. ([PR 1014](https://github.com/TooTallNate/Java-WebSocket/pull/1014)) + +In this release 1 issue and 1 pull request were closed. + ## Version Release 1.5.0 (2020/05/06) #### Breaking Changes From 27d2a25898033b1908b930914330c4ea12a55daa Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 10 May 2020 22:34:22 +0200 Subject: [PATCH 043/165] Release 1.5.1 --- README.markdown | 4 ++-- pom.xml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.markdown b/README.markdown index 488414685..27682b6c5 100644 --- a/README.markdown +++ b/README.markdown @@ -29,7 +29,7 @@ To use maven add this dependency to your pom.xml: org.java-websocket Java-WebSocket - 1.5.0 + 1.5.1 ``` @@ -40,7 +40,7 @@ mavenCentral() ``` Then you can just add the latest version to your build. ```xml -compile "org.java-websocket:Java-WebSocket:1.5.0" +compile "org.java-websocket:Java-WebSocket:1.5.1" ``` #### Logging diff --git a/pom.xml b/pom.xml index 46e8aa439..70999a245 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.java-websocket Java-WebSocket jar - 1.5.1-SNAPSHOT + 1.5.2-SNAPSHOT Java-WebSocket A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket From ada038ed4811c116f94406d979977427c433e328 Mon Sep 17 00:00:00 2001 From: Pawan Gupta Date: Mon, 11 May 2020 22:28:35 +0530 Subject: [PATCH 044/165] Fixes for #1017 --- src/main/java/org/java_websocket/WebSocketImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index 3459438ef..f553a21cf 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -427,7 +427,7 @@ private ByteBuffer generateHttpResponseDueToError( int errorCode ) { default: errorCodeDescription = "500 Internal Server Error"; } - return ByteBuffer.wrap( Charsetfunctions.asciiBytes( "HTTP/1.1 " + errorCodeDescription + "\r\nContent-Type: text/html\nServer: TooTallNate Java-WebSocket\r\nContent-Length: " + ( 48 + errorCodeDescription.length() ) + "\r\n\r\n

" + errorCodeDescription + "

" ) ); + return ByteBuffer.wrap( Charsetfunctions.asciiBytes( "HTTP/1.1 " + errorCodeDescription + "\r\nContent-Type: text/html\r\nServer: TooTallNate Java-WebSocket\r\nContent-Length: " + ( 48 + errorCodeDescription.length() ) + "\r\n\r\n

" + errorCodeDescription + "

" ) ); } public synchronized void close( int code, String message, boolean remote ) { From b56ad28304ec27644a85d7349536e0501bbf5fe7 Mon Sep 17 00:00:00 2001 From: Pawan Gupta Date: Mon, 11 May 2020 22:28:35 +0530 Subject: [PATCH 045/165] Fixes for #1017 --- src/main/java/org/java_websocket/WebSocketImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index 3459438ef..f553a21cf 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -427,7 +427,7 @@ private ByteBuffer generateHttpResponseDueToError( int errorCode ) { default: errorCodeDescription = "500 Internal Server Error"; } - return ByteBuffer.wrap( Charsetfunctions.asciiBytes( "HTTP/1.1 " + errorCodeDescription + "\r\nContent-Type: text/html\nServer: TooTallNate Java-WebSocket\r\nContent-Length: " + ( 48 + errorCodeDescription.length() ) + "\r\n\r\n

" + errorCodeDescription + "

" ) ); + return ByteBuffer.wrap( Charsetfunctions.asciiBytes( "HTTP/1.1 " + errorCodeDescription + "\r\nContent-Type: text/html\r\nServer: TooTallNate Java-WebSocket\r\nContent-Length: " + ( 48 + errorCodeDescription.length() ) + "\r\n\r\n

" + errorCodeDescription + "

" ) ); } public synchronized void close( int code, String message, boolean remote ) { From af28db4ab0ccda5056014e80970f8be7c7edbde2 Mon Sep 17 00:00:00 2001 From: yindex Date: Mon, 18 May 2020 21:30:10 +0800 Subject: [PATCH 046/165] Use appropriate schema in any case #1026 add unit test for schema check --- .../client/WebSocketClient.java | 17 ++-- .../java_websocket/client/AllClientTests.java | 3 +- .../client/SchemaCheckTest.java | 86 +++++++++++++++++++ 3 files changed, 95 insertions(+), 11 deletions(-) create mode 100644 src/test/java/org/java_websocket/client/SchemaCheckTest.java diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 4d735dee6..c60f10da5 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -534,17 +534,14 @@ protected void onSetSSLParameters(SSLParameters sslParameters) { */ private int getPort() { int port = uri.getPort(); - if( port == -1 ) { - String scheme = uri.getScheme(); - if( "wss".equals( scheme ) ) { - return WebSocketImpl.DEFAULT_WSS_PORT; - } else if( "ws".equals( scheme ) ) { - return WebSocketImpl.DEFAULT_PORT; - } else { - throw new IllegalArgumentException( "unknown scheme: " + scheme ); - } + String scheme = uri.getScheme(); + if( "wss".equals( scheme ) ) { + return port == -1 ? WebSocketImpl.DEFAULT_WSS_PORT : port; + } else if( "ws".equals( scheme ) ) { + return port == -1 ? WebSocketImpl.DEFAULT_PORT : port; + } else { + throw new IllegalArgumentException( "unknown scheme: " + scheme ); } - return port; } /** diff --git a/src/test/java/org/java_websocket/client/AllClientTests.java b/src/test/java/org/java_websocket/client/AllClientTests.java index ffc13457c..620afba99 100644 --- a/src/test/java/org/java_websocket/client/AllClientTests.java +++ b/src/test/java/org/java_websocket/client/AllClientTests.java @@ -31,7 +31,8 @@ @RunWith(Suite.class) @Suite.SuiteClasses({ - org.java_websocket.client.AttachmentTest.class + org.java_websocket.client.AttachmentTest.class, + org.java_websocket.client.SchemaCheckTest.class }) /** * Start all tests for the client diff --git a/src/test/java/org/java_websocket/client/SchemaCheckTest.java b/src/test/java/org/java_websocket/client/SchemaCheckTest.java new file mode 100644 index 000000000..fd829cfc4 --- /dev/null +++ b/src/test/java/org/java_websocket/client/SchemaCheckTest.java @@ -0,0 +1,86 @@ +package org.java_websocket.client; + +import org.java_websocket.handshake.ServerHandshake; +import org.junit.Test; + +import java.net.URI; +import java.net.URISyntaxException; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class SchemaCheckTest { + + @Test + public void testSchemaCheck() throws URISyntaxException { + final String []invalidCase = { + "http://localhost:80", + "http://localhost:81", + "http://localhost", + "https://localhost:443", + "https://localhost:444", + "https://localhost", + "any://localhost", + "any://localhost:82", + }; + final Exception[] exs = new Exception[invalidCase.length]; + for (int i = 0; i < invalidCase.length; i++) { + final int finalI = i; + new WebSocketClient(new URI(invalidCase[finalI])) { + @Override + public void onOpen(ServerHandshake handshakedata) { + + } + + @Override + public void onMessage(String message) { + + } + + @Override + public void onClose(int code, String reason, boolean remote) { + + } + + @Override + public void onError(Exception ex) { + exs[finalI] = ex; + } + }.run(); + } + for (Exception exception : exs) { + assertTrue(exception instanceof IllegalArgumentException); + } + final String []validCase = { + "ws://localhost", + "ws://localhost:80", + "ws://localhost:81", + "wss://localhost", + "wss://localhost:443", + "wss://localhost:444" + }; + for (String s : validCase) { + new WebSocketClient(new URI(s)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + + } + + @Override + public void onMessage(String message) { + + } + + @Override + public void onClose(int code, String reason, boolean remote) { + + } + + @Override + public void onError(Exception ex) { + assertFalse(ex instanceof IllegalArgumentException); + } + }.run(); + } + } +} From abb51a69d6760a102c7b16010332d3ad55af55cc Mon Sep 17 00:00:00 2001 From: Alpha Date: Sat, 23 May 2020 21:59:05 +0800 Subject: [PATCH 047/165] Fixed typo in WebSocketClient.reset's error message --- src/main/java/org/java_websocket/client/WebSocketClient.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 4d735dee6..8899ce144 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -319,7 +319,7 @@ public boolean reconnectBlocking() throws InterruptedException { private void reset() { Thread current = Thread.currentThread(); if (current == writeThread || current == connectReadThread) { - throw new IllegalStateException("You cannot initialize a reconnect out of the websocket thread. Use reconnect in another thread to insure a successful cleanup."); + throw new IllegalStateException("You cannot initialize a reconnect out of the websocket thread. Use reconnect in another thread to ensure a successful cleanup."); } try { closeBlocking(); From edeb6feadbe0db3af675236fe5d563ab786ba78d Mon Sep 17 00:00:00 2001 From: marci4 Date: Thu, 28 May 2020 20:40:16 +0200 Subject: [PATCH 048/165] Make Protocols less strict --- src/main/example/ChatServer.java | 8 + .../SecWebSocketProtocolServerExample.java | 54 +++++ .../java/org/java_websocket/WebSocket.java | 9 + .../org/java_websocket/WebSocketImpl.java | 10 + .../client/WebSocketClient.java | 4 + .../java_websocket/protocols/Protocol.java | 3 + .../ProtoclHandshakeRejectionTest.java | 184 ++++++++++++++++-- .../protocols/ProtocolTest.java | 8 +- 8 files changed, 262 insertions(+), 18 deletions(-) create mode 100644 src/main/example/SecWebSocketProtocolServerExample.java diff --git a/src/main/example/ChatServer.java b/src/main/example/ChatServer.java index d12029117..7439add7b 100644 --- a/src/main/example/ChatServer.java +++ b/src/main/example/ChatServer.java @@ -29,11 +29,15 @@ import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; +import java.util.Collections; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketImpl; +import org.java_websocket.drafts.Draft; +import org.java_websocket.drafts.Draft_6455; import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.protocols.IProtocol; import org.java_websocket.server.WebSocketServer; /** @@ -49,6 +53,10 @@ public ChatServer( InetSocketAddress address ) { super( address ); } + public ChatServer(int port, Draft_6455 draft) { + super( new InetSocketAddress( port ), Collections.singletonList(draft)); + } + @Override public void onOpen( WebSocket conn, ClientHandshake handshake ) { conn.send("Welcome to the server!"); //This method sends a message to the new client diff --git a/src/main/example/SecWebSocketProtocolServerExample.java b/src/main/example/SecWebSocketProtocolServerExample.java new file mode 100644 index 000000000..911961240 --- /dev/null +++ b/src/main/example/SecWebSocketProtocolServerExample.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2010-2020 Nathan Rajlich + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +import org.java_websocket.drafts.Draft_6455; +import org.java_websocket.extensions.IExtension; +import org.java_websocket.protocols.IProtocol; +import org.java_websocket.protocols.Protocol; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collections; + +/** + * This example demonstrates how to use a specific Sec-WebSocket-Protocol for your connection. + */ +public class SecWebSocketProtocolServerExample { + + public static void main( String[] args ) throws URISyntaxException { + // This draft only allows you to use the specific Sec-WebSocket-Protocol without a fallback. + Draft_6455 draft_ocppOnly = new Draft_6455(Collections.emptyList(), Collections.singletonList(new Protocol("ocpp2.0"))); + + // This draft allows the specific Sec-WebSocket-Protocol and also provides a fallback, if the other endpoint does not accept the specific Sec-WebSocket-Protocol + ArrayList protocols = new ArrayList(); + protocols.add(new Protocol("ocpp2.0")); + protocols.add(new Protocol("")); + Draft_6455 draft_ocppAndFallBack = new Draft_6455(Collections.emptyList(), protocols); + + ChatServer chatServer = new ChatServer(8887, draft_ocppOnly); + chatServer.start(); + } +} diff --git a/src/main/java/org/java_websocket/WebSocket.java b/src/main/java/org/java_websocket/WebSocket.java index c4d0441c7..5bc6c74ff 100644 --- a/src/main/java/org/java_websocket/WebSocket.java +++ b/src/main/java/org/java_websocket/WebSocket.java @@ -34,6 +34,7 @@ import org.java_websocket.enums.ReadyState; import org.java_websocket.exceptions.WebsocketNotConnectedException; import org.java_websocket.framing.Framedata; +import org.java_websocket.protocols.IProtocol; import javax.net.ssl.SSLSession; @@ -224,4 +225,12 @@ public interface WebSocket { * @since 1.4.1 */ SSLSession getSSLSession() throws IllegalArgumentException; + + /** + * Returns the used Sec-WebSocket-Protocol for this websocket connection + * @return the Sec-WebSocket-Protocol or null, if no draft available + * @throws IllegalArgumentException the underlying draft does not support a Sec-WebSocket-Protocol + * @since 1.5.2 + */ + IProtocol getProtocol(); } \ No newline at end of file diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index 3459438ef..fe073df8b 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -34,6 +34,7 @@ import org.java_websocket.framing.Framedata; import org.java_websocket.framing.PingFrame; import org.java_websocket.handshake.*; +import org.java_websocket.protocols.IProtocol; import org.java_websocket.server.WebSocketServer.WebSocketWorker; import org.java_websocket.util.Charsetfunctions; @@ -832,6 +833,15 @@ public SSLSession getSSLSession() { return ((ISSLChannel) channel).getSSLEngine().getSession(); } + @Override + public IProtocol getProtocol() { + if (draft == null) + return null; + if (!(draft instanceof Draft_6455)) + throw new IllegalArgumentException("This draft does not support Sec-WebSocket-Protocol"); + return ((Draft_6455) draft).getProtocol(); + } + @Override public void setAttachment(T attachment) { this.attachment = attachment; diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 4d735dee6..58e378855 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -59,6 +59,7 @@ import org.java_websocket.handshake.HandshakeImpl1Client; import org.java_websocket.handshake.Handshakedata; import org.java_websocket.handshake.ServerHandshake; +import org.java_websocket.protocols.IProtocol; /** * A subclass must implement at least onOpen, onClose, and onMessage to be @@ -913,6 +914,9 @@ public SSLSession getSSLSession() { return engine.getSSLSession(); } + @Override + public IProtocol getProtocol() { return engine.getProtocol();} + /** * Method to give some additional info for specific IOExceptions * @param e the IOException causing a eot. diff --git a/src/main/java/org/java_websocket/protocols/Protocol.java b/src/main/java/org/java_websocket/protocols/Protocol.java index 4c3ba70f1..9c63115a9 100644 --- a/src/main/java/org/java_websocket/protocols/Protocol.java +++ b/src/main/java/org/java_websocket/protocols/Protocol.java @@ -56,6 +56,9 @@ public Protocol( String providedProtocol ) { @Override public boolean acceptProvidedProtocol( String inputProtocolHeader ) { + if ("".equals(providedProtocol)) { + return true; + } String protocolHeader = patternSpace.matcher(inputProtocolHeader).replaceAll(""); String[] headers = patternComma.split(protocolHeader); for( String header : headers ) { diff --git a/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java b/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java index 6ee3d89b3..6c0b8072d 100644 --- a/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java +++ b/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java @@ -48,17 +48,14 @@ import java.util.Collections; import java.util.Scanner; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; public class ProtoclHandshakeRejectionTest { private static final String additionalHandshake = "HTTP/1.1 101 Websocket Connection Upgrade\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"; - private static int counter = 0; private static Thread thread; private static ServerSocket serverSocket; - private static boolean debugPrintouts = false; - private static int port; @BeforeClass @@ -70,7 +67,6 @@ public void run() { try { serverSocket = new ServerSocket( port ); serverSocket.setReuseAddress( true ); - int count = 1; while( true ) { Socket client = null; try { @@ -94,7 +90,6 @@ public void run() { } } OutputStream os = client.getOutputStream(); - count++; if( "/0".equals( testCase ) ) { os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "\r\n" ) ); os.flush(); @@ -175,6 +170,47 @@ public void run() { os.write( Charsetfunctions.asciiBytes( additionalHandshake + "\r\n" ) ); os.flush(); } + // Order check + if( "/20".equals( testCase ) ) { + os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n" ) ); + os.flush(); + } + if( "/21".equals( testCase ) ) { + os.write( Charsetfunctions.asciiBytes( additionalHandshake +getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n" ) ); + os.flush(); + } + if( "/22".equals( testCase ) ) { + os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n" ) ); + os.flush(); + } + if( "/23".equals( testCase ) ) { + os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n" ) ); + os.flush(); + } + if( "/24".equals( testCase ) ) { + os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n" ) ); + os.flush(); + } + if( "/25".equals( testCase ) ) { + os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: abc" + "\r\n\r\n" ) ); + os.flush(); + } + if( "/26".equals( testCase ) ) { + os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "\r\n\r\n" ) ); + os.flush(); + } + if( "/27".equals( testCase ) ) { + os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n" ) ); + os.flush(); + } + if( "/28".equals( testCase ) ) { + os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: abc" + "\r\n\r\n" ) ); + os.flush(); + } + if( "/29".equals( testCase ) ) { + os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "\r\n\r\n" ) ); + os.flush(); + } } catch ( IOException e ) { // } @@ -193,16 +229,14 @@ private static String getSecKey( String seckey ) { } @AfterClass - public static void successTests() throws InterruptedException, IOException { + public static void successTests() throws IOException { serverSocket.close(); thread.interrupt(); - if( debugPrintouts ) - System.out.println( counter + " successful tests" ); } @Test(timeout = 5000) public void testProtocolRejectionTestCase0() throws Exception { - testProtocolRejection( 0, new Draft_6455() ); + testProtocolRejection( 0, new Draft_6455(Collections.emptyList(), Collections.singletonList( new Protocol( "" ))) ); } @Test(timeout = 5000) @@ -312,6 +346,62 @@ public void testHandshakeRejectionTestCase19() throws Exception { testProtocolRejection( 19, new Draft_6455() ); } + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase20() throws Exception { + testProtocolRejection( 20, new Draft_6455() ); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase21() throws Exception { + ArrayList protocols = new ArrayList(); + protocols.add( new Protocol( "chat1" ) ); + protocols.add( new Protocol( "chat2" ) ); + protocols.add( new Protocol( "chat3" ) ); + testProtocolRejection( 21, new Draft_6455( Collections.emptyList(), protocols ) ); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase22() throws Exception { + ArrayList protocols = new ArrayList(); + protocols.add( new Protocol( "chat2" ) ); + protocols.add( new Protocol( "chat3" ) ); + protocols.add( new Protocol( "chat1" ) ); + testProtocolRejection( 22, new Draft_6455( Collections.emptyList(), protocols ) ); + } + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase23() throws Exception { + ArrayList protocols = new ArrayList(); + protocols.add( new Protocol( "chat3" ) ); + protocols.add( new Protocol( "chat2" ) ); + protocols.add( new Protocol( "chat1" ) ); + testProtocolRejection( 23, new Draft_6455( Collections.emptyList(), protocols ) ); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase24() throws Exception { + testProtocolRejection( 24, new Draft_6455() ); + } + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase25() throws Exception { + testProtocolRejection( 25, new Draft_6455() ); + } + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase26() throws Exception { + testProtocolRejection( 26, new Draft_6455() ); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase27() throws Exception { + testProtocolRejection( 27, new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "opc" ) ) ) ); + } + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase28() throws Exception { + testProtocolRejection( 28, new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "opc" ) ) ) ); + } + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase29() throws Exception { + testProtocolRejection( 29, new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "opc" ) ) ) ); + } private void testProtocolRejection( int i, Draft_6455 draft ) throws Exception { final int finalI = i; final boolean[] threadReturned = { false }; @@ -320,6 +410,11 @@ private void testProtocolRejection( int i, Draft_6455 draft ) throws Exception { public void onOpen( ServerHandshake handshakedata ) { switch(finalI) { case 0: + case 1: + case 2: + case 3: + case 4: + case 5: case 6: case 7: case 8: @@ -327,7 +422,13 @@ public void onOpen( ServerHandshake handshakedata ) { case 13: case 14: case 17: - counter++; + case 20: + case 21: + case 22: + case 23: + case 24: + case 25: + case 26: threadReturned[0] = true; closeConnection( CloseFrame.ABNORMAL_CLOSE, "Bye" ); break; @@ -343,9 +444,60 @@ public void onMessage( String message ) { @Override public void onClose( int code, String reason, boolean remote ) { + switch (finalI) { + case 0: + case 1: + case 2: + case 3: + case 4: + case 20: + case 24: + case 25: + case 26: + assertEquals("" ,getProtocol().getProvidedProtocol()); + break; + case 5: + case 9: + case 10: + case 11: + case 12: + case 13: + case 15: + case 16: + case 18: + case 19: + case 27: + case 28: + case 29: + assertNull(getProtocol()); + break; + case 6: + case 7: + case 8: + case 17: + assertEquals("chat" ,getProtocol().getProvidedProtocol()); + break; + case 14: + case 22: + assertEquals("chat2" ,getProtocol().getProvidedProtocol()); + break; + case 21: + assertEquals("chat1" ,getProtocol().getProvidedProtocol()); + break; + case 23: + assertEquals("chat3" ,getProtocol().getProvidedProtocol()); + break; + default: + fail(); + } if( code == CloseFrame.ABNORMAL_CLOSE ) { switch(finalI) { case 0: + case 1: + case 2: + case 3: + case 4: + case 5: case 6: case 7: case 8: @@ -353,16 +505,20 @@ public void onClose( int code, String reason, boolean remote ) { case 13: case 14: case 17: + case 20: + case 21: + case 22: + case 23: + case 24: + case 25: + case 26: return; } } if( code != CloseFrame.PROTOCOL_ERROR ) { fail( "There should be a protocol error! " + finalI + " " + code ); } else if( reason.endsWith( "refuses handshake" ) ) { - if( debugPrintouts ) - System.out.println( "Protocol error for test case: " + finalI ); threadReturned[0] = true; - counter++; } else { fail( "The reason should be included!" ); } diff --git a/src/test/java/org/java_websocket/protocols/ProtocolTest.java b/src/test/java/org/java_websocket/protocols/ProtocolTest.java index faf32891c..91d7b3394 100644 --- a/src/test/java/org/java_websocket/protocols/ProtocolTest.java +++ b/src/test/java/org/java_websocket/protocols/ProtocolTest.java @@ -46,12 +46,12 @@ public void testConstructor() throws Exception { public void testAcceptProvidedProtocol() throws Exception { Protocol protocol0 = new Protocol( "" ); assertTrue( protocol0.acceptProvidedProtocol( "" ) ); - assertTrue( !protocol0.acceptProvidedProtocol( "chat" ) ); - assertTrue( !protocol0.acceptProvidedProtocol( "chat, test" ) ); - assertTrue( !protocol0.acceptProvidedProtocol( "chat, test," ) ); + assertTrue( protocol0.acceptProvidedProtocol( "chat" ) ); + assertTrue( protocol0.acceptProvidedProtocol( "chat, test" ) ); + assertTrue( protocol0.acceptProvidedProtocol( "chat, test," ) ); Protocol protocol1 = new Protocol( "chat" ); assertTrue( protocol1.acceptProvidedProtocol( "chat" ) ); - assertTrue( !protocol1.acceptProvidedProtocol( "test" ) ); + assertFalse( protocol1.acceptProvidedProtocol( "test" ) ); assertTrue( protocol1.acceptProvidedProtocol( "chat, test" ) ); assertTrue( protocol1.acceptProvidedProtocol( "test, chat" ) ); assertTrue( protocol1.acceptProvidedProtocol( "test,chat" ) ); From f1802ae73fb79f1a4b083ae07f044a1fda416241 Mon Sep 17 00:00:00 2001 From: marci4 Date: Thu, 28 May 2020 22:20:42 +0200 Subject: [PATCH 049/165] Update Draft_6455Test.java Adjust tests --- .../java_websocket/drafts/Draft_6455Test.java | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/test/java/org/java_websocket/drafts/Draft_6455Test.java b/src/test/java/org/java_websocket/drafts/Draft_6455Test.java index cbf41cedb..af0b1bfae 100644 --- a/src/test/java/org/java_websocket/drafts/Draft_6455Test.java +++ b/src/test/java/org/java_websocket/drafts/Draft_6455Test.java @@ -132,7 +132,7 @@ public void testGetKnownExtensions() throws Exception { @Test public void testGetProtocol() throws Exception { - Draft_6455 draft_6455 = new Draft_6455(); + Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), Collections.emptyList()); assertNull( draft_6455.getProtocol() ); draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ); assertNull( draft_6455.getProtocol() ); @@ -194,7 +194,7 @@ public void testToString() throws Exception { Draft_6455 draft_6455 = new Draft_6455(); assertEquals( "Draft_6455 extension: DefaultExtension max frame size: 2147483647", draft_6455.toString() ); draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ); - assertEquals( "Draft_6455 extension: DefaultExtension max frame size: 2147483647", draft_6455.toString() ); + assertEquals( "Draft_6455 extension: DefaultExtension protocol: max frame size: 2147483647", draft_6455.toString() ); draft_6455 = new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ); assertEquals( "Draft_6455 extension: DefaultExtension max frame size: 2147483647", draft_6455.toString() ); draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ); @@ -223,7 +223,7 @@ public void testEquals() throws Exception { draft1.acceptHandshakeAsServer( handshakedataProtocolExtension ); assertNotEquals( draft2, draft3 ); assertNotEquals( draft0, draft2 ); - assertEquals( draft0, draft1 ); + assertNotEquals( draft0, draft1 ); draft2 = draft2.copyInstance(); draft1 = draft1.copyInstance(); //unequal for draft draft2 due to a provided protocol @@ -231,7 +231,7 @@ public void testEquals() throws Exception { draft1.acceptHandshakeAsServer( handshakedataProtocol ); assertNotEquals( draft2, draft3 ); assertNotEquals( draft0, draft2 ); - assertEquals( draft0, draft1 ); + assertNotEquals( draft0, draft1 ); draft2 = draft2.copyInstance(); draft1 = draft1.copyInstance(); //unequal for draft draft0 due to a provided protocol (no protocol) @@ -297,14 +297,14 @@ public void testHashCode() throws Exception { public void acceptHandshakeAsServer() throws Exception { Draft_6455 draft_6455 = new Draft_6455(); assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedata ) ); - assertEquals( HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocol ) ); + assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocol ) ); assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataExtension ) ); - assertEquals( HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ) ); + assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ) ); draft_6455 = new Draft_6455( new TestExtension() ); assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedata ) ); - assertEquals( HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocol ) ); + assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocol ) ); assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataExtension ) ); - assertEquals( HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ) ); + assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ) ); draft_6455 = new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ); assertEquals( HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsServer( handshakedata ) ); assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocol ) ); @@ -336,7 +336,7 @@ public void acceptHandshakeAsClient() throws Exception { response.put( "Sec-WebSocket-Accept", "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=" ); assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient( request, response ) ); response.put( "Sec-WebSocket-Protocol", "chat" ); - assertEquals( HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient( request, response ) ); + assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient( request, response ) ); draft_6455 = new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ); assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient( request, response ) ); ArrayList protocols = new ArrayList(); @@ -344,7 +344,7 @@ public void acceptHandshakeAsClient() throws Exception { protocols.add( new Protocol( "chat" ) ); draft_6455 = new Draft_6455( Collections.emptyList(), protocols ); assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient( request, response ) ); - draft_6455 = new Draft_6455(); + draft_6455 =new Draft_6455(Collections.emptyList(), Collections.emptyList()); assertEquals( HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient( request, response ) ); protocols.clear(); protocols.add( new Protocol( "chat3" ) ); From 1e9d489c67f698b04e416331a4d9c2c8322dcd62 Mon Sep 17 00:00:00 2001 From: chenguoping Date: Sun, 28 Jun 2020 17:00:25 +0800 Subject: [PATCH 050/165] update build.gradle : make it same as pom.xml --- build.gradle | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/build.gradle b/build.gradle index e5dd35858..7a1a0108f 100644 --- a/build.gradle +++ b/build.gradle @@ -8,8 +8,8 @@ repositories { mavenCentral() } -group = 'org.java_websocket' -version = '1.4.1-SNAPSHOT' +group = 'org.java-websocket' +version = '1.5.2-SNAPSHOT' sourceCompatibility = 1.6 targetCompatibility = 1.6 @@ -19,7 +19,7 @@ configurations { configure(install.repositories.mavenInstaller) { pom.version = project.version - pom.groupId = "org.java_websocket" + pom.groupId = "org.java-websocket" pom.artifactId = 'Java-WebSocket' } @@ -27,8 +27,8 @@ dependencies { deployerJars "org.apache.maven.wagon:wagon-webdav:1.0-beta-2" compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25' testCompile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25' - testCompile group: 'junit', name: 'junit', version: '4.11' - testCompile group: 'org.json', name: 'json', version: '20180130' + testCompile group: 'junit', name: 'junit', version: '4.12' + testCompile group: 'org.json', name: 'json', version: '20180813' } From b6435fc44c43d0c566647699205ca1a928d5c37e Mon Sep 17 00:00:00 2001 From: dota17 Date: Mon, 29 Jun 2020 12:04:41 +0800 Subject: [PATCH 051/165] FixTypo --- autobahn reports/clients/index.html | 158 +++++++++--------- autobahn reports/servers/index.html | 2 +- src/main/example/ChatClient.java | 2 +- .../org/java_websocket/SSLSocketChannel.java | 8 +- .../org/java_websocket/SSLSocketChannel2.java | 6 +- .../java/org/java_websocket/WebSocket.java | 2 +- .../org/java_websocket/WebSocketImpl.java | 8 +- .../org/java_websocket/WebSocketListener.java | 20 +-- .../java/org/java_websocket/drafts/Draft.java | 2 +- .../IncompleteHandshakeException.java | 6 +- .../exceptions/InvalidDataException.java | 2 +- .../exceptions/InvalidFrameException.java | 2 +- .../exceptions/InvalidHandshakeException.java | 2 +- .../java_websocket/framing/CloseFrame.java | 2 +- .../java_websocket/framing/ControlFrame.java | 8 +- .../server/WebSocketServer.java | 10 +- .../java/org/java_websocket/util/Base64.java | 16 +- .../framing/BinaryFrameTest.java | 2 +- .../framing/CloseFrameTest.java | 2 +- .../framing/ContinuousFrameTest.java | 2 +- .../framing/FramedataImpl1Test.java | 4 +- .../java_websocket/framing/PingFrameTest.java | 2 +- .../java_websocket/framing/PongFrameTest.java | 2 +- .../java_websocket/framing/TextFrameTest.java | 2 +- 24 files changed, 136 insertions(+), 136 deletions(-) diff --git a/autobahn reports/clients/index.html b/autobahn reports/clients/index.html index 5fa8f93d7..4caa128b9 100644 --- a/autobahn reports/clients/index.html +++ b/autobahn reports/clients/index.html @@ -2246,13 +2246,13 @@

Case 6.2.4

Case 6.3.1

Up -

Case Description

Send invalid UTF-8 text message unfragmented.

MESSAGE:
κόσμε���edited
cebae1bdb9cf83cebcceb5eda080656469746564

+

Case Description

Send invalid UTF-8 text message unfragmented.

MESSAGE:
κόσμε�edited
cebae1bdb9cf83cebcceb5eda080656469746564

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.3.2

Up -

Case Description

Send invalid UTF-8 text message in fragments of 1 octet, resulting in frames ending on positions which are not code point ends.

MESSAGE:
κόσμε���edited
cebae1bdb9cf83cebcceb5eda080656469746564

+

Case Description

Send invalid UTF-8 text message in fragments of 1 octet, resulting in frames ending on positions which are not code point ends.

MESSAGE:
κόσμε�edited
cebae1bdb9cf83cebcceb5eda080656469746564

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


@@ -2263,7 +2263,7 @@

Case 6.4.1

Note that PART1 and PART3 are valid UTF-8 in themselves, PART2 is a 0x11000 encoded as in the UTF-8 integer encoding scheme, but the codepoint is invalid (out of range).

MESSAGE PARTS:
PART1 = κόσμε (cebae1bdb9cf83cebcceb5)
-PART2 = ���� (f4908080)
+PART2 = ���� (f4908080)
PART3 = edited (656469746564)

Case Expectation

The first frame is accepted, we expect to timeout on the first wait. The 2nd frame should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.

@@ -2273,9 +2273,9 @@

Case 6.4.2

Up

Case Description

Same as Case 6.4.1, but in 2nd frame, we send only up to and including the octet making the complete payload invalid.

MESSAGE PARTS:
-PART1 = κόσμε� (cebae1bdb9cf83cebcceb5f4)
-PART2 = � (90)
-PART3 = ��edited (8080656469746564)
+PART1 = κόσμε� (cebae1bdb9cf83cebcceb5f4)
+PART2 = � (90)
+PART3 = ��edited (8080656469746564)

Case Expectation

The first frame is accepted, we expect to timeout on the first wait. The 2nd frame should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.


@@ -2285,7 +2285,7 @@

Case 6.4.3

Case Description

Same as Case 6.4.1, but we send message not in 3 frames, but in 3 chops of the same message frame.

MESSAGE PARTS:
PART1 = κόσμε (cebae1bdb9cf83cebcceb5)
-PART2 = ���� (f4908080)
+PART2 = ���� (f4908080)
PART3 = edited (656469746564)

Case Expectation

The first chop is accepted, we expect to timeout on the first wait. The 2nd chop should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.

@@ -2295,8 +2295,8 @@

Case 6.4.4

Up

Case Description

Same as Case 6.4.2, but we send message not in 3 frames, but in 3 chops of the same message frame.

MESSAGE PARTS:
-PART1 = κόσμε� (cebae1bdb9cf83cebcceb5f4)
-PART2 = � (90)
+PART1 = κόσμε� (cebae1bdb9cf83cebcceb5f4)
+PART2 = � (90)
PART3 = ()

Case Expectation

The first chop is accepted, we expect to timeout on the first wait. The 2nd chop should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.

@@ -2310,7 +2310,7 @@

Case 6.5.1

Case 6.6.1

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
ce

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
ce

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


@@ -2322,13 +2322,13 @@

Case 6.6.2

Case 6.6.3

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
κ�
cebae1

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
κ�
cebae1

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.6.4

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
κ�
cebae1bd

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
κ�
cebae1bd

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


@@ -2340,7 +2340,7 @@

Case 6.6.5

Case 6.6.6

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
κό�
cebae1bdb9cf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
κό�
cebae1bdb9cf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


@@ -2352,7 +2352,7 @@

Case 6.6.7

Case 6.6.8

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
κόσ�
cebae1bdb9cf83ce

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
κόσ�
cebae1bdb9cf83ce

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


@@ -2364,7 +2364,7 @@

Case 6.6.9

Case 6.6.10

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
κόσμ�
cebae1bdb9cf83cebcce

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
κόσμ�
cebae1bdb9cf83cebcce

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


@@ -2400,13 +2400,13 @@

Case 6.7.4

Case 6.8.1

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����
f888808080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����
f888808080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.8.2

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
fc8480808080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
fc8480808080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


@@ -2436,19 +2436,19 @@

Case 6.9.4

Case 6.10.1

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
f7bfbfbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
f7bfbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.10.2

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����
fbbfbfbfbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����
fbbfbfbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.10.3

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
fdbfbfbfbfbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
fdbfbfbfbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


@@ -2478,349 +2478,349 @@

Case 6.11.4

Case 6.11.5

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
f4908080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
f4908080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.12.1

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
80

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
80

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.12.2

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
bf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
bf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.12.3

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
80bf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
80bf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.12.4

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
80bf80

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
80bf80

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.12.5

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
80bf80bf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
80bf80bf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.12.6

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����
80bf80bf80

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����
80bf80bf80

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.12.7

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
80bf80bf80bf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
80bf80bf80bf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.12.8

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���������������������������������������������������������������
808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbe

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���������������������������������������������������������������
808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbe

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.13.1

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �
c020c120c220c320c420c520c620c720c820c920ca20cb20cc20cd20ce20cf20d020d120d220d320d420d520d620d720d820d920da20db20dc20dd20de20

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �
c020c120c220c320c420c520c620c720c820c920ca20cb20cc20cd20ce20cf20d020d120d220d320d420d520d620d720d820d920da20db20dc20dd20de20

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.13.2

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
� � � � � � � � � � � � � � �
e020e120e220e320e420e520e620e720e820e920ea20eb20ec20ed20ee20

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
� � � � � � � � � � � � � � �
e020e120e220e320e420e520e620e720e820e920ea20eb20ec20ed20ee20

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.13.3

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
� � � � � � �
f020f120f220f320f420f520f620

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
� � � � � � �
f020f120f220f320f420f520f620

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.13.4

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
� � �
f820f920fa20

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
� � �
f820f920fa20

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.13.5

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
fc20

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
fc20

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.1

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
c0

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
c0

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.2

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
e080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
e080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.3

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
f08080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
f08080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.4

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
f8808080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
f8808080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.5

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����
fc80808080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����
fc80808080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.6

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
df

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
df

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.7

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
efbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
efbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.8

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
f7bfbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
f7bfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.9

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
fbbfbfbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
fbbfbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.10

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����
fdbfbfbfbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����
fdbfbfbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.15.1

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����������������������������
c0e080f08080f8808080fc80808080dfefbff7bfbffbbfbfbffdbfbfbfbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����������������������������
c0e080f08080f8808080fc80808080dfefbff7bfbffbbfbfbffdbfbfbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.16.1

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
fe

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
fe

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.16.2

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
ff

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
ff

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.16.3

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
fefeffff

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
fefeffff

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.17.1

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
c0af

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
c0af

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.17.2

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
e080af

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
e080af

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.17.3

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
f08080af

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
f08080af

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.17.4

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����
f8808080af

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����
f8808080af

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.17.5

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
fc80808080af

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
fc80808080af

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.18.1

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
c1bf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
c1bf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.18.2

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
e09fbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
e09fbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.18.3

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
f08fbfbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
f08fbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.18.4

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����
f887bfbfbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����
f887bfbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.18.5

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
fc83bfbfbfbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
fc83bfbfbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.19.1

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
c080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
c080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.19.2

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
e08080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
e08080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.19.3

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
f0808080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
����
f0808080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.19.4

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����
f880808080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�����
f880808080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.19.5

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
fc8080808080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
fc8080808080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.20.1

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
eda080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
eda080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.20.2

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
edadbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
edadbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.20.3

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
edae80

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
edae80

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.20.4

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
edafbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
edafbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.20.5

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
edb080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
edb080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.20.6

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
edbe80

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
edbe80

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.20.7

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
���
edbfbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
�
edbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.21.1

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
eda080edb080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
eda080edb080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.21.2

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
eda080edbfbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
eda080edbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.21.3

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
edadbfedb080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
edadbfedb080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.21.4

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
edadbfedbfbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
edadbfedbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.21.5

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
edae80edb080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
edae80edb080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.21.6

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
edae80edbfbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
edae80edbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.21.7

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
edafbfedb080

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
edafbfedb080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.21.8

Up -

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
������
edafbfedbfbf

+

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

MESSAGE:
��
edafbfedbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


@@ -3067,7 +3067,7 @@

Case 7.1.5

Case 7.1.6

Up

Case Description

Send 256K message followed by close then a ping

-

Case Expectation

Case outcome depends on implimentation defined close behavior. Message and close frame are sent back to back. If the close frame is processed before the text message write is complete (as can happen in asyncronous processing models) the close frame is processed first and the text message may not be recieved or may only be partially recieved.

+

Case Expectation

Case outcome depends on implimentation defined close behavior. Message and close frame are sent back to back. If the close frame is processed before the text message write is complete (as can happen in asyncronous processing models) the close frame is processed first and the text message may not be received or may only be partially received.


Case 7.3.1

diff --git a/autobahn reports/servers/index.html b/autobahn reports/servers/index.html index d9056d0b3..1a8d01e2b 100644 --- a/autobahn reports/servers/index.html +++ b/autobahn reports/servers/index.html @@ -4112,7 +4112,7 @@

Case 7.1.5

Case 7.1.6

Up

Case Description

Send 256K message followed by close then a ping

-

Case Expectation

Case outcome depends on implementation defined close behavior. Message and close frame are sent back to back. If the close frame is processed before the text message write is complete (as can happen in asynchronous processing models) the close frame is processed first and the text message may not be received or may only be partially recieved.

+

Case Expectation

Case outcome depends on implementation defined close behavior. Message and close frame are sent back to back. If the close frame is processed before the text message write is complete (as can happen in asynchronous processing models) the close frame is processed first and the text message may not be received or may only be partially received.


Case 7.3.1

diff --git a/src/main/example/ChatClient.java b/src/main/example/ChatClient.java index 9a210592e..978a29127 100644 --- a/src/main/example/ChatClient.java +++ b/src/main/example/ChatClient.java @@ -146,7 +146,7 @@ public void onClose( int code, String reason, boolean remote ) { @Override public void onError( Exception ex ) { - ta.append( "Exception occured ...\n" + ex + "\n" ); + ta.append( "Exception occurred ...\n" + ex + "\n" ); ta.setCaretPosition( ta.getDocument().getLength() ); ex.printStackTrace(); connect.setEnabled( true ); diff --git a/src/main/java/org/java_websocket/SSLSocketChannel.java b/src/main/java/org/java_websocket/SSLSocketChannel.java index ed8a797d2..ac214d68b 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel.java @@ -61,7 +61,7 @@ *

* Modified by marci4 to allow the usage as a ByteChannel *

- * Permission for usage recieved at May 25, 2017 by Alex Karnezis + * Permission for usage received at May 25, 2017 by Alex Karnezis */ public class SSLSocketChannel implements WrappedByteChannel, ByteChannel, ISSLChannel { @@ -214,7 +214,7 @@ public synchronized int write( ByteBuffer output ) throws IOException { myNetData = enlargePacketBuffer( myNetData ); break; case BUFFER_UNDERFLOW: - throw new SSLException( "Buffer underflow occured after a wrap. I don't think we should ever get here." ); + throw new SSLException( "Buffer underflow occurred after a wrap. I don't think we should ever get here." ); case CLOSED: closeConnection(); return 0; @@ -283,7 +283,7 @@ private boolean doHandshake() throws IOException { try { engine.closeInbound(); } catch ( SSLException e ) { - //Ignore, cant do anything against this exception + //Ignore, can't do anything against this exception } engine.closeOutbound(); // After closeOutbound the engine will be set to WRAP state, in order to try to send a close message to the client. @@ -347,7 +347,7 @@ private boolean doHandshake() throws IOException { myNetData = enlargePacketBuffer( myNetData ); break; case BUFFER_UNDERFLOW: - throw new SSLException( "Buffer underflow occured after a wrap. I don't think we should ever get here." ); + throw new SSLException( "Buffer underflow occurred after a wrap. I don't think we should ever get here." ); case CLOSED: try { myNetData.flip(); diff --git a/src/main/java/org/java_websocket/SSLSocketChannel2.java b/src/main/java/org/java_websocket/SSLSocketChannel2.java index e2fb0acc0..ae9669d49 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel2.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel2.java @@ -315,11 +315,11 @@ public int read(ByteBuffer dst) throws IOException { inCrypt.flip(); unwrap(); - int transfered = transfereTo(inData, dst); - if (transfered == 0 && isBlocking()) { + int transferred = transfereTo(inData, dst); + if (transferred == 0 && isBlocking()) { continue; } - return transfered; + return transferred; } } /** diff --git a/src/main/java/org/java_websocket/WebSocket.java b/src/main/java/org/java_websocket/WebSocket.java index c4d0441c7..c5a80797a 100644 --- a/src/main/java/org/java_websocket/WebSocket.java +++ b/src/main/java/org/java_websocket/WebSocket.java @@ -59,7 +59,7 @@ public interface WebSocket { /** * This will close the connection immediately without a proper close handshake. - * The code and the message therefore won't be transfered over the wire also they will be forwarded to onClose/onWebsocketClose. + * The code and the message therefore won't be transferred over the wire also they will be forwarded to onClose/onWebsocketClose. * @param code the closing code * @param message the closing message **/ diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index f553a21cf..385451c6c 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -152,7 +152,7 @@ public class WebSocketImpl implements WebSocket { private String resourceDescriptor = null; /** - * Attribute, when the last pong was recieved + * Attribute, when the last pong was received */ private long lastPong = System.nanoTime(); @@ -483,7 +483,7 @@ public void close( int code, String message ) { /** * This will close the connection immediately without a proper close handshake. - * The code and the message therefore won't be transfered over the wire also they will be forwarded to onClose/onWebsocketClose. + * The code and the message therefore won't be transferred over the wire also they will be forwarded to onClose/onWebsocketClose. * * @param code the closing code * @param message the closing message @@ -789,9 +789,9 @@ public String getResourceDescriptor() { } /** - * Getter for the last pong recieved + * Getter for the last pong received * - * @return the timestamp for the last recieved pong + * @return the timestamp for the last received pong */ long getLastPong() { return lastPong; diff --git a/src/main/java/org/java_websocket/WebSocketListener.java b/src/main/java/org/java_websocket/WebSocketListener.java index 23cdaef59..7271100c4 100644 --- a/src/main/java/org/java_websocket/WebSocketListener.java +++ b/src/main/java/org/java_websocket/WebSocketListener.java @@ -117,7 +117,7 @@ public interface WebSocketListener { * Indicates that a complete WebSocket connection has been established, * and we are ready to send/receive data. * - * @param conn The WebSocket instance this event is occuring on. + * @param conn The WebSocket instance this event is occurring on. * @param d The handshake of the websocket instance */ void onWebsocketOpen( WebSocket conn, Handshakedata d ); @@ -126,7 +126,7 @@ public interface WebSocketListener { * Called after WebSocket#close is explicity called, or when the * other end of the WebSocket connection is closed. * - * @param ws The WebSocket instance this event is occuring on. + * @param ws The WebSocket instance this event is occurring on. * @param code The codes can be looked up here: {@link CloseFrame} * @param reason Additional information string * @param remote Returns whether or not the closing of the connection was initiated by the remote host. @@ -135,7 +135,7 @@ public interface WebSocketListener { /** Called as soon as no further frames are accepted * - * @param ws The WebSocket instance this event is occuring on. + * @param ws The WebSocket instance this event is occurring on. * @param code The codes can be looked up here: {@link CloseFrame} * @param reason Additional information string * @param remote Returns whether or not the closing of the connection was initiated by the remote host. @@ -144,7 +144,7 @@ public interface WebSocketListener { /** send when this peer sends a close handshake * - * @param ws The WebSocket instance this event is occuring on. + * @param ws The WebSocket instance this event is occurring on. * @param code The codes can be looked up here: {@link CloseFrame} * @param reason Additional information string */ @@ -154,7 +154,7 @@ public interface WebSocketListener { * Called if an exception worth noting occurred. * If an error causes the connection to fail onClose will be called additionally afterwards. * - * @param conn The WebSocket instance this event is occuring on. + * @param conn The WebSocket instance this event is occurring on. * @param ex * The exception that occurred.
* Might be null if the exception is not related to any specific connection. For example if the server port could not be bound. @@ -165,7 +165,7 @@ public interface WebSocketListener { * Called a ping frame has been received. * This method must send a corresponding pong by itself. * - * @param conn The WebSocket instance this event is occuring on. + * @param conn The WebSocket instance this event is occurring on. * @param f The ping frame. Control frames may contain payload. */ void onWebsocketPing( WebSocket conn, Framedata f ); @@ -181,20 +181,20 @@ public interface WebSocketListener { /** * Called when a pong frame is received. * - * @param conn The WebSocket instance this event is occuring on. + * @param conn The WebSocket instance this event is occurring on. * @param f The pong frame. Control frames may contain payload. **/ void onWebsocketPong( WebSocket conn, Framedata f ); /** This method is used to inform the selector thread that there is data queued to be written to the socket. - * @param conn The WebSocket instance this event is occuring on. + * @param conn The WebSocket instance this event is occurring on. */ void onWriteDemand( WebSocket conn ); /** * @see WebSocket#getLocalSocketAddress() * - * @param conn The WebSocket instance this event is occuring on. + * @param conn The WebSocket instance this event is occurring on. * @return Returns the address of the endpoint this socket is bound to. */ InetSocketAddress getLocalSocketAddress( WebSocket conn ); @@ -202,7 +202,7 @@ public interface WebSocketListener { /** * @see WebSocket#getRemoteSocketAddress() * - * @param conn The WebSocket instance this event is occuring on. + * @param conn The WebSocket instance this event is occurring on. * @return Returns the address of the endpoint this socket is connected to, or{@code null} if it is unconnected. */ InetSocketAddress getRemoteSocketAddress( WebSocket conn ); diff --git a/src/main/java/org/java_websocket/drafts/Draft.java b/src/main/java/org/java_websocket/drafts/Draft.java index 77d5d19bb..3fb040c9b 100644 --- a/src/main/java/org/java_websocket/drafts/Draft.java +++ b/src/main/java/org/java_websocket/drafts/Draft.java @@ -51,7 +51,7 @@ import org.java_websocket.util.Charsetfunctions; /** - * Base class for everything of a websocket specification which is not common such as the way the handshake is read or frames are transfered. + * Base class for everything of a websocket specification which is not common such as the way the handshake is read or frames are transferred. **/ public abstract class Draft { diff --git a/src/main/java/org/java_websocket/exceptions/IncompleteHandshakeException.java b/src/main/java/org/java_websocket/exceptions/IncompleteHandshakeException.java index 0125ae342..80c5bc82a 100644 --- a/src/main/java/org/java_websocket/exceptions/IncompleteHandshakeException.java +++ b/src/main/java/org/java_websocket/exceptions/IncompleteHandshakeException.java @@ -26,7 +26,7 @@ package org.java_websocket.exceptions; /** - * exception which indicates that a incomplete handshake was recieved + * exception which indicates that a incomplete handshake was received */ public class IncompleteHandshakeException extends RuntimeException { @@ -36,14 +36,14 @@ public class IncompleteHandshakeException extends RuntimeException { private static final long serialVersionUID = 7906596804233893092L; /** - * attribut which size of handshake would have been prefered + * attribut which size of handshake would have been preferred */ private final int preferredSize; /** * constructor for a IncompleteHandshakeException *

- * @param preferredSize the prefered size + * @param preferredSize the preferred size */ public IncompleteHandshakeException(int preferredSize) { this.preferredSize = preferredSize; diff --git a/src/main/java/org/java_websocket/exceptions/InvalidDataException.java b/src/main/java/org/java_websocket/exceptions/InvalidDataException.java index ec79a1625..af5eaf9e5 100644 --- a/src/main/java/org/java_websocket/exceptions/InvalidDataException.java +++ b/src/main/java/org/java_websocket/exceptions/InvalidDataException.java @@ -26,7 +26,7 @@ package org.java_websocket.exceptions; /** - * exception which indicates that a invalid data was recieved + * exception which indicates that a invalid data was received */ public class InvalidDataException extends Exception { diff --git a/src/main/java/org/java_websocket/exceptions/InvalidFrameException.java b/src/main/java/org/java_websocket/exceptions/InvalidFrameException.java index 336fef91b..9d5ed55c9 100644 --- a/src/main/java/org/java_websocket/exceptions/InvalidFrameException.java +++ b/src/main/java/org/java_websocket/exceptions/InvalidFrameException.java @@ -28,7 +28,7 @@ import org.java_websocket.framing.CloseFrame; /** - * exception which indicates that a invalid frame was recieved (CloseFrame.PROTOCOL_ERROR) + * exception which indicates that a invalid frame was received (CloseFrame.PROTOCOL_ERROR) */ public class InvalidFrameException extends InvalidDataException { diff --git a/src/main/java/org/java_websocket/exceptions/InvalidHandshakeException.java b/src/main/java/org/java_websocket/exceptions/InvalidHandshakeException.java index 7aa6881e0..12209ec6f 100644 --- a/src/main/java/org/java_websocket/exceptions/InvalidHandshakeException.java +++ b/src/main/java/org/java_websocket/exceptions/InvalidHandshakeException.java @@ -28,7 +28,7 @@ import org.java_websocket.framing.CloseFrame; /** - * exception which indicates that a invalid handshake was recieved (CloseFrame.PROTOCOL_ERROR) + * exception which indicates that a invalid handshake was received (CloseFrame.PROTOCOL_ERROR) */ public class InvalidHandshakeException extends InvalidDataException { diff --git a/src/main/java/org/java_websocket/framing/CloseFrame.java b/src/main/java/org/java_websocket/framing/CloseFrame.java index 61e85fbdd..229b24822 100644 --- a/src/main/java/org/java_websocket/framing/CloseFrame.java +++ b/src/main/java/org/java_websocket/framing/CloseFrame.java @@ -190,7 +190,7 @@ public CloseFrame() { */ public void setCode(int code) { this.code = code; - // CloseFrame.TLS_ERROR is not allowed to be transfered over the wire + // CloseFrame.TLS_ERROR is not allowed to be transferred over the wire if (code == CloseFrame.TLS_ERROR) { this.code = CloseFrame.NOCODE; this.reason = ""; diff --git a/src/main/java/org/java_websocket/framing/ControlFrame.java b/src/main/java/org/java_websocket/framing/ControlFrame.java index fd088df65..e8848ed84 100644 --- a/src/main/java/org/java_websocket/framing/ControlFrame.java +++ b/src/main/java/org/java_websocket/framing/ControlFrame.java @@ -45,16 +45,16 @@ public ControlFrame( Opcode opcode ) { @Override public void isValid() throws InvalidDataException { if( !isFin() ) { - throw new InvalidFrameException( "Control frame cant have fin==false set" ); + throw new InvalidFrameException( "Control frame can't have fin==false set" ); } if( isRSV1() ) { - throw new InvalidFrameException( "Control frame cant have rsv1==true set" ); + throw new InvalidFrameException( "Control frame can't have rsv1==true set" ); } if( isRSV2() ) { - throw new InvalidFrameException( "Control frame cant have rsv2==true set" ); + throw new InvalidFrameException( "Control frame can't have rsv2==true set" ); } if( isRSV3() ) { - throw new InvalidFrameException( "Control frame cant have rsv3==true set" ); + throw new InvalidFrameException( "Control frame can't have rsv3==true set" ); } } } diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index f7349a6d7..3dd79028f 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -718,7 +718,7 @@ protected boolean removeConnection( WebSocket ws ) { removed = this.connections.remove( ws ); } else { //Don't throw an assert error if the ws is not in the list. e.g. when the other endpoint did not send any handshake. see #512 - log.trace("Removing connection which is not in the connections collection! Possible no handshake recieved! {}", ws); + log.trace("Removing connection which is not in the connections collection! Possible no handshake received! {}", ws); } } if( isclosed.get() && connections.isEmpty() ) { @@ -823,14 +823,14 @@ public InetSocketAddress getRemoteSocketAddress( WebSocket conn ) { } /** Called after an opening handshake has been performed and the given websocket is ready to be written on. - * @param conn The WebSocket instance this event is occuring on. + * @param conn The WebSocket instance this event is occurring on. * @param handshake The handshake of the websocket instance */ public abstract void onOpen( WebSocket conn, ClientHandshake handshake ); /** * Called after the websocket connection has been closed. * - * @param conn The WebSocket instance this event is occuring on. + * @param conn The WebSocket instance this event is occurring on. * @param code * The codes can be looked up here: {@link CloseFrame} * @param reason @@ -843,7 +843,7 @@ public InetSocketAddress getRemoteSocketAddress( WebSocket conn ) { * Callback for string messages received from the remote host * * @see #onMessage(WebSocket, ByteBuffer) - * @param conn The WebSocket instance this event is occuring on. + * @param conn The WebSocket instance this event is occurring on. * @param message The UTF-8 decoded message that was received. **/ public abstract void onMessage( WebSocket conn, String message ); @@ -860,7 +860,7 @@ public InetSocketAddress getRemoteSocketAddress( WebSocket conn ) { /** * Called when the server started up successfully. * - * If any error occured, onError is called instead. + * If any error occurred, onError is called instead. */ public abstract void onStart(); diff --git a/src/main/java/org/java_websocket/util/Base64.java b/src/main/java/org/java_websocket/util/Base64.java index ceda3a577..9ca6b5469 100644 --- a/src/main/java/org/java_websocket/util/Base64.java +++ b/src/main/java/org/java_websocket/util/Base64.java @@ -97,7 +97,7 @@ * RFC3548. *

  • Throws exceptions instead of returning null values. Because some operations * (especially those that may permit the GZIP option) use IO streams, there - * is a possiblity of an java.io.IOException being thrown. After some discussion and + * is a possibility of an java.io.IOException being thrown. After some discussion and * thought, I've changed the behavior of the methods to throw java.io.IOExceptions * rather than return null if ever there's an error. I think this is more * appropriate, though it will require some changes to your code. Sorry, @@ -462,7 +462,7 @@ private Base64(){} /** * Encodes up to the first three bytes of array threeBytes * and returns a four-byte array in Base64 notation. - * The actual number of significant bytes in your array is + * The actual number of significan't bytes in your array is * given by numSigBytes. * The array threeBytes needs only be as big as * numSigBytes. @@ -470,7 +470,7 @@ private Base64(){} * * @param b4 A reusable byte array to reduce array instantiation * @param threeBytes the array to convert - * @param numSigBytes the number of significant bytes in your array + * @param numSigBytes the number of significan't bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ @@ -487,17 +487,17 @@ private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, * anywhere along their length by specifying * srcOffset and destOffset. * This method does not check to make sure your arrays - * are large enough to accomodate srcOffset + 3 for + * are large enough to accommodate srcOffset + 3 for * the source array or destOffset + 4 for * the destination array. - * The actual number of significant bytes in your array is + * The actual number of significan't bytes in your array is * given by numSigBytes.

    *

    This is the lowest level of the encoding methods with * all possible parameters.

    * * @param source the array to convert * @param srcOffset the index where conversion begins - * @param numSigBytes the number of significant bytes in your array + * @param numSigBytes the number of significan't bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the destination array @@ -517,7 +517,7 @@ private static byte[] encode3to4( // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two - // significant bytes passed in the array. + // significan't bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) @@ -762,7 +762,7 @@ public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int op * anywhere along their length by specifying * srcOffset and destOffset. * This method does not check to make sure your arrays - * are large enough to accomodate srcOffset + 4 for + * are large enough to accommodate srcOffset + 4 for * the source array or destOffset + 3 for * the destination array. * This method returns the actual number of bytes that diff --git a/src/test/java/org/java_websocket/framing/BinaryFrameTest.java b/src/test/java/org/java_websocket/framing/BinaryFrameTest.java index 994660652..a7cf127b6 100644 --- a/src/test/java/org/java_websocket/framing/BinaryFrameTest.java +++ b/src/test/java/org/java_websocket/framing/BinaryFrameTest.java @@ -42,7 +42,7 @@ public void testConstructor() { BinaryFrame frame = new BinaryFrame(); assertEquals("Opcode must be equal", Opcode.BINARY , frame.getOpcode()); assertEquals("Fin must be set", true , frame.isFin()); - assertEquals("TransferedMask must not be set", false , frame.getTransfereMasked()); + assertEquals("transferredMask must not be set", false , frame.getTransfereMasked()); assertEquals("Payload must be empty", 0 , frame.getPayloadData().capacity()); assertEquals("RSV1 must be false", false , frame.isRSV1()); assertEquals("RSV2 must be false", false , frame.isRSV2()); diff --git a/src/test/java/org/java_websocket/framing/CloseFrameTest.java b/src/test/java/org/java_websocket/framing/CloseFrameTest.java index 1246e926c..33a9cc4d0 100644 --- a/src/test/java/org/java_websocket/framing/CloseFrameTest.java +++ b/src/test/java/org/java_websocket/framing/CloseFrameTest.java @@ -42,7 +42,7 @@ public void testConstructor() { CloseFrame frame = new CloseFrame(); assertEquals("Opcode must be equal", Opcode.CLOSING, frame.getOpcode()); assertEquals("Fin must be set", true, frame.isFin()); - assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); + assertEquals("transferredMask must not be set", false, frame.getTransfereMasked()); assertEquals("Payload must be 2 (close code)", 2, frame.getPayloadData().capacity()); assertEquals("RSV1 must be false", false, frame.isRSV1()); assertEquals("RSV2 must be false", false, frame.isRSV2()); diff --git a/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java b/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java index a6ea68e11..6319fcca5 100644 --- a/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java +++ b/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java @@ -42,7 +42,7 @@ public void testConstructor() { ContinuousFrame frame = new ContinuousFrame(); assertEquals("Opcode must be equal", Opcode.CONTINUOUS , frame.getOpcode()); assertEquals("Fin must be set", true , frame.isFin()); - assertEquals("TransferedMask must not be set", false , frame.getTransfereMasked()); + assertEquals("transferredMask must not be set", false , frame.getTransfereMasked()); assertEquals("Payload must be empty", 0 , frame.getPayloadData().capacity()); assertEquals("RSV1 must be false", false , frame.isRSV1()); assertEquals("RSV2 must be false", false , frame.isRSV2()); diff --git a/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java b/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java index fbfaa256e..6a29abe8d 100644 --- a/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java +++ b/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java @@ -44,7 +44,7 @@ public void testDefaultValues() { FramedataImpl1 binary = FramedataImpl1.get(Opcode.BINARY); assertEquals("Opcode must be equal", Opcode.BINARY, binary.getOpcode()); assertEquals("Fin must be set", true, binary.isFin()); - assertEquals("TransferedMask must not be set", false, binary.getTransfereMasked()); + assertEquals("transferredMask must not be set", false, binary.getTransfereMasked()); assertEquals("Payload must be empty", 0, binary.getPayloadData().capacity()); assertEquals("RSV1 must be false", false, binary.isRSV1()); assertEquals("RSV2 must be false", false, binary.isRSV2()); @@ -79,7 +79,7 @@ public void testSetters() { frame.setFin(false); assertEquals("Fin must not be set", false, frame.isFin()); frame.setTransferemasked(true); - assertEquals("TransferedMask must be set", true, frame.getTransfereMasked()); + assertEquals("transferredMask must be set", true, frame.getTransfereMasked()); ByteBuffer buffer = ByteBuffer.allocate(100); frame.setPayload(buffer); assertEquals("Payload must be of size 100", 100, frame.getPayloadData().capacity()); diff --git a/src/test/java/org/java_websocket/framing/PingFrameTest.java b/src/test/java/org/java_websocket/framing/PingFrameTest.java index 2056d31b0..ffcd2070b 100644 --- a/src/test/java/org/java_websocket/framing/PingFrameTest.java +++ b/src/test/java/org/java_websocket/framing/PingFrameTest.java @@ -42,7 +42,7 @@ public void testConstructor() { PingFrame frame = new PingFrame(); assertEquals("Opcode must be equal", Opcode.PING , frame.getOpcode()); assertEquals("Fin must be set", true , frame.isFin()); - assertEquals("TransferedMask must not be set", false , frame.getTransfereMasked()); + assertEquals("transferredMask must not be set", false , frame.getTransfereMasked()); assertEquals("Payload must be empty", 0 , frame.getPayloadData().capacity()); assertEquals("RSV1 must be false", false , frame.isRSV1()); assertEquals("RSV2 must be false", false , frame.isRSV2()); diff --git a/src/test/java/org/java_websocket/framing/PongFrameTest.java b/src/test/java/org/java_websocket/framing/PongFrameTest.java index 03bb316ed..c19a3ca57 100644 --- a/src/test/java/org/java_websocket/framing/PongFrameTest.java +++ b/src/test/java/org/java_websocket/framing/PongFrameTest.java @@ -44,7 +44,7 @@ public void testConstructor() { PongFrame frame = new PongFrame(); assertEquals("Opcode must be equal", Opcode.PONG , frame.getOpcode()); assertEquals("Fin must be set", true , frame.isFin()); - assertEquals("TransferedMask must not be set", false , frame.getTransfereMasked()); + assertEquals("transferredMask must not be set", false , frame.getTransfereMasked()); assertEquals("Payload must be empty", 0 , frame.getPayloadData().capacity()); assertEquals("RSV1 must be false", false , frame.isRSV1()); assertEquals("RSV2 must be false", false , frame.isRSV2()); diff --git a/src/test/java/org/java_websocket/framing/TextFrameTest.java b/src/test/java/org/java_websocket/framing/TextFrameTest.java index 433e89962..6c1a07b7f 100644 --- a/src/test/java/org/java_websocket/framing/TextFrameTest.java +++ b/src/test/java/org/java_websocket/framing/TextFrameTest.java @@ -44,7 +44,7 @@ public void testConstructor() { TextFrame frame = new TextFrame(); assertEquals("Opcode must be equal", Opcode.TEXT , frame.getOpcode()); assertEquals("Fin must be set", true , frame.isFin()); - assertEquals("TransferedMask must not be set", false , frame.getTransfereMasked()); + assertEquals("transferredMask must not be set", false , frame.getTransfereMasked()); assertEquals("Payload must be empty", 0 , frame.getPayloadData().capacity()); assertEquals("RSV1 must be false", false , frame.isRSV1()); assertEquals("RSV2 must be false", false , frame.isRSV2()); From 92979c530566c4cda1f194e56b5fed584a01db87 Mon Sep 17 00:00:00 2001 From: dota17 Date: Tue, 30 Jun 2020 09:02:20 +0800 Subject: [PATCH 052/165] Restore --- autobahn reports/clients/index.html | 158 +++++++++--------- .../java/org/java_websocket/util/Base64.java | 10 +- 2 files changed, 84 insertions(+), 84 deletions(-) diff --git a/autobahn reports/clients/index.html b/autobahn reports/clients/index.html index 4caa128b9..5fa8f93d7 100644 --- a/autobahn reports/clients/index.html +++ b/autobahn reports/clients/index.html @@ -2246,13 +2246,13 @@

    Case 6.2.4

    Case 6.3.1

    Up -

    Case Description

    Send invalid UTF-8 text message unfragmented.

    MESSAGE:
    κόσμε�edited
    cebae1bdb9cf83cebcceb5eda080656469746564

    +

    Case Description

    Send invalid UTF-8 text message unfragmented.

    MESSAGE:
    κόσμε���edited
    cebae1bdb9cf83cebcceb5eda080656469746564

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.3.2

    Up -

    Case Description

    Send invalid UTF-8 text message in fragments of 1 octet, resulting in frames ending on positions which are not code point ends.

    MESSAGE:
    κόσμε�edited
    cebae1bdb9cf83cebcceb5eda080656469746564

    +

    Case Description

    Send invalid UTF-8 text message in fragments of 1 octet, resulting in frames ending on positions which are not code point ends.

    MESSAGE:
    κόσμε���edited
    cebae1bdb9cf83cebcceb5eda080656469746564

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    @@ -2263,7 +2263,7 @@

    Case 6.4.1

    Note that PART1 and PART3 are valid UTF-8 in themselves, PART2 is a 0x11000 encoded as in the UTF-8 integer encoding scheme, but the codepoint is invalid (out of range).

    MESSAGE PARTS:
    PART1 = κόσμε (cebae1bdb9cf83cebcceb5)
    -PART2 = ���� (f4908080)
    +PART2 = ���� (f4908080)
    PART3 = edited (656469746564)

    Case Expectation

    The first frame is accepted, we expect to timeout on the first wait. The 2nd frame should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.

    @@ -2273,9 +2273,9 @@

    Case 6.4.2

    Up

    Case Description

    Same as Case 6.4.1, but in 2nd frame, we send only up to and including the octet making the complete payload invalid.

    MESSAGE PARTS:
    -PART1 = κόσμε� (cebae1bdb9cf83cebcceb5f4)
    -PART2 = � (90)
    -PART3 = ��edited (8080656469746564)
    +PART1 = κόσμε� (cebae1bdb9cf83cebcceb5f4)
    +PART2 = � (90)
    +PART3 = ��edited (8080656469746564)

    Case Expectation

    The first frame is accepted, we expect to timeout on the first wait. The 2nd frame should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.


    @@ -2285,7 +2285,7 @@

    Case 6.4.3

    Case Description

    Same as Case 6.4.1, but we send message not in 3 frames, but in 3 chops of the same message frame.

    MESSAGE PARTS:
    PART1 = κόσμε (cebae1bdb9cf83cebcceb5)
    -PART2 = ���� (f4908080)
    +PART2 = ���� (f4908080)
    PART3 = edited (656469746564)

    Case Expectation

    The first chop is accepted, we expect to timeout on the first wait. The 2nd chop should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.

    @@ -2295,8 +2295,8 @@

    Case 6.4.4

    Up

    Case Description

    Same as Case 6.4.2, but we send message not in 3 frames, but in 3 chops of the same message frame.

    MESSAGE PARTS:
    -PART1 = κόσμε� (cebae1bdb9cf83cebcceb5f4)
    -PART2 = � (90)
    +PART1 = κόσμε� (cebae1bdb9cf83cebcceb5f4)
    +PART2 = � (90)
    PART3 = ()

    Case Expectation

    The first chop is accepted, we expect to timeout on the first wait. The 2nd chop should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.

    @@ -2310,7 +2310,7 @@

    Case 6.5.1

    Case 6.6.1

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    ce

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    ce

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    @@ -2322,13 +2322,13 @@

    Case 6.6.2

    Case 6.6.3

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    κ�
    cebae1

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    κ�
    cebae1

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.6.4

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    κ�
    cebae1bd

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    κ�
    cebae1bd

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    @@ -2340,7 +2340,7 @@

    Case 6.6.5

    Case 6.6.6

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    κό�
    cebae1bdb9cf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    κό�
    cebae1bdb9cf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    @@ -2352,7 +2352,7 @@

    Case 6.6.7

    Case 6.6.8

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    κόσ�
    cebae1bdb9cf83ce

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    κόσ�
    cebae1bdb9cf83ce

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    @@ -2364,7 +2364,7 @@

    Case 6.6.9

    Case 6.6.10

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    κόσμ�
    cebae1bdb9cf83cebcce

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    κόσμ�
    cebae1bdb9cf83cebcce

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    @@ -2400,13 +2400,13 @@

    Case 6.7.4

    Case 6.8.1

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����
    f888808080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����
    f888808080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.8.2

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    fc8480808080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    fc8480808080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    @@ -2436,19 +2436,19 @@

    Case 6.9.4

    Case 6.10.1

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    f7bfbfbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    f7bfbfbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.10.2

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����
    fbbfbfbfbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����
    fbbfbfbfbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.10.3

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    fdbfbfbfbfbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    fdbfbfbfbfbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    @@ -2478,349 +2478,349 @@

    Case 6.11.4

    Case 6.11.5

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    f4908080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    f4908080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.12.1

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    80

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    80

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.12.2

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    bf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    bf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.12.3

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    80bf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    80bf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.12.4

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    80bf80

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    80bf80

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.12.5

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    80bf80bf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    80bf80bf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.12.6

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����
    80bf80bf80

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����
    80bf80bf80

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.12.7

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    80bf80bf80bf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    80bf80bf80bf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.12.8

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���������������������������������������������������������������
    808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbe

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���������������������������������������������������������������
    808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbe

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.13.1

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �
    c020c120c220c320c420c520c620c720c820c920ca20cb20cc20cd20ce20cf20d020d120d220d320d420d520d620d720d820d920da20db20dc20dd20de20

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �
    c020c120c220c320c420c520c620c720c820c920ca20cb20cc20cd20ce20cf20d020d120d220d320d420d520d620d720d820d920da20db20dc20dd20de20

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.13.2

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    � � � � � � � � � � � � � � �
    e020e120e220e320e420e520e620e720e820e920ea20eb20ec20ed20ee20

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    � � � � � � � � � � � � � � �
    e020e120e220e320e420e520e620e720e820e920ea20eb20ec20ed20ee20

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.13.3

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    � � � � � � �
    f020f120f220f320f420f520f620

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    � � � � � � �
    f020f120f220f320f420f520f620

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.13.4

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    � � �
    f820f920fa20

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    � � �
    f820f920fa20

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.13.5

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    fc20

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    fc20

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.14.1

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    c0

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    c0

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.14.2

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    e080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    e080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.14.3

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    f08080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    f08080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.14.4

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    f8808080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    f8808080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.14.5

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����
    fc80808080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����
    fc80808080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.14.6

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    df

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    df

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.14.7

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    efbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    efbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.14.8

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    f7bfbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    f7bfbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.14.9

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    fbbfbfbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    fbbfbfbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.14.10

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����
    fdbfbfbfbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����
    fdbfbfbfbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.15.1

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����������������������������
    c0e080f08080f8808080fc80808080dfefbff7bfbffbbfbfbffdbfbfbfbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����������������������������
    c0e080f08080f8808080fc80808080dfefbff7bfbffbbfbfbffdbfbfbfbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.16.1

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    fe

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    fe

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.16.2

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    ff

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    ff

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.16.3

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    fefeffff

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    fefeffff

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.17.1

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    c0af

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    c0af

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.17.2

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    e080af

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    e080af

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.17.3

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    f08080af

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    f08080af

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.17.4

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����
    f8808080af

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����
    f8808080af

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.17.5

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    fc80808080af

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    fc80808080af

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.18.1

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    c1bf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    c1bf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.18.2

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    e09fbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    e09fbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.18.3

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    f08fbfbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    f08fbfbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.18.4

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����
    f887bfbfbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����
    f887bfbfbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.18.5

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    fc83bfbfbfbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    fc83bfbfbfbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.19.1

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    c080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    c080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.19.2

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    e08080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    e08080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.19.3

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    f0808080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ����
    f0808080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.19.4

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����
    f880808080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �����
    f880808080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.19.5

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    fc8080808080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    fc8080808080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.20.1

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    eda080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    eda080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.20.2

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    edadbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    edadbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.20.3

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    edae80

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    edae80

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.20.4

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    edafbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    edafbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.20.5

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    edb080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    edb080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.20.6

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    edbe80

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    edbe80

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.20.7

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    �
    edbfbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ���
    edbfbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.21.1

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    eda080edb080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    eda080edb080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.21.2

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    eda080edbfbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    eda080edbfbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.21.3

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    edadbfedb080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    edadbfedb080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.21.4

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    edadbfedbfbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    edadbfedbfbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.21.5

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    edae80edb080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    edae80edb080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.21.6

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    edae80edbfbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    edae80edbfbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.21.7

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    edafbfedb080

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    edafbfedb080

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    Case 6.21.8

    Up -

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ��
    edafbfedbfbf

    +

    Case Description

    Send a text message with payload which is not valid UTF-8 in one fragment.

    MESSAGE:
    ������
    edafbfedbfbf

    Case Expectation

    The connection is failed immediately, since the payload is not valid UTF-8.


    @@ -3067,7 +3067,7 @@

    Case 7.1.5

    Case 7.1.6

    Up

    Case Description

    Send 256K message followed by close then a ping

    -

    Case Expectation

    Case outcome depends on implimentation defined close behavior. Message and close frame are sent back to back. If the close frame is processed before the text message write is complete (as can happen in asyncronous processing models) the close frame is processed first and the text message may not be received or may only be partially received.

    +

    Case Expectation

    Case outcome depends on implimentation defined close behavior. Message and close frame are sent back to back. If the close frame is processed before the text message write is complete (as can happen in asyncronous processing models) the close frame is processed first and the text message may not be recieved or may only be partially recieved.


    Case 7.3.1

    diff --git a/src/main/java/org/java_websocket/util/Base64.java b/src/main/java/org/java_websocket/util/Base64.java index 9ca6b5469..d156c600f 100644 --- a/src/main/java/org/java_websocket/util/Base64.java +++ b/src/main/java/org/java_websocket/util/Base64.java @@ -462,7 +462,7 @@ private Base64(){} /** * Encodes up to the first three bytes of array threeBytes * and returns a four-byte array in Base64 notation. - * The actual number of significan't bytes in your array is + * The actual number of significant bytes in your array is * given by numSigBytes. * The array threeBytes needs only be as big as * numSigBytes. @@ -470,7 +470,7 @@ private Base64(){} * * @param b4 A reusable byte array to reduce array instantiation * @param threeBytes the array to convert - * @param numSigBytes the number of significan't bytes in your array + * @param numSigBytes the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ @@ -490,14 +490,14 @@ private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, * are large enough to accommodate srcOffset + 3 for * the source array or destOffset + 4 for * the destination array. - * The actual number of significan't bytes in your array is + * The actual number of significant bytes in your array is * given by numSigBytes.

    *

    This is the lowest level of the encoding methods with * all possible parameters.

    * * @param source the array to convert * @param srcOffset the index where conversion begins - * @param numSigBytes the number of significan't bytes in your array + * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the destination array @@ -517,7 +517,7 @@ private static byte[] encode3to4( // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two - // significan't bytes passed in the array. + // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) From 5f6e8d5487ecb0a176902776a31af3a6be7dd9f8 Mon Sep 17 00:00:00 2001 From: dota17 Date: Tue, 30 Jun 2020 10:14:15 +0800 Subject: [PATCH 053/165] Restore --- src/test/java/org/java_websocket/framing/BinaryFrameTest.java | 2 +- src/test/java/org/java_websocket/framing/CloseFrameTest.java | 2 +- .../java/org/java_websocket/framing/ContinuousFrameTest.java | 2 +- .../java/org/java_websocket/framing/FramedataImpl1Test.java | 4 ++-- src/test/java/org/java_websocket/framing/PingFrameTest.java | 2 +- src/test/java/org/java_websocket/framing/PongFrameTest.java | 2 +- src/test/java/org/java_websocket/framing/TextFrameTest.java | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/test/java/org/java_websocket/framing/BinaryFrameTest.java b/src/test/java/org/java_websocket/framing/BinaryFrameTest.java index a7cf127b6..994660652 100644 --- a/src/test/java/org/java_websocket/framing/BinaryFrameTest.java +++ b/src/test/java/org/java_websocket/framing/BinaryFrameTest.java @@ -42,7 +42,7 @@ public void testConstructor() { BinaryFrame frame = new BinaryFrame(); assertEquals("Opcode must be equal", Opcode.BINARY , frame.getOpcode()); assertEquals("Fin must be set", true , frame.isFin()); - assertEquals("transferredMask must not be set", false , frame.getTransfereMasked()); + assertEquals("TransferedMask must not be set", false , frame.getTransfereMasked()); assertEquals("Payload must be empty", 0 , frame.getPayloadData().capacity()); assertEquals("RSV1 must be false", false , frame.isRSV1()); assertEquals("RSV2 must be false", false , frame.isRSV2()); diff --git a/src/test/java/org/java_websocket/framing/CloseFrameTest.java b/src/test/java/org/java_websocket/framing/CloseFrameTest.java index 33a9cc4d0..1246e926c 100644 --- a/src/test/java/org/java_websocket/framing/CloseFrameTest.java +++ b/src/test/java/org/java_websocket/framing/CloseFrameTest.java @@ -42,7 +42,7 @@ public void testConstructor() { CloseFrame frame = new CloseFrame(); assertEquals("Opcode must be equal", Opcode.CLOSING, frame.getOpcode()); assertEquals("Fin must be set", true, frame.isFin()); - assertEquals("transferredMask must not be set", false, frame.getTransfereMasked()); + assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); assertEquals("Payload must be 2 (close code)", 2, frame.getPayloadData().capacity()); assertEquals("RSV1 must be false", false, frame.isRSV1()); assertEquals("RSV2 must be false", false, frame.isRSV2()); diff --git a/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java b/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java index 6319fcca5..a6ea68e11 100644 --- a/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java +++ b/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java @@ -42,7 +42,7 @@ public void testConstructor() { ContinuousFrame frame = new ContinuousFrame(); assertEquals("Opcode must be equal", Opcode.CONTINUOUS , frame.getOpcode()); assertEquals("Fin must be set", true , frame.isFin()); - assertEquals("transferredMask must not be set", false , frame.getTransfereMasked()); + assertEquals("TransferedMask must not be set", false , frame.getTransfereMasked()); assertEquals("Payload must be empty", 0 , frame.getPayloadData().capacity()); assertEquals("RSV1 must be false", false , frame.isRSV1()); assertEquals("RSV2 must be false", false , frame.isRSV2()); diff --git a/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java b/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java index 6a29abe8d..fbfaa256e 100644 --- a/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java +++ b/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java @@ -44,7 +44,7 @@ public void testDefaultValues() { FramedataImpl1 binary = FramedataImpl1.get(Opcode.BINARY); assertEquals("Opcode must be equal", Opcode.BINARY, binary.getOpcode()); assertEquals("Fin must be set", true, binary.isFin()); - assertEquals("transferredMask must not be set", false, binary.getTransfereMasked()); + assertEquals("TransferedMask must not be set", false, binary.getTransfereMasked()); assertEquals("Payload must be empty", 0, binary.getPayloadData().capacity()); assertEquals("RSV1 must be false", false, binary.isRSV1()); assertEquals("RSV2 must be false", false, binary.isRSV2()); @@ -79,7 +79,7 @@ public void testSetters() { frame.setFin(false); assertEquals("Fin must not be set", false, frame.isFin()); frame.setTransferemasked(true); - assertEquals("transferredMask must be set", true, frame.getTransfereMasked()); + assertEquals("TransferedMask must be set", true, frame.getTransfereMasked()); ByteBuffer buffer = ByteBuffer.allocate(100); frame.setPayload(buffer); assertEquals("Payload must be of size 100", 100, frame.getPayloadData().capacity()); diff --git a/src/test/java/org/java_websocket/framing/PingFrameTest.java b/src/test/java/org/java_websocket/framing/PingFrameTest.java index ffcd2070b..2056d31b0 100644 --- a/src/test/java/org/java_websocket/framing/PingFrameTest.java +++ b/src/test/java/org/java_websocket/framing/PingFrameTest.java @@ -42,7 +42,7 @@ public void testConstructor() { PingFrame frame = new PingFrame(); assertEquals("Opcode must be equal", Opcode.PING , frame.getOpcode()); assertEquals("Fin must be set", true , frame.isFin()); - assertEquals("transferredMask must not be set", false , frame.getTransfereMasked()); + assertEquals("TransferedMask must not be set", false , frame.getTransfereMasked()); assertEquals("Payload must be empty", 0 , frame.getPayloadData().capacity()); assertEquals("RSV1 must be false", false , frame.isRSV1()); assertEquals("RSV2 must be false", false , frame.isRSV2()); diff --git a/src/test/java/org/java_websocket/framing/PongFrameTest.java b/src/test/java/org/java_websocket/framing/PongFrameTest.java index c19a3ca57..03bb316ed 100644 --- a/src/test/java/org/java_websocket/framing/PongFrameTest.java +++ b/src/test/java/org/java_websocket/framing/PongFrameTest.java @@ -44,7 +44,7 @@ public void testConstructor() { PongFrame frame = new PongFrame(); assertEquals("Opcode must be equal", Opcode.PONG , frame.getOpcode()); assertEquals("Fin must be set", true , frame.isFin()); - assertEquals("transferredMask must not be set", false , frame.getTransfereMasked()); + assertEquals("TransferedMask must not be set", false , frame.getTransfereMasked()); assertEquals("Payload must be empty", 0 , frame.getPayloadData().capacity()); assertEquals("RSV1 must be false", false , frame.isRSV1()); assertEquals("RSV2 must be false", false , frame.isRSV2()); diff --git a/src/test/java/org/java_websocket/framing/TextFrameTest.java b/src/test/java/org/java_websocket/framing/TextFrameTest.java index 6c1a07b7f..433e89962 100644 --- a/src/test/java/org/java_websocket/framing/TextFrameTest.java +++ b/src/test/java/org/java_websocket/framing/TextFrameTest.java @@ -44,7 +44,7 @@ public void testConstructor() { TextFrame frame = new TextFrame(); assertEquals("Opcode must be equal", Opcode.TEXT , frame.getOpcode()); assertEquals("Fin must be set", true , frame.isFin()); - assertEquals("transferredMask must not be set", false , frame.getTransfereMasked()); + assertEquals("TransferedMask must not be set", false , frame.getTransfereMasked()); assertEquals("Payload must be empty", 0 , frame.getPayloadData().capacity()); assertEquals("RSV1 must be false", false , frame.isRSV1()); assertEquals("RSV2 must be false", false , frame.isRSV2()); From d64fce5f42309e663a6271ecd327dd53c19b5fe9 Mon Sep 17 00:00:00 2001 From: dota17 Date: Wed, 1 Jul 2020 16:09:22 +0800 Subject: [PATCH 054/165] WebSocket API moved to https://html.spec.whatwg.org/multipage/web-sockets.html . --- README.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.markdown b/README.markdown index 27682b6c5..dd77fa2eb 100644 --- a/README.markdown +++ b/README.markdown @@ -8,7 +8,7 @@ Java WebSockets This repository contains a barebones WebSocket server and client implementation written in 100% Java. The underlying classes are implemented `java.nio`, which allows for a non-blocking event-driven model (similar to the -[WebSocket API](http://dev.w3.org/html5/websockets/) for web browsers). +[WebSocket API](https://html.spec.whatwg.org/multipage/web-sockets.html) for web browsers). Implemented WebSocket protocol versions are: From 8dd34f08901da3a81ca52159d8c6ff51cba6df39 Mon Sep 17 00:00:00 2001 From: dota17 Date: Tue, 7 Jul 2020 20:35:18 +0800 Subject: [PATCH 055/165] Restore index.html --- README.markdown | 2 +- autobahn reports/servers/index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.markdown b/README.markdown index dd77fa2eb..51bf1c8a9 100644 --- a/README.markdown +++ b/README.markdown @@ -100,7 +100,7 @@ It is currently not possible to accept ws and wss connections at the same time v For some reason Firefox does not allow multiple connections to the same wss server if the server uses a different port than the default port (443). -If you want to use `wss` on the android platfrom you should take a look at [this](https://github.com/TooTallNate/Java-WebSocket/wiki/FAQ:-Secure-WebSockets#wss-on-android). +If you want to use `wss` on the android platform you should take a look at [this](https://github.com/TooTallNate/Java-WebSocket/wiki/FAQ:-Secure-WebSockets#wss-on-android). I ( @Davidiusdadi ) would be glad if you would give some feedback whether wss is working fine for you or not. diff --git a/autobahn reports/servers/index.html b/autobahn reports/servers/index.html index 1a8d01e2b..d9056d0b3 100644 --- a/autobahn reports/servers/index.html +++ b/autobahn reports/servers/index.html @@ -4112,7 +4112,7 @@

    Case 7.1.5

    Case 7.1.6

    Up

    Case Description

    Send 256K message followed by close then a ping

    -

    Case Expectation

    Case outcome depends on implementation defined close behavior. Message and close frame are sent back to back. If the close frame is processed before the text message write is complete (as can happen in asynchronous processing models) the close frame is processed first and the text message may not be received or may only be partially received.

    +

    Case Expectation

    Case outcome depends on implementation defined close behavior. Message and close frame are sent back to back. If the close frame is processed before the text message write is complete (as can happen in asynchronous processing models) the close frame is processed first and the text message may not be received or may only be partially recieved.


    Case 7.3.1

    From b320ee781c5ea503ec4cb1a6f1d1a6a6b579e811 Mon Sep 17 00:00:00 2001 From: dota17 Date: Sat, 18 Jul 2020 09:56:23 +0800 Subject: [PATCH 056/165] Update the document of PerMessageDeflateExtension --- .../PerMessageDeflateExtension.java | 45 ++++++++++++++++++- .../framing/FramedataImpl1.java | 6 +-- .../PerMessageDeflateExtensionTest.java | 14 ++++++ 3 files changed, 60 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index 296a20b76..7f86f3d6f 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -6,7 +6,13 @@ import org.java_websocket.extensions.CompressionExtension; import org.java_websocket.extensions.ExtensionRequestData; import org.java_websocket.extensions.IExtension; -import org.java_websocket.framing.*; +import org.java_websocket.framing.BinaryFrame; +import org.java_websocket.framing.CloseFrame; +import org.java_websocket.framing.ContinuousFrame; +import org.java_websocket.framing.DataFrame; +import org.java_websocket.framing.Framedata; +import org.java_websocket.framing.FramedataImpl1; +import org.java_websocket.framing.TextFrame; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; @@ -16,6 +22,12 @@ import java.util.zip.Deflater; import java.util.zip.Inflater; +/** + * PerMessage Deflate Extension (7. The "permessage-deflate" Extension in + * RFC 7692). + * + * @see 7. The "permessage-deflate" Extension in RFC 7692 + */ public class PerMessageDeflateExtension extends CompressionExtension { // Name of the extension as registered by IETF https://tools.ietf.org/html/rfc7692#section-9. @@ -28,7 +40,7 @@ public class PerMessageDeflateExtension extends CompressionExtension { private static final String CLIENT_MAX_WINDOW_BITS = "client_max_window_bits"; private static final int serverMaxWindowBits = 1 << 15; private static final int clientMaxWindowBits = 1 << 15; - private static final byte[] TAIL_BYTES = {0x00, 0x00, (byte)0xFF, (byte)0xFF}; + private static final byte[] TAIL_BYTES = { (byte)0x00, (byte)0x00, (byte)0xFF, (byte)0xFF }; private static final int BUFFER_SIZE = 1 << 10; private boolean serverNoContextTakeover = true; @@ -40,6 +52,24 @@ public class PerMessageDeflateExtension extends CompressionExtension { private Inflater inflater = new Inflater(true); private Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); + /** + * + * @return serverNoContextTakeover + */ + public boolean isServerNoContextTakeover() + { + return serverNoContextTakeover; + } + + /** + * + * @return clientNoContextTakeover + */ + public boolean isClientNoContextTakeover() + { + return clientNoContextTakeover; + } + /* An endpoint uses the following algorithm to decompress a message. 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the @@ -93,6 +123,12 @@ We can check the getRemaining() method to see whether the data we supplied has b ((FramedataImpl1) inputFrame).setPayload(ByteBuffer.wrap(output.toByteArray(), 0, output.size())); } + /** + * + * @param data the bytes of date + * @param outputBuffer the output stream + * @throws DataFormatException + */ private void decompress(byte[] data, ByteArrayOutputStream outputBuffer) throws DataFormatException{ inflater.setInput(data); byte[] buffer = new byte[BUFFER_SIZE]; @@ -146,6 +182,11 @@ public void encodeFrame(Framedata inputFrame) { ((FramedataImpl1) inputFrame).setPayload(ByteBuffer.wrap(outputBytes, 0, outputLength)); } + /** + * + * @param data the bytes of data + * @return true if the data is OK + */ private boolean endsWithTail(byte[] data){ if(data.length < 4) return false; diff --git a/src/main/java/org/java_websocket/framing/FramedataImpl1.java b/src/main/java/org/java_websocket/framing/FramedataImpl1.java index 21122fdeb..d445ba850 100644 --- a/src/main/java/org/java_websocket/framing/FramedataImpl1.java +++ b/src/main/java/org/java_websocket/framing/FramedataImpl1.java @@ -183,7 +183,7 @@ public void setFin(boolean fin) { /** * Set the rsv1 of this frame to the provided boolean * - * @param rsv1 true if fin has to be set + * @param rsv1 true if rsv1 has to be set */ public void setRSV1(boolean rsv1) { this.rsv1 = rsv1; @@ -192,7 +192,7 @@ public void setRSV1(boolean rsv1) { /** * Set the rsv2 of this frame to the provided boolean * - * @param rsv2 true if fin has to be set + * @param rsv2 true if rsv2 has to be set */ public void setRSV2(boolean rsv2) { this.rsv2 = rsv2; @@ -201,7 +201,7 @@ public void setRSV2(boolean rsv2) { /** * Set the rsv3 of this frame to the provided boolean * - * @param rsv3 true if fin has to be set + * @param rsv3 true if rsv3 has to be set */ public void setRSV3(boolean rsv3) { this.rsv3 = rsv3; diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index f1f665b60..1ae7cc232 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -117,4 +117,18 @@ public void testToString() throws Exception { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); assertEquals( "PerMessageDeflateExtension", deflateExtension.toString() ); } + + @Test + public void testIsServerNoContextTakeover() + { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertTrue(deflateExtension.isServerNoContextTakeover()); + } + + @Test + public void testIsClientNoContextTakeover() + { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertFalse(deflateExtension.isClientNoContextTakeover()); + } } From ad97b03508c34795a10b4a46537347667bada07d Mon Sep 17 00:00:00 2001 From: dota17 Date: Sat, 18 Jul 2020 14:49:14 +0800 Subject: [PATCH 057/165] Update the value of boolean --- .../PerMessageDeflateExtension.java | 18 +++++++++++++ .../PerMessageDeflateExtensionTest.java | 27 ++++++++++++++++--- 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index 7f86f3d6f..627ca875f 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -61,6 +61,15 @@ public boolean isServerNoContextTakeover() return serverNoContextTakeover; } + /** + * + * @param serverNoContextTakeover + */ + public void setServerNoContextTakeover(boolean serverNoContextTakeover) + { + this.serverNoContextTakeover = serverNoContextTakeover; + } + /** * * @return clientNoContextTakeover @@ -70,6 +79,15 @@ public boolean isClientNoContextTakeover() return clientNoContextTakeover; } + /** + * + * @param clientNoContextTakeover + */ + public void setClientNoContextTakeover(boolean clientNoContextTakeover) + { + this.clientNoContextTakeover = clientNoContextTakeover; + } + /* An endpoint uses the following algorithm to decompress a message. 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index 1ae7cc232..937edbef2 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -119,16 +119,35 @@ public void testToString() throws Exception { } @Test - public void testIsServerNoContextTakeover() - { + public void testIsServerNoContextTakeover() { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); assertTrue(deflateExtension.isServerNoContextTakeover()); } @Test - public void testIsClientNoContextTakeover() - { + public void testSetServerNoContextTakeover() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setServerNoContextTakeover(false); + assertFalse(deflateExtension.isServerNoContextTakeover()); + } + + @Test + public void testIsClientNoContextTakeover() { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); assertFalse(deflateExtension.isClientNoContextTakeover()); } + + @Test + public void testSetClientNoContextTakeover() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setClientNoContextTakeover(true); + assertTrue(deflateExtension.isClientNoContextTakeover()); + } + + @Test + public void testCopyInstance() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + IExtension newDeflateExtension = deflateExtension.copyInstance(); + assertEquals(deflateExtension.toString(), newDeflateExtension.toString()); + } } From 3070d82643187260a4f27b7fc86f45763365aa9b Mon Sep 17 00:00:00 2001 From: dota17 Date: Sat, 18 Jul 2020 14:54:10 +0800 Subject: [PATCH 058/165] Remove the unthrown exception. --- .../extensions/PerMessageDeflateExtensionTest.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index 937edbef2..a3fb60f94 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -8,7 +8,11 @@ import java.nio.ByteBuffer; -import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; public class PerMessageDeflateExtensionTest { @@ -113,7 +117,7 @@ public void testGetProvidedExtensionAsServer() { } @Test - public void testToString() throws Exception { + public void testToString() { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); assertEquals( "PerMessageDeflateExtension", deflateExtension.toString() ); } From 6eb1ddeaa4e7a37f8d4d632b6664aad03f384d6d Mon Sep 17 00:00:00 2001 From: dota17 Date: Wed, 22 Jul 2020 16:05:43 +0800 Subject: [PATCH 059/165] Add several testcases to improve the code coverage. --- .../java/org/java_websocket/AllTests.java | 1 + .../java_websocket/client/AllClientTests.java | 3 +- .../java_websocket/client/HeadersTest.java | 133 ++++++++++++++++++ .../org/java_websocket/util/Base64Test.java | 34 +++++ 4 files changed, 170 insertions(+), 1 deletion(-) create mode 100644 src/test/java/org/java_websocket/client/HeadersTest.java diff --git a/src/test/java/org/java_websocket/AllTests.java b/src/test/java/org/java_websocket/AllTests.java index 5ec33618e..9fae8d634 100644 --- a/src/test/java/org/java_websocket/AllTests.java +++ b/src/test/java/org/java_websocket/AllTests.java @@ -32,6 +32,7 @@ @RunWith(Suite.class) @Suite.SuiteClasses({ org.java_websocket.util.ByteBufferUtilsTest.class, + org.java_websocket.util.Base64Test.class, org.java_websocket.client.AllClientTests.class, org.java_websocket.drafts.AllDraftTests.class, org.java_websocket.issues.AllIssueTests.class, diff --git a/src/test/java/org/java_websocket/client/AllClientTests.java b/src/test/java/org/java_websocket/client/AllClientTests.java index 620afba99..9be07eefe 100644 --- a/src/test/java/org/java_websocket/client/AllClientTests.java +++ b/src/test/java/org/java_websocket/client/AllClientTests.java @@ -32,7 +32,8 @@ @RunWith(Suite.class) @Suite.SuiteClasses({ org.java_websocket.client.AttachmentTest.class, - org.java_websocket.client.SchemaCheckTest.class + org.java_websocket.client.SchemaCheckTest.class, + org.java_websocket.client.HeadersTest.class }) /** * Start all tests for the client diff --git a/src/test/java/org/java_websocket/client/HeadersTest.java b/src/test/java/org/java_websocket/client/HeadersTest.java new file mode 100644 index 000000000..962e3ae15 --- /dev/null +++ b/src/test/java/org/java_websocket/client/HeadersTest.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2010-2020 Nathan Rajlich + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.java_websocket.client; + +import org.java_websocket.handshake.ServerHandshake; +import org.junit.Test; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class HeadersTest { + + @Test + public void testHttpHeaders() throws URISyntaxException { + Map httpHeaders = new HashMap(); + httpHeaders.put("Cache-Control", "only-if-cached"); + httpHeaders.put("Keep-Alive", "1000"); + + WebSocketClient client = new WebSocketClient(new URI( "ws://localhost"), httpHeaders) { + @Override + public void onOpen( ServerHandshake handshakedata ) { + + } + + @Override + public void onMessage( String message ) { + + } + + @Override + public void onClose( int code, String reason, boolean remote ) { + + } + + @Override + public void onError( Exception ex ) { + + } + }; + + assertEquals("only-if-cached", client.removeHeader("Cache-Control")); + assertEquals("1000", client.removeHeader("Keep-Alive")); + } + + @Test + public void test_Add_RemoveHeaders() throws URISyntaxException { + Map httpHeaders = null; + WebSocketClient client = new WebSocketClient(new URI( "ws://localhost"), httpHeaders) { + @Override + public void onOpen( ServerHandshake handshakedata ) { + + } + + @Override + public void onMessage( String message ) { + + } + + @Override + public void onClose( int code, String reason, boolean remote ) { + + } + + @Override + public void onError( Exception ex ) { + + } + }; + client.addHeader("Cache-Control", "only-if-cached"); + assertEquals("only-if-cached", client.removeHeader("Cache-Control")); + assertNull(client.removeHeader("Cache-Control")); + + client.addHeader("Cache-Control", "only-if-cached"); + client.clearHeaders(); + assertNull(client.removeHeader("Cache-Control")); + } + + @Test + public void testGetURI() throws URISyntaxException { + WebSocketClient client = new WebSocketClient(new URI( "ws://localhost")) { + @Override + public void onOpen( ServerHandshake handshakedata ) { + + } + + @Override + public void onMessage( String message ) { + + } + + @Override + public void onClose( int code, String reason, boolean remote ) { + + } + + @Override + public void onError( Exception ex ) { + + } + }; + String actualURI = client.getURI().getScheme() + "://" + client.getURI().getHost(); + + assertEquals("ws://localhost", actualURI); + } +} diff --git a/src/test/java/org/java_websocket/util/Base64Test.java b/src/test/java/org/java_websocket/util/Base64Test.java index c6d43378e..7670e670b 100644 --- a/src/test/java/org/java_websocket/util/Base64Test.java +++ b/src/test/java/org/java_websocket/util/Base64Test.java @@ -41,6 +41,14 @@ public void testEncodeBytes() throws IOException { Assert.assertEquals("", Base64.encodeBytes(new byte[0])); Assert.assertEquals("QHE=", Base64.encodeBytes(new byte[] {49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 2, 2, 0)); + Assert.assertEquals("H4sIAAAAAAAAADMEALfv3IMBAAAA", + Base64.encodeBytes(new byte[] {49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 0, 1, 6)); + Assert.assertEquals("H4sIAAAAAAAAAHMoBABQHKKWAgAAAA==", + Base64.encodeBytes(new byte[] {49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 2, 2, 18)); + Assert.assertEquals("F63=", + Base64.encodeBytes(new byte[] {49, 121, 64, 113, 63, 43, -24, 62, 4, 48}, 2, 2, 32)); + Assert.assertEquals("6sg7---------6Bc0-0F699L-V----==", + Base64.encodeBytes(new byte[] {49, 121, 64, 113, 63, 43, -24, 62, 4, 48}, 2, 2, 34)); } @Test @@ -90,4 +98,30 @@ public void testEncodeBytesToBytes2() throws IOException { thrown.expect(IllegalArgumentException.class); Base64.encodeBytesToBytes(new byte[] {83, 10, 91, 67, 42, -1, 107, 62, 91, 67}, 8, 6, 26); } + + @Test + public void testEncodeBytesToBytes3() throws IOException { + byte[] src = new byte[] { + 113, 42, 123, 99, 10, -33, 75, 30, 88, 99, + 113, 42, 123, 99, 10, -33, 75, 31, 88, 99, + 113, 42, 123, 99, 10, -33, 75, 32, 88, 99, + 113, 42, 123, 99, 10, -33, 75, 33, 88, 99, + 113, 42, 123, 99, 10, -33, 75, 34, 88, 99, + 113, 42, 123, 99, 10, -33, 75, 35, 88, 99, + 55, 60 + }; + byte[] excepted = new byte[] { + 99, 83, 112, 55, 89, 119, 114, 102, 83, 120, + 53, 89, 89, 51, 69, 113, 101, 50, 77, 75, 51, + 48, 115, 102, 87, 71, 78, 120, 75, 110, 116, 106, + 67, 116, 57, 76, 73, 70, 104, 106, 99, 83, 112, + 55, 89, 119, 114, 102, 83, 121, 70, 89, 89, + 51, 69, 113, 101, 50, 77, 75, 51, 48, 115, + 105, 87, 71, 78, 120, 75, 110, 116, 106, 67, + 116, 57, 76, 10, 73, 49, 104, 106, 78, 122, + 119, 61 + }; + + Assert.assertArrayEquals(excepted, Base64.encodeBytesToBytes(src, 0, 62, 8)); + } } From b907661dacda1d0c410e4bef33d70457c18de572 Mon Sep 17 00:00:00 2001 From: dota17 Date: Wed, 22 Jul 2020 16:29:33 +0800 Subject: [PATCH 060/165] Format with the blanks. --- .../PerMessageDeflateExtension.java | 56 +++++++++---------- 1 file changed, 27 insertions(+), 29 deletions(-) diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index 627ca875f..40cba71d5 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -65,8 +65,7 @@ public boolean isServerNoContextTakeover() * * @param serverNoContextTakeover */ - public void setServerNoContextTakeover(boolean serverNoContextTakeover) - { + public void setServerNoContextTakeover(boolean serverNoContextTakeover) { this.serverNoContextTakeover = serverNoContextTakeover; } @@ -83,8 +82,7 @@ public boolean isClientNoContextTakeover() * * @param clientNoContextTakeover */ - public void setClientNoContextTakeover(boolean clientNoContextTakeover) - { + public void setClientNoContextTakeover(boolean clientNoContextTakeover) { this.clientNoContextTakeover = clientNoContextTakeover; } @@ -98,11 +96,11 @@ public void setClientNoContextTakeover(boolean clientNoContextTakeover) @Override public void decodeFrame(Framedata inputFrame) throws InvalidDataException { // Only DataFrames can be decompressed. - if(!(inputFrame instanceof DataFrame)) + if (!(inputFrame instanceof DataFrame)) return; // RSV1 bit must be set only for the first frame. - if(inputFrame.getOpcode() == Opcode.CONTINUOUS && inputFrame.isRSV1()) + if (inputFrame.getOpcode() == Opcode.CONTINUOUS && inputFrame.isRSV1()) throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "RSV1 bit can only be set for the first frame."); // Decompressed output buffer. @@ -118,15 +116,15 @@ We can check the getRemaining() method to see whether the data we supplied has b And if not, we just reset the inflater and decompress again. Note that this behavior doesn't occur if the message is "first compressed and then fragmented". */ - if(inflater.getRemaining() > 0){ + if (inflater.getRemaining() > 0) { inflater = new Inflater(true); decompress(inputFrame.getPayloadData().array(), output); } - if(inputFrame.isFin()) { + if (inputFrame.isFin()) { decompress(TAIL_BYTES, output); // If context takeover is disabled, inflater can be reset. - if(clientNoContextTakeover) + if (clientNoContextTakeover) inflater = new Inflater(true); } } catch (DataFormatException e) { @@ -134,7 +132,7 @@ We can check the getRemaining() method to see whether the data we supplied has b } // RSV1 bit must be cleared after decoding, so that other extensions don't throw an exception. - if(inputFrame.isRSV1()) + if (inputFrame.isRSV1()) ((DataFrame) inputFrame).setRSV1(false); // Set frames payload to the new decompressed data. @@ -147,12 +145,12 @@ We can check the getRemaining() method to see whether the data we supplied has b * @param outputBuffer the output stream * @throws DataFormatException */ - private void decompress(byte[] data, ByteArrayOutputStream outputBuffer) throws DataFormatException{ + private void decompress(byte[] data, ByteArrayOutputStream outputBuffer) throws DataFormatException { inflater.setInput(data); byte[] buffer = new byte[BUFFER_SIZE]; int bytesInflated; - while((bytesInflated = inflater.inflate(buffer)) > 0){ + while ((bytesInflated = inflater.inflate(buffer)) > 0) { outputBuffer.write(buffer, 0, bytesInflated); } } @@ -160,11 +158,11 @@ private void decompress(byte[] data, ByteArrayOutputStream outputBuffer) throws @Override public void encodeFrame(Framedata inputFrame) { // Only DataFrames can be decompressed. - if(!(inputFrame instanceof DataFrame)) + if (!(inputFrame instanceof DataFrame)) return; // Only the first frame's RSV1 must be set. - if(!(inputFrame instanceof ContinuousFrame)) + if (!(inputFrame instanceof ContinuousFrame)) ((DataFrame) inputFrame).setRSV1(true); deflater.setInput(inputFrame.getPayloadData().array()); @@ -173,7 +171,7 @@ public void encodeFrame(Framedata inputFrame) { // Temporary buffer to hold compressed output. byte[] buffer = new byte[1024]; int bytesCompressed; - while((bytesCompressed = deflater.deflate(buffer, 0, buffer.length, Deflater.SYNC_FLUSH)) > 0) { + while ((bytesCompressed = deflater.deflate(buffer, 0, buffer.length, Deflater.SYNC_FLUSH)) > 0) { output.write(buffer, 0, bytesCompressed); } @@ -186,11 +184,11 @@ public void encodeFrame(Framedata inputFrame) { To simulate removal, we just pass 4 bytes less to the new payload if the frame is final and outputBytes ends with 0x00 0x00 0xff 0xff. */ - if(inputFrame.isFin()) { - if(endsWithTail(outputBytes)) + if (inputFrame.isFin()) { + if (endsWithTail(outputBytes)) outputLength -= TAIL_BYTES.length; - if(serverNoContextTakeover) { + if (serverNoContextTakeover) { deflater.end(); deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); } @@ -205,13 +203,13 @@ public void encodeFrame(Framedata inputFrame) { * @param data the bytes of data * @return true if the data is OK */ - private boolean endsWithTail(byte[] data){ - if(data.length < 4) + private boolean endsWithTail(byte[] data) { + if (data.length < 4) return false; int length = data.length; - for(int i = 0; i < TAIL_BYTES.length; i++){ - if(TAIL_BYTES[i] != data[length - TAIL_BYTES.length + i]) + for (int i = 0; i < TAIL_BYTES.length; i++) { + if (TAIL_BYTES[i] != data[length - TAIL_BYTES.length + i]) return false; } @@ -221,15 +219,15 @@ private boolean endsWithTail(byte[] data){ @Override public boolean acceptProvidedExtensionAsServer(String inputExtension) { String[] requestedExtensions = inputExtension.split(","); - for(String extension : requestedExtensions) { + for (String extension : requestedExtensions) { ExtensionRequestData extensionData = ExtensionRequestData.parseExtensionRequest(extension); - if(!EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extensionData.getExtensionName())) + if (!EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extensionData.getExtensionName())) continue; // Holds parameters that peer client has sent. Map headers = extensionData.getExtensionParameters(); requestedParameters.putAll(headers); - if(requestedParameters.containsKey(CLIENT_NO_CONTEXT_TAKEOVER)) + if (requestedParameters.containsKey(CLIENT_NO_CONTEXT_TAKEOVER)) clientNoContextTakeover = true; return true; @@ -241,9 +239,9 @@ public boolean acceptProvidedExtensionAsServer(String inputExtension) { @Override public boolean acceptProvidedExtensionAsClient(String inputExtension) { String[] requestedExtensions = inputExtension.split(","); - for(String extension : requestedExtensions) { + for (String extension : requestedExtensions) { ExtensionRequestData extensionData = ExtensionRequestData.parseExtensionRequest(extension); - if(!EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extensionData.getExtensionName())) + if (!EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extensionData.getExtensionName())) continue; // Holds parameters that are sent by the server, as a response to our initial extension request. @@ -281,9 +279,9 @@ public IExtension copyInstance() { */ @Override public void isFrameValid(Framedata inputFrame) throws InvalidDataException { - if((inputFrame instanceof TextFrame || inputFrame instanceof BinaryFrame) && !inputFrame.isRSV1()) + if ((inputFrame instanceof TextFrame || inputFrame instanceof BinaryFrame) && !inputFrame.isRSV1()) throw new InvalidFrameException("RSV1 bit must be set for DataFrames."); - if((inputFrame instanceof ContinuousFrame) && (inputFrame.isRSV1() || inputFrame.isRSV2() || inputFrame.isRSV3())) + if ((inputFrame instanceof ContinuousFrame) && (inputFrame.isRSV1() || inputFrame.isRSV2() || inputFrame.isRSV3())) throw new InvalidFrameException( "bad rsv RSV1: " + inputFrame.isRSV1() + " RSV2: " + inputFrame.isRSV2() + " RSV3: " + inputFrame.isRSV3() ); super.isFrameValid(inputFrame); } From 3eeb3d235657e21f30f4879e4604dbd98efee951 Mon Sep 17 00:00:00 2001 From: dota17 Date: Wed, 22 Jul 2020 16:47:48 +0800 Subject: [PATCH 061/165] Update the README.markdown with RFC7692 --- README.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/README.markdown b/README.markdown index 27682b6c5..8c028bb7d 100644 --- a/README.markdown +++ b/README.markdown @@ -13,6 +13,7 @@ non-blocking event-driven model (similar to the Implemented WebSocket protocol versions are: * [RFC 6455](http://tools.ietf.org/html/rfc6455) + * [RFC 7692](http://tools.ietf.org/html/rfc7692) [Here](https://github.com/TooTallNate/Java-WebSocket/wiki/Drafts) some more details about protocol versions/drafts. From 7b760076a817f297c2fd1382a6c956bcfcec606f Mon Sep 17 00:00:00 2001 From: dota17 Date: Thu, 23 Jul 2020 15:06:25 +0800 Subject: [PATCH 062/165] 1. Point to a perMessageDeflate example in the wiki; 2. Reference each section here for setter and getter; --- README.markdown | 1 + .../PerMessageDeflateExtension.java | 19 ++++++++++++- .../PerMessageDeflateExtensionTest.java | 28 +++++++++++++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/README.markdown b/README.markdown index 8c028bb7d..2d1e3fa9f 100644 --- a/README.markdown +++ b/README.markdown @@ -16,6 +16,7 @@ Implemented WebSocket protocol versions are: * [RFC 7692](http://tools.ietf.org/html/rfc7692) [Here](https://github.com/TooTallNate/Java-WebSocket/wiki/Drafts) some more details about protocol versions/drafts. +[PerMessageDeflateExample](https://github.com/TooTallNate/Java-WebSocket/wiki/PerMessageDeflateExample) enable the extension with reference to both a server and client example. ## Getting Started diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index 40cba71d5..d5f1d95b4 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -49,9 +49,26 @@ public class PerMessageDeflateExtension extends CompressionExtension { // For WebSocketServers, this variable holds the extension parameters that the peer client has requested. // For WebSocketClients, this variable holds the extension parameters that client himself has requested. private Map requestedParameters = new LinkedHashMap(); + private Inflater inflater = new Inflater(true); private Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); + public Inflater getInflater() { + return inflater; + } + + public void setInflater(Inflater inflater) { + this.inflater = inflater; + } + + public Deflater getDeflater() { + return deflater; + } + + public void setDeflater(Deflater deflater) { + this.deflater = deflater; + } + /** * * @return serverNoContextTakeover @@ -141,7 +158,7 @@ We can check the getRemaining() method to see whether the data we supplied has b /** * - * @param data the bytes of date + * @param data the bytes of data * @param outputBuffer the output stream * @throws DataFormatException */ diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index a3fb60f94..5c59e954c 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -7,6 +7,8 @@ import org.junit.Test; import java.nio.ByteBuffer; +import java.util.zip.Deflater; +import java.util.zip.Inflater; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -154,4 +156,30 @@ public void testCopyInstance() { IExtension newDeflateExtension = deflateExtension.copyInstance(); assertEquals(deflateExtension.toString(), newDeflateExtension.toString()); } + + @Test + public void testGetInflater() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertEquals(deflateExtension.getInflater(), new Inflater(true)); + } + + @Test + public void testSetInflater() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setInflater(new Inflater(false)); + assertEquals(deflateExtension.getInflater(), new Inflater(false)); + } + + @Test + public void testGetDeflater() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertEquals(deflateExtension.getDeflater(), new Deflater(Deflater.DEFAULT_COMPRESSION, true)); + } + + @Test + public void testSetDeflater() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setDeflater(new Deflater(Deflater.DEFAULT_COMPRESSION, false)); + assertEquals(deflateExtension.getDeflater(), new Deflater(Deflater.DEFAULT_COMPRESSION, false)); + } } From 7022fca5794ed9abfefb8cdf541d0f328ba8cecf Mon Sep 17 00:00:00 2001 From: dota17 Date: Thu, 23 Jul 2020 15:40:04 +0800 Subject: [PATCH 063/165] Fix the failure of testcases. --- .../extensions/PerMessageDeflateExtensionTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index 5c59e954c..9906cfa52 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -160,26 +160,26 @@ public void testCopyInstance() { @Test public void testGetInflater() { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertEquals(deflateExtension.getInflater(), new Inflater(true)); + assertEquals(deflateExtension.getInflater().getRemaining(), new Inflater(true).getRemaining()); } @Test public void testSetInflater() { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); deflateExtension.setInflater(new Inflater(false)); - assertEquals(deflateExtension.getInflater(), new Inflater(false)); + assertEquals(deflateExtension.getInflater().getRemaining(), new Inflater(false).getRemaining()); } @Test public void testGetDeflater() { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertEquals(deflateExtension.getDeflater(), new Deflater(Deflater.DEFAULT_COMPRESSION, true)); + assertEquals(deflateExtension.getDeflater().finished(), new Deflater(Deflater.DEFAULT_COMPRESSION, true).finished()); } @Test public void testSetDeflater() { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); deflateExtension.setDeflater(new Deflater(Deflater.DEFAULT_COMPRESSION, false)); - assertEquals(deflateExtension.getDeflater(), new Deflater(Deflater.DEFAULT_COMPRESSION, false)); + assertEquals(deflateExtension.getDeflater().finished(),new Deflater(Deflater.DEFAULT_COMPRESSION, false).finished()); } } From 934bd9f5f14ce729d97132fc18b82bfcbb94d2a6 Mon Sep 17 00:00:00 2001 From: chenguoping Date: Tue, 28 Jul 2020 15:54:43 +0800 Subject: [PATCH 064/165] fix the issue256Test --- src/test/java/org/java_websocket/issues/Issue256Test.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/java/org/java_websocket/issues/Issue256Test.java b/src/test/java/org/java_websocket/issues/Issue256Test.java index f0556a765..29cae69ef 100644 --- a/src/test/java/org/java_websocket/issues/Issue256Test.java +++ b/src/test/java/org/java_websocket/issues/Issue256Test.java @@ -96,6 +96,7 @@ public void onStart() { }; ws.setConnectionLostTimeout( 0 ); ws.start(); + countServerDownLatch.await(); } private void runTestScenarioReconnect( boolean closeBlocking ) throws Exception { From 96e511a43b1605787e4d892f8fe9759bd3092c8d Mon Sep 17 00:00:00 2001 From: dota17 Date: Sat, 1 Aug 2020 11:20:10 +0800 Subject: [PATCH 065/165] Fix Issue-1053 --- .../org/java_websocket/drafts/Draft_6455.java | 2 +- .../java_websocket/drafts/Draft_6455Test.java | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index bb97c82de..b6259c957 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -383,7 +383,7 @@ public HandshakeBuilder postProcessHandshakeResponseAsServer( ClientHandshake re response.put( UPGRADE, "websocket" ); response.put( CONNECTION, request.getFieldValue( CONNECTION) ); // to respond to a Connection keep alives String seckey = request.getFieldValue(SEC_WEB_SOCKET_KEY); - if( seckey == null ) + if( seckey == null || "".equals(seckey) ) throw new InvalidHandshakeException( "missing Sec-WebSocket-Key" ); response.put( SEC_WEB_SOCKET_ACCEPT, generateFinalKey( seckey ) ); if( getExtension().getProvidedExtensionAsServer().length() != 0 ) { diff --git a/src/test/java/org/java_websocket/drafts/Draft_6455Test.java b/src/test/java/org/java_websocket/drafts/Draft_6455Test.java index af0b1bfae..1f8959767 100644 --- a/src/test/java/org/java_websocket/drafts/Draft_6455Test.java +++ b/src/test/java/org/java_websocket/drafts/Draft_6455Test.java @@ -27,6 +27,7 @@ import org.java_websocket.enums.CloseHandshakeType; import org.java_websocket.enums.HandshakeState; +import org.java_websocket.exceptions.InvalidHandshakeException; import org.java_websocket.extensions.DefaultExtension; import org.java_websocket.extensions.IExtension; import org.java_websocket.framing.BinaryFrame; @@ -459,6 +460,19 @@ public void postProcessHandshakeResponseAsServer() throws Exception { draft_6455.postProcessHandshakeResponseAsServer(request, response); assertEquals( "test", response.getFieldValue( "Sec-WebSocket-Protocol" ) ); assertTrue( !response.hasFieldValue( "Sec-WebSocket-Extensions" ) ); + + // issue #1053 : check the exception - missing Sec-WebSocket-Key + response = new HandshakeImpl1Server(); + request = new HandshakeImpl1Client(); + draft_6455.reset(); + request.put( "Connection", "upgrade" ); + + try { + draft_6455.postProcessHandshakeResponseAsServer(request, response); + fail( "InvalidHandshakeException should be thrown" ); + } catch ( InvalidHandshakeException e ) { + + } } @@ -517,4 +531,4 @@ public boolean equals( Object o ) { return getClass() == o.getClass(); } } -} \ No newline at end of file +} From cba57c46ab6e8e56c382c5151645da1d1c4e0aa0 Mon Sep 17 00:00:00 2001 From: dota17 Date: Sat, 1 Aug 2020 17:21:45 +0800 Subject: [PATCH 066/165] Fixtypo --- src/main/java/org/java_websocket/SSLSocketChannel.java | 2 +- src/main/java/org/java_websocket/SSLSocketChannel2.java | 4 ++-- src/main/java/org/java_websocket/WebSocketServerFactory.java | 2 +- src/main/java/org/java_websocket/client/WebSocketClient.java | 2 +- .../exceptions/IncompleteHandshakeException.java | 2 +- .../org/java_websocket/exceptions/InvalidDataException.java | 2 +- src/main/java/org/java_websocket/framing/FramedataImpl1.java | 2 +- src/main/java/org/java_websocket/server/WebSocketServer.java | 4 ++-- src/main/java/org/java_websocket/util/Base64.java | 4 ++-- .../java/org/java_websocket/extensions/AllExtensionTests.java | 2 +- 10 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/java_websocket/SSLSocketChannel.java b/src/main/java/org/java_websocket/SSLSocketChannel.java index ac214d68b..a3c0dc30f 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel.java @@ -167,7 +167,7 @@ public synchronized int read( ByteBuffer dst ) throws IOException { try { result = engine.unwrap( peerNetData, peerAppData ); } catch ( SSLException e ) { - log.error("SSLExcpetion during unwrap", e); + log.error("SSLException during unwrap", e); throw e; } switch(result.getStatus()) { diff --git a/src/main/java/org/java_websocket/SSLSocketChannel2.java b/src/main/java/org/java_websocket/SSLSocketChannel2.java index ae9669d49..ccf21fc26 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel2.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel2.java @@ -71,7 +71,7 @@ public class SSLSocketChannel2 implements ByteChannel, WrappedByteChannel, ISSLC protected List> tasks; - /** raw payload incomming */ + /** raw payload incoming */ protected ByteBuffer inData; /** encrypted data outgoing */ protected ByteBuffer outCrypt; @@ -130,7 +130,7 @@ private void consumeFutureUninterruptible( Future f ) { } /** - * This method will do whatever necessary to process the sslengine handshake. + * This method will do whatever necessary to process the sslEngine handshake. * Thats why it's called both from the {@link #read(ByteBuffer)} and {@link #write(ByteBuffer)} **/ private synchronized void processHandshake() throws IOException { diff --git a/src/main/java/org/java_websocket/WebSocketServerFactory.java b/src/main/java/org/java_websocket/WebSocketServerFactory.java index c8deaa2c8..2a6c2347f 100644 --- a/src/main/java/org/java_websocket/WebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/WebSocketServerFactory.java @@ -44,7 +44,7 @@ public interface WebSocketServerFactory extends WebSocketFactory { WebSocketImpl createWebSocket( WebSocketAdapter a, List drafts ); /** - * Allows to wrap the Socketchannel( key.channel() ) to insert a protocol layer( like ssl or proxy authentication) beyond the ws layer. + * Allows to wrap the SocketChannel( key.channel() ) to insert a protocol layer( like ssl or proxy authentication) beyond the ws layer. * * @param channel The SocketChannel to wrap * @param key a SelectionKey of an open SocketChannel. diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 91171cccc..e75d33886 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -684,7 +684,7 @@ public InetSocketAddress getRemoteSocketAddress( WebSocket conn ) { return null; } - // ABTRACT METHODS ///////////////////////////////////////////////////////// + // ABSTRACT METHODS ///////////////////////////////////////////////////////// /** * Called after an opening handshake has been performed and the given websocket is ready to be written on. diff --git a/src/main/java/org/java_websocket/exceptions/IncompleteHandshakeException.java b/src/main/java/org/java_websocket/exceptions/IncompleteHandshakeException.java index 80c5bc82a..87826e297 100644 --- a/src/main/java/org/java_websocket/exceptions/IncompleteHandshakeException.java +++ b/src/main/java/org/java_websocket/exceptions/IncompleteHandshakeException.java @@ -36,7 +36,7 @@ public class IncompleteHandshakeException extends RuntimeException { private static final long serialVersionUID = 7906596804233893092L; /** - * attribut which size of handshake would have been preferred + * attribute which size of handshake would have been preferred */ private final int preferredSize; diff --git a/src/main/java/org/java_websocket/exceptions/InvalidDataException.java b/src/main/java/org/java_websocket/exceptions/InvalidDataException.java index af5eaf9e5..885cf4545 100644 --- a/src/main/java/org/java_websocket/exceptions/InvalidDataException.java +++ b/src/main/java/org/java_websocket/exceptions/InvalidDataException.java @@ -36,7 +36,7 @@ public class InvalidDataException extends Exception { private static final long serialVersionUID = 3731842424390998726L; /** - * attribut which closecode will be returned + * attribute which closecode will be returned */ private final int closecode; diff --git a/src/main/java/org/java_websocket/framing/FramedataImpl1.java b/src/main/java/org/java_websocket/framing/FramedataImpl1.java index 21122fdeb..4a99977ab 100644 --- a/src/main/java/org/java_websocket/framing/FramedataImpl1.java +++ b/src/main/java/org/java_websocket/framing/FramedataImpl1.java @@ -159,7 +159,7 @@ public void append(Framedata nextframe) { @Override public String toString() { - return "Framedata{ optcode:" + getOpcode() + ", fin:" + isFin() + ", rsv1:" + isRSV1() + ", rsv2:" + isRSV2() + ", rsv3:" + isRSV3() + ", payloadlength:[pos:" + unmaskedpayload.position() + ", len:" + unmaskedpayload.remaining() + "], payload:" + ( unmaskedpayload.remaining() > 1000 ? "(too big to display)" : new String( unmaskedpayload.array() ) ) + '}'; + return "Framedata{ opcode:" + getOpcode() + ", fin:" + isFin() + ", rsv1:" + isRSV1() + ", rsv2:" + isRSV2() + ", rsv3:" + isRSV3() + ", payloadlength:[pos:" + unmaskedpayload.position() + ", len:" + unmaskedpayload.remaining() + "], payload:" + ( unmaskedpayload.remaining() > 1000 ? "(too big to display)" : new String( unmaskedpayload.array() ) ) + '}'; } /** diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 3dd79028f..0e73523b9 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -977,7 +977,7 @@ private void doBroadcast(Object data, Collection clients) { * @param draft The draft to use * @param draftFrames The list of frames per draft to fill * @param sData the string data, can be null - * @param bData the bytebuffer data, can be null + * @param bData the byte buffer data, can be null */ private void fillFrames(Draft draft, Map> draftFrames, String sData, ByteBuffer bData) { if( !draftFrames.containsKey( draft ) ) { @@ -1036,7 +1036,7 @@ public void run() { } /** - * call ws.decode on the bytebuffer + * call ws.decode on the byteBuffer * @param ws the Websocket * @param buf the buffer to decode to * @throws InterruptedException thrown by pushBuffer diff --git a/src/main/java/org/java_websocket/util/Base64.java b/src/main/java/org/java_websocket/util/Base64.java index d156c600f..e5c9f9d58 100644 --- a/src/main/java/org/java_websocket/util/Base64.java +++ b/src/main/java/org/java_websocket/util/Base64.java @@ -938,7 +938,7 @@ public void write(int theByte) if( suspendEncoding ) { this.out.write( theByte ); return; - } // end if: supsended + } // end if: suspended // Encode? if( encode ) { @@ -991,7 +991,7 @@ public void write( byte[] theBytes, int off, int len ) if( suspendEncoding ) { this.out.write( theBytes, off, len ); return; - } // end if: supsended + } // end if: suspended for( int i = 0; i < len; i++ ) { write( theBytes[ off + i ] ); diff --git a/src/test/java/org/java_websocket/extensions/AllExtensionTests.java b/src/test/java/org/java_websocket/extensions/AllExtensionTests.java index 736d1eb3f..47fe67498 100644 --- a/src/test/java/org/java_websocket/extensions/AllExtensionTests.java +++ b/src/test/java/org/java_websocket/extensions/AllExtensionTests.java @@ -34,7 +34,7 @@ org.java_websocket.extensions.CompressionExtensionTest.class }) /** - * Start all tests for extensuins + * Start all tests for extensions */ public class AllExtensionTests { } From 78cc001c25baf651584e3ec14ee6f18c4f3d282d Mon Sep 17 00:00:00 2001 From: dota17 Date: Mon, 3 Aug 2020 11:16:19 +0800 Subject: [PATCH 067/165] Fix the failure of the CloseFrameTest. --- src/main/java/org/java_websocket/framing/FramedataImpl1.java | 2 +- src/test/java/org/java_websocket/framing/CloseFrameTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/java_websocket/framing/FramedataImpl1.java b/src/main/java/org/java_websocket/framing/FramedataImpl1.java index 964597f61..f3e3f97e1 100644 --- a/src/main/java/org/java_websocket/framing/FramedataImpl1.java +++ b/src/main/java/org/java_websocket/framing/FramedataImpl1.java @@ -159,7 +159,7 @@ public void append(Framedata nextframe) { @Override public String toString() { - return "Framedata{ opcode:" + getOpcode() + ", fin:" + isFin() + ", rsv1:" + isRSV1() + ", rsv2:" + isRSV2() + ", rsv3:" + isRSV3() + ", payloadlength:[pos:" + unmaskedpayload.position() + ", len:" + unmaskedpayload.remaining() + "], payload:" + ( unmaskedpayload.remaining() > 1000 ? "(too big to display)" : new String( unmaskedpayload.array() ) ) + '}'; + return "Framedata{ opcode:" + getOpcode() + ", fin:" + isFin() + ", rsv1:" + isRSV1() + ", rsv2:" + isRSV2() + ", rsv3:" + isRSV3() + ", payload length:[pos:" + unmaskedpayload.position() + ", len:" + unmaskedpayload.remaining() + "], payload:" + ( unmaskedpayload.remaining() > 1000 ? "(too big to display)" : new String( unmaskedpayload.array() ) ) + '}'; } /** diff --git a/src/test/java/org/java_websocket/framing/CloseFrameTest.java b/src/test/java/org/java_websocket/framing/CloseFrameTest.java index 1246e926c..3ddd9fa6c 100644 --- a/src/test/java/org/java_websocket/framing/CloseFrameTest.java +++ b/src/test/java/org/java_websocket/framing/CloseFrameTest.java @@ -65,7 +65,7 @@ public void testToString() { CloseFrame frame = new CloseFrame(); String frameString = frame.toString(); frameString = frameString.replaceAll("payload:(.*)}", "payload: *}"); - assertEquals("Frame toString must include a close code", "Framedata{ optcode:CLOSING, fin:true, rsv1:false, rsv2:false, rsv3:false, payloadlength:[pos:0, len:2], payload: *}code: 1000", frameString); + assertEquals("Frame toString must include a close code", "Framedata{ opcode:CLOSING, fin:true, rsv1:false, rsv2:false, rsv3:false, payload length:[pos:0, len:2], payload: *}code: 1000", frameString); } From 07a6707172f660878ff992c6eeae3ee23acd23ff Mon Sep 17 00:00:00 2001 From: dota17 Date: Thu, 13 Aug 2020 17:21:33 +0800 Subject: [PATCH 068/165] remove the old codeformatterprofile.xml --- CodeFormatterProfile.xml | 279 --------------------------------------- 1 file changed, 279 deletions(-) delete mode 100644 CodeFormatterProfile.xml diff --git a/CodeFormatterProfile.xml b/CodeFormatterProfile.xml deleted file mode 100644 index 73325dedd..000000000 --- a/CodeFormatterProfile.xml +++ /dev/null @@ -1,279 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - From 285ce2af139788b16058aa0d372be26f8ccc2c3a Mon Sep 17 00:00:00 2001 From: dota17 Date: Thu, 13 Aug 2020 17:22:16 +0800 Subject: [PATCH 069/165] add new codeformatprofile - google version --- eclipse-java-google-style.xml | 337 +++++++++++++++++++ intellij-java-google-style.xml | 598 +++++++++++++++++++++++++++++++++ 2 files changed, 935 insertions(+) create mode 100644 eclipse-java-google-style.xml create mode 100644 intellij-java-google-style.xml diff --git a/eclipse-java-google-style.xml b/eclipse-java-google-style.xml new file mode 100644 index 000000000..7bb6804eb --- /dev/null +++ b/eclipse-java-google-style.xml @@ -0,0 +1,337 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/intellij-java-google-style.xml b/intellij-java-google-style.xml new file mode 100644 index 000000000..f3a6743ef --- /dev/null +++ b/intellij-java-google-style.xml @@ -0,0 +1,598 @@ + + + + + + From 63bde93751d5424d7ca41b67df7c13a0dcfdf268 Mon Sep 17 00:00:00 2001 From: dota17 Date: Thu, 13 Aug 2020 17:33:27 +0800 Subject: [PATCH 070/165] Reformat Code - the source code in src --- src/main/example/ChatClient.java | 273 +- src/main/example/ChatServer.java | 146 +- .../example/ChatServerAttachmentExample.java | 121 +- .../example/CustomHeaderClientExample.java | 62 +- src/main/example/ExampleClient.java | 74 +- src/main/example/FragmentedFramesExample.java | 74 +- .../example/PerMessageDeflateExample.java | 81 +- src/main/example/ProxyClientExample.java | 11 +- src/main/example/ReconnectClientExample.java | 39 +- src/main/example/SSLClientExample.java | 134 +- ...SLServerCustomWebsocketFactoryExample.java | 67 +- src/main/example/SSLServerExample.java | 52 +- .../example/SSLServerLetsEncryptExample.java | 160 +- .../SecWebSocketProtocolClientExample.java | 24 +- .../SecWebSocketProtocolServerExample.java | 24 +- .../ServerAdditionalHeaderExample.java | 62 +- .../example/ServerRejectHandshakeExample.java | 94 +- src/main/example/ServerStressTest.java | 386 +- src/main/example/TwoWaySSLServerExample.java | 62 +- .../org/java_websocket/AbstractWebSocket.java | 453 +- .../AbstractWrappedByteChannel.java | 140 +- .../org/java_websocket/SSLSocketChannel.java | 953 +-- .../org/java_websocket/SSLSocketChannel2.java | 772 +-- .../java_websocket/SocketChannelIOHelper.java | 139 +- .../java/org/java_websocket/WebSocket.java | 402 +- .../org/java_websocket/WebSocketAdapter.java | 121 +- .../org/java_websocket/WebSocketFactory.java | 31 +- .../org/java_websocket/WebSocketImpl.java | 1640 +++--- .../org/java_websocket/WebSocketListener.java | 320 +- .../WebSocketServerFactory.java | 42 +- .../java_websocket/WrappedByteChannel.java | 70 +- .../java_websocket/client/DnsResolver.java | 27 +- .../client/WebSocketClient.java | 1747 +++--- .../java/org/java_websocket/drafts/Draft.java | 555 +- .../org/java_websocket/drafts/Draft_6455.java | 2138 +++---- .../enums/CloseHandshakeType.java | 2 +- .../java_websocket/enums/HandshakeState.java | 12 +- .../java/org/java_websocket/enums/Opcode.java | 4 +- .../org/java_websocket/enums/ReadyState.java | 2 +- .../java/org/java_websocket/enums/Role.java | 2 +- .../exceptions/IncompleteException.java | 46 +- .../IncompleteHandshakeException.java | 65 +- .../exceptions/InvalidDataException.java | 110 +- .../exceptions/InvalidEncodingException.java | 42 +- .../exceptions/InvalidFrameException.java | 86 +- .../exceptions/InvalidHandshakeException.java | 86 +- .../exceptions/LimitExceededException.java | 103 +- .../exceptions/NotSendableException.java | 58 +- .../WebsocketNotConnectedException.java | 8 +- .../exceptions/WrappedIOException.java | 69 +- .../exceptions/package-info.java | 3 +- .../extensions/CompressionExtension.java | 24 +- .../extensions/DefaultExtension.java | 102 +- .../extensions/ExtensionRequestData.java | 67 +- .../java_websocket/extensions/IExtension.java | 170 +- .../extensions/package-info.java | 3 +- .../PerMessageDeflateExtension.java | 491 +- .../java_websocket/framing/BinaryFrame.java | 12 +- .../java_websocket/framing/CloseFrame.java | 543 +- .../framing/ContinuousFrame.java | 12 +- .../java_websocket/framing/ControlFrame.java | 45 +- .../org/java_websocket/framing/DataFrame.java | 24 +- .../org/java_websocket/framing/Framedata.java | 93 +- .../framing/FramedataImpl1.java | 463 +- .../org/java_websocket/framing/PingFrame.java | 12 +- .../org/java_websocket/framing/PongFrame.java | 30 +- .../org/java_websocket/framing/TextFrame.java | 24 +- .../java_websocket/framing/package-info.java | 3 +- .../handshake/ClientHandshake.java | 11 +- .../handshake/ClientHandshakeBuilder.java | 11 +- .../handshake/HandshakeBuilder.java | 24 +- .../handshake/HandshakeImpl1Client.java | 29 +- .../handshake/HandshakeImpl1Server.java | 58 +- .../handshake/Handshakedata.java | 48 +- .../handshake/HandshakedataImpl1.java | 84 +- .../handshake/ServerHandshake.java | 22 +- .../handshake/ServerHandshakeBuilder.java | 22 +- .../handshake/package-info.java | 3 +- .../interfaces/ISSLChannel.java | 11 +- .../java_websocket/protocols/IProtocol.java | 63 +- .../java_websocket/protocols/Protocol.java | 112 +- .../protocols/package-info.java | 3 +- .../CustomSSLWebSocketServerFactory.java | 93 +- .../DefaultSSLWebSocketServerFactory.java | 80 +- .../server/DefaultWebSocketServerFactory.java | 36 +- .../SSLParametersWebSocketServerFactory.java | 19 +- .../server/WebSocketServer.java | 2023 +++---- .../java/org/java_websocket/util/Base64.java | 1661 +++--- .../java_websocket/util/ByteBufferUtils.java | 72 +- .../java_websocket/util/Charsetfunctions.java | 241 +- .../util/NamedThreadFactory.java | 25 +- .../java/org/java_websocket/AllTests.java | 19 +- .../autobahn/AutobahnServerResultsTest.java | 5160 +++++++++-------- .../java_websocket/client/AllClientTests.java | 7 +- .../java_websocket/client/AttachmentTest.java | 80 +- .../java_websocket/client/HeadersTest.java | 134 +- .../client/SchemaCheckTest.java | 20 +- .../java_websocket/drafts/AllDraftTests.java | 4 +- .../java_websocket/drafts/Draft_6455Test.java | 1004 ++-- .../example/AutobahnClientTest.java | 272 +- .../example/AutobahnSSLServerTest.java | 158 +- .../example/AutobahnServerTest.java | 117 +- .../exceptions/AllExceptionsTests.java | 19 +- .../exceptions/IncompleteExceptionTest.java | 10 +- .../IncompleteHandshakeExceptionTest.java | 15 +- .../exceptions/InvalidDataExceptionTest.java | 34 +- .../InvalidEncodingExceptionTest.java | 24 +- .../exceptions/InvalidFrameExceptionTest.java | 49 +- .../InvalidHandshakeExceptionTest.java | 49 +- .../LimitExceededExceptionTest.java | 32 +- .../exceptions/NotSendableExceptionTest.java | 24 +- .../WebsocketNotConnectedExceptionTest.java | 10 +- .../extensions/AllExtensionTests.java | 6 +- .../extensions/CompressionExtensionTest.java | 125 +- .../extensions/DefaultExtensionTest.java | 225 +- .../PerMessageDeflateExtensionTest.java | 332 +- .../framing/AllFramingTests.java | 15 +- .../framing/BinaryFrameTest.java | 56 +- .../framing/CloseFrameTest.java | 400 +- .../framing/ContinuousFrameTest.java | 56 +- .../framing/FramedataImpl1Test.java | 119 +- .../java_websocket/framing/PingFrameTest.java | 118 +- .../java_websocket/framing/PongFrameTest.java | 132 +- .../java_websocket/framing/TextFrameTest.java | 86 +- .../java_websocket/issues/AllIssueTests.java | 30 +- .../java_websocket/issues/Issue256Test.java | 214 +- .../java_websocket/issues/Issue580Test.java | 131 +- .../java_websocket/issues/Issue598Test.java | 349 +- .../java_websocket/issues/Issue609Test.java | 134 +- .../java_websocket/issues/Issue621Test.java | 149 +- .../java_websocket/issues/Issue661Test.java | 162 +- .../java_websocket/issues/Issue666Test.java | 225 +- .../java_websocket/issues/Issue677Test.java | 166 +- .../java_websocket/issues/Issue713Test.java | 275 +- .../java_websocket/issues/Issue732Test.java | 140 +- .../java_websocket/issues/Issue764Test.java | 134 +- .../java_websocket/issues/Issue765Test.java | 91 +- .../java_websocket/issues/Issue811Test.java | 79 +- .../java_websocket/issues/Issue825Test.java | 164 +- .../java_websocket/issues/Issue834Test.java | 48 +- .../java_websocket/issues/Issue847Test.java | 264 +- .../java_websocket/issues/Issue855Test.java | 112 +- .../java_websocket/issues/Issue879Test.java | 205 +- .../java_websocket/issues/Issue890Test.java | 210 +- .../java_websocket/issues/Issue900Test.java | 208 +- .../java_websocket/issues/Issue941Test.java | 133 +- .../java_websocket/issues/Issue962Test.java | 185 +- .../java_websocket/issues/Issue997Test.java | 236 +- .../org/java_websocket/misc/AllMiscTests.java | 4 +- .../misc/OpeningHandshakeRejectionTest.java | 431 +- .../protocols/AllProtocolTests.java | 5 +- .../ProtoclHandshakeRejectionTest.java | 1066 ++-- .../protocols/ProtocolTest.java | 138 +- .../java_websocket/server/AllServerTests.java | 5 +- .../CustomSSLWebSocketServerFactoryTest.java | 277 +- .../DefaultSSLWebSocketServerFactoryTest.java | 223 +- .../DefaultWebSocketServerFactoryTest.java | 114 +- ...LParametersWebSocketServerFactoryTest.java | 167 +- .../server/WebSocketServerTest.java | 357 +- .../org/java_websocket/util/Base64Test.java | 166 +- .../util/ByteBufferUtilsTest.java | 162 +- .../util/CharsetfunctionsTest.java | 23 +- .../org/java_websocket/util/KeyUtils.java | 39 +- .../java_websocket/util/SSLContextUtil.java | 77 +- .../org/java_websocket/util/SocketUtil.java | 24 +- .../org/java_websocket/util/ThreadCheck.java | 97 +- 166 files changed, 18289 insertions(+), 17104 deletions(-) diff --git a/src/main/example/ChatClient.java b/src/main/example/ChatClient.java index 978a29127..7368a062f 100644 --- a/src/main/example/ChatClient.java +++ b/src/main/example/ChatClient.java @@ -45,140 +45,143 @@ import org.java_websocket.handshake.ServerHandshake; public class ChatClient extends JFrame implements ActionListener { - private static final long serialVersionUID = -6056260699202978657L; - - private final JTextField uriField; - private final JButton connect; - private final JButton close; - private final JTextArea ta; - private final JTextField chatField; - private final JComboBox draft; - private WebSocketClient cc; - - public ChatClient( String defaultlocation ) { - super( "WebSocket Chat Client" ); - Container c = getContentPane(); - GridLayout layout = new GridLayout(); - layout.setColumns( 1 ); - layout.setRows( 6 ); - c.setLayout( layout ); - - Draft[] drafts = { new Draft_6455() }; - draft = new JComboBox( drafts ); - c.add( draft ); - - uriField = new JTextField(); - uriField.setText( defaultlocation ); - c.add( uriField ); - - connect = new JButton( "Connect" ); - connect.addActionListener( this ); - c.add( connect ); - - close = new JButton( "Close" ); - close.addActionListener( this ); - close.setEnabled( false ); - c.add( close ); - - JScrollPane scroll = new JScrollPane(); - ta = new JTextArea(); - scroll.setViewportView( ta ); - c.add( scroll ); - - chatField = new JTextField(); - chatField.setText( "" ); - chatField.addActionListener( this ); - c.add( chatField ); - - java.awt.Dimension d = new java.awt.Dimension( 300, 400 ); - setPreferredSize( d ); - setSize( d ); - - addWindowListener( new java.awt.event.WindowAdapter() { - @Override - public void windowClosing( WindowEvent e ) { - if( cc != null ) { - cc.close(); - } - dispose(); - } - } ); - - setLocationRelativeTo( null ); - setVisible( true ); - } - - public void actionPerformed( ActionEvent e ) { - - if( e.getSource() == chatField ) { - if( cc != null ) { - cc.send( chatField.getText() ); - chatField.setText( "" ); - chatField.requestFocus(); - } - - } else if( e.getSource() == connect ) { - try { - // cc = new ChatClient(new URI(uriField.getText()), area, ( Draft ) draft.getSelectedItem() ); - cc = new WebSocketClient( new URI( uriField.getText() ), (Draft) draft.getSelectedItem() ) { - - @Override - public void onMessage( String message ) { - ta.append( "got: " + message + "\n" ); - ta.setCaretPosition( ta.getDocument().getLength() ); - } - - @Override - public void onOpen( ServerHandshake handshake ) { - ta.append( "You are connected to ChatServer: " + getURI() + "\n" ); - ta.setCaretPosition( ta.getDocument().getLength() ); - } - - @Override - public void onClose( int code, String reason, boolean remote ) { - ta.append( "You have been disconnected from: " + getURI() + "; Code: " + code + " " + reason + "\n" ); - ta.setCaretPosition( ta.getDocument().getLength() ); - connect.setEnabled( true ); - uriField.setEditable( true ); - draft.setEditable( true ); - close.setEnabled( false ); - } - - @Override - public void onError( Exception ex ) { - ta.append( "Exception occurred ...\n" + ex + "\n" ); - ta.setCaretPosition( ta.getDocument().getLength() ); - ex.printStackTrace(); - connect.setEnabled( true ); - uriField.setEditable( true ); - draft.setEditable( true ); - close.setEnabled( false ); - } - }; - - close.setEnabled( true ); - connect.setEnabled( false ); - uriField.setEditable( false ); - draft.setEditable( false ); - cc.connect(); - } catch ( URISyntaxException ex ) { - ta.append( uriField.getText() + " is not a valid WebSocket URI\n" ); - } - } else if( e.getSource() == close ) { - cc.close(); - } - } - - public static void main( String[] args ) { - String location; - if( args.length != 0 ) { - location = args[ 0 ]; - System.out.println( "Default server url specified: \'" + location + "\'" ); - } else { - location = "ws://localhost:8887"; - System.out.println( "Default server url not specified: defaulting to \'" + location + "\'" ); - } - new ChatClient( location ); - } + + private static final long serialVersionUID = -6056260699202978657L; + + private final JTextField uriField; + private final JButton connect; + private final JButton close; + private final JTextArea ta; + private final JTextField chatField; + private final JComboBox draft; + private WebSocketClient cc; + + public ChatClient(String defaultlocation) { + super("WebSocket Chat Client"); + Container c = getContentPane(); + GridLayout layout = new GridLayout(); + layout.setColumns(1); + layout.setRows(6); + c.setLayout(layout); + + Draft[] drafts = {new Draft_6455()}; + draft = new JComboBox(drafts); + c.add(draft); + + uriField = new JTextField(); + uriField.setText(defaultlocation); + c.add(uriField); + + connect = new JButton("Connect"); + connect.addActionListener(this); + c.add(connect); + + close = new JButton("Close"); + close.addActionListener(this); + close.setEnabled(false); + c.add(close); + + JScrollPane scroll = new JScrollPane(); + ta = new JTextArea(); + scroll.setViewportView(ta); + c.add(scroll); + + chatField = new JTextField(); + chatField.setText(""); + chatField.addActionListener(this); + c.add(chatField); + + java.awt.Dimension d = new java.awt.Dimension(300, 400); + setPreferredSize(d); + setSize(d); + + addWindowListener(new java.awt.event.WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + if (cc != null) { + cc.close(); + } + dispose(); + } + }); + + setLocationRelativeTo(null); + setVisible(true); + } + + public void actionPerformed(ActionEvent e) { + + if (e.getSource() == chatField) { + if (cc != null) { + cc.send(chatField.getText()); + chatField.setText(""); + chatField.requestFocus(); + } + + } else if (e.getSource() == connect) { + try { + // cc = new ChatClient(new URI(uriField.getText()), area, ( Draft ) draft.getSelectedItem() ); + cc = new WebSocketClient(new URI(uriField.getText()), (Draft) draft.getSelectedItem()) { + + @Override + public void onMessage(String message) { + ta.append("got: " + message + "\n"); + ta.setCaretPosition(ta.getDocument().getLength()); + } + + @Override + public void onOpen(ServerHandshake handshake) { + ta.append("You are connected to ChatServer: " + getURI() + "\n"); + ta.setCaretPosition(ta.getDocument().getLength()); + } + + @Override + public void onClose(int code, String reason, boolean remote) { + ta.append( + "You have been disconnected from: " + getURI() + "; Code: " + code + " " + reason + + "\n"); + ta.setCaretPosition(ta.getDocument().getLength()); + connect.setEnabled(true); + uriField.setEditable(true); + draft.setEditable(true); + close.setEnabled(false); + } + + @Override + public void onError(Exception ex) { + ta.append("Exception occurred ...\n" + ex + "\n"); + ta.setCaretPosition(ta.getDocument().getLength()); + ex.printStackTrace(); + connect.setEnabled(true); + uriField.setEditable(true); + draft.setEditable(true); + close.setEnabled(false); + } + }; + + close.setEnabled(true); + connect.setEnabled(false); + uriField.setEditable(false); + draft.setEditable(false); + cc.connect(); + } catch (URISyntaxException ex) { + ta.append(uriField.getText() + " is not a valid WebSocket URI\n"); + } + } else if (e.getSource() == close) { + cc.close(); + } + } + + public static void main(String[] args) { + String location; + if (args.length != 0) { + location = args[0]; + System.out.println("Default server url specified: \'" + location + "\'"); + } else { + location = "ws://localhost:8887"; + System.out.println("Default server url not specified: defaulting to \'" + location + "\'"); + } + new ChatClient(location); + } } diff --git a/src/main/example/ChatServer.java b/src/main/example/ChatServer.java index 7439add7b..de847adec 100644 --- a/src/main/example/ChatServer.java +++ b/src/main/example/ChatServer.java @@ -45,76 +45,80 @@ */ public class ChatServer extends WebSocketServer { - public ChatServer( int port ) throws UnknownHostException { - super( new InetSocketAddress( port ) ); - } - - public ChatServer( InetSocketAddress address ) { - super( address ); - } - - public ChatServer(int port, Draft_6455 draft) { - super( new InetSocketAddress( port ), Collections.singletonList(draft)); - } - - @Override - public void onOpen( WebSocket conn, ClientHandshake handshake ) { - conn.send("Welcome to the server!"); //This method sends a message to the new client - broadcast( "new connection: " + handshake.getResourceDescriptor() ); //This method sends a message to all clients connected - System.out.println( conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!" ); - } - - @Override - public void onClose( WebSocket conn, int code, String reason, boolean remote ) { - broadcast( conn + " has left the room!" ); - System.out.println( conn + " has left the room!" ); - } - - @Override - public void onMessage( WebSocket conn, String message ) { - broadcast( message ); - System.out.println( conn + ": " + message ); - } - @Override - public void onMessage( WebSocket conn, ByteBuffer message ) { - broadcast( message.array() ); - System.out.println( conn + ": " + message ); - } - - - public static void main( String[] args ) throws InterruptedException , IOException { - int port = 8887; // 843 flash policy port - try { - port = Integer.parseInt( args[ 0 ] ); - } catch ( Exception ex ) { - } - ChatServer s = new ChatServer( port ); - s.start(); - System.out.println( "ChatServer started on port: " + s.getPort() ); - - BufferedReader sysin = new BufferedReader( new InputStreamReader( System.in ) ); - while ( true ) { - String in = sysin.readLine(); - s.broadcast( in ); - if( in.equals( "exit" ) ) { - s.stop(1000); - break; - } - } - } - @Override - public void onError( WebSocket conn, Exception ex ) { - ex.printStackTrace(); - if( conn != null ) { - // some errors like port binding failed may not be assignable to a specific websocket - } - } - - @Override - public void onStart() { - System.out.println("Server started!"); - setConnectionLostTimeout(0); - setConnectionLostTimeout(100); - } + public ChatServer(int port) throws UnknownHostException { + super(new InetSocketAddress(port)); + } + + public ChatServer(InetSocketAddress address) { + super(address); + } + + public ChatServer(int port, Draft_6455 draft) { + super(new InetSocketAddress(port), Collections.singletonList(draft)); + } + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + conn.send("Welcome to the server!"); //This method sends a message to the new client + broadcast("new connection: " + handshake + .getResourceDescriptor()); //This method sends a message to all clients connected + System.out.println( + conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!"); + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + broadcast(conn + " has left the room!"); + System.out.println(conn + " has left the room!"); + } + + @Override + public void onMessage(WebSocket conn, String message) { + broadcast(message); + System.out.println(conn + ": " + message); + } + + @Override + public void onMessage(WebSocket conn, ByteBuffer message) { + broadcast(message.array()); + System.out.println(conn + ": " + message); + } + + + public static void main(String[] args) throws InterruptedException, IOException { + int port = 8887; // 843 flash policy port + try { + port = Integer.parseInt(args[0]); + } catch (Exception ex) { + } + ChatServer s = new ChatServer(port); + s.start(); + System.out.println("ChatServer started on port: " + s.getPort()); + + BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in)); + while (true) { + String in = sysin.readLine(); + s.broadcast(in); + if (in.equals("exit")) { + s.stop(1000); + break; + } + } + } + + @Override + public void onError(WebSocket conn, Exception ex) { + ex.printStackTrace(); + if (conn != null) { + // some errors like port binding failed may not be assignable to a specific websocket + } + } + + @Override + public void onStart() { + System.out.println("Server started!"); + setConnectionLostTimeout(0); + setConnectionLostTimeout(100); + } } diff --git a/src/main/example/ChatServerAttachmentExample.java b/src/main/example/ChatServerAttachmentExample.java index 3b7b2d528..3439bcbdf 100644 --- a/src/main/example/ChatServerAttachmentExample.java +++ b/src/main/example/ChatServerAttachmentExample.java @@ -38,75 +38,80 @@ /** * A simple WebSocketServer implementation. Keeps track of a "chatroom". - * + *

    * Shows how to use the attachment for a WebSocket. This example just uses a simple integer as ID. * Setting an attachment also works in the WebSocketClient */ public class ChatServerAttachmentExample extends WebSocketServer { - Integer index = 0; - public ChatServerAttachmentExample( int port ) throws UnknownHostException { - super( new InetSocketAddress( port ) ); - } + Integer index = 0; + + public ChatServerAttachmentExample(int port) throws UnknownHostException { + super(new InetSocketAddress(port)); + } + + public ChatServerAttachmentExample(InetSocketAddress address) { + super(address); + } + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + conn.setAttachment(index); //Set the attachment to the current index + index++; + // Get the attachment of this connection as Integer + System.out.println( + conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room! ID: " + + conn.getAttachment()); + } - public ChatServerAttachmentExample( InetSocketAddress address ) { - super( address ); - } + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + // Get the attachment of this connection as Integer + System.out.println(conn + " has left the room! ID: " + conn.getAttachment()); + } - @Override - public void onOpen( WebSocket conn, ClientHandshake handshake ) { - conn.setAttachment( index ); //Set the attachment to the current index - index++; - // Get the attachment of this connection as Integer - System.out.println( conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room! ID: " + conn.getAttachment() ); - } + @Override + public void onMessage(WebSocket conn, String message) { + System.out.println(conn + ": " + message); + } - @Override - public void onClose( WebSocket conn, int code, String reason, boolean remote ) { - // Get the attachment of this connection as Integer - System.out.println( conn + " has left the room! ID: " + conn.getAttachment() ); - } + @Override + public void onMessage(WebSocket conn, ByteBuffer message) { + System.out.println(conn + ": " + message); + } - @Override - public void onMessage( WebSocket conn, String message ) { - System.out.println( conn + ": " + message ); - } - @Override - public void onMessage( WebSocket conn, ByteBuffer message ) { - System.out.println( conn + ": " + message ); - } + public static void main(String[] args) throws InterruptedException, IOException { + int port = 8887; // 843 flash policy port + try { + port = Integer.parseInt(args[0]); + } catch (Exception ex) { + } + ChatServerAttachmentExample s = new ChatServerAttachmentExample(port); + s.start(); + System.out.println("ChatServer started on port: " + s.getPort()); - public static void main( String[] args ) throws InterruptedException , IOException { - int port = 8887; // 843 flash policy port - try { - port = Integer.parseInt( args[ 0 ] ); - } catch ( Exception ex ) { - } - ChatServerAttachmentExample s = new ChatServerAttachmentExample( port ); - s.start(); - System.out.println( "ChatServer started on port: " + s.getPort() ); + BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in)); + while (true) { + String in = sysin.readLine(); + s.broadcast(in); + if (in.equals("exit")) { + s.stop(1000); + break; + } + } + } - BufferedReader sysin = new BufferedReader( new InputStreamReader( System.in ) ); - while ( true ) { - String in = sysin.readLine(); - s.broadcast( in ); - if( in.equals( "exit" ) ) { - s.stop(1000); - break; - } - } - } - @Override - public void onError( WebSocket conn, Exception ex ) { - ex.printStackTrace(); - if( conn != null ) { - // some errors like port binding failed may not be assignable to a specific websocket - } - } + @Override + public void onError(WebSocket conn, Exception ex) { + ex.printStackTrace(); + if (conn != null) { + // some errors like port binding failed may not be assignable to a specific websocket + } + } - @Override - public void onStart() { - System.out.println("Server started!"); - } + @Override + public void onStart() { + System.out.println("Server started!"); + } } diff --git a/src/main/example/CustomHeaderClientExample.java b/src/main/example/CustomHeaderClientExample.java index 5f2c2818c..eab1e474c 100644 --- a/src/main/example/CustomHeaderClientExample.java +++ b/src/main/example/CustomHeaderClientExample.java @@ -32,39 +32,39 @@ /** * This class shows how to add additional http header like "Origin" or "Cookie". - * + *

    * To see it working, start ServerRejectHandshakeExample and then start this example. */ public class CustomHeaderClientExample { - public static void main( String[] args ) throws URISyntaxException, InterruptedException { - Map httpHeaders = new HashMap(); - httpHeaders.put( "Cookie", "test" ); - ExampleClient c = new ExampleClient( new URI( "ws://localhost:8887" ), httpHeaders); - //We expect no successful connection - c.connectBlocking(); - httpHeaders.put( "Cookie", "username=nemo" ); - c = new ExampleClient( new URI( "ws://localhost:8887" ) , httpHeaders); - //Wer expect a successful connection - c.connectBlocking(); - c.closeBlocking(); - httpHeaders.put( "Access-Control-Allow-Origin", "*" ); - c = new ExampleClient( new URI( "ws://localhost:8887" ) , httpHeaders); - //We expect no successful connection - c.connectBlocking(); - c.closeBlocking(); - httpHeaders.clear(); - httpHeaders.put( "Origin", "localhost:8887" ); - httpHeaders.put( "Cookie", "username=nemo" ); - c = new ExampleClient( new URI( "ws://localhost:8887" ) , httpHeaders); - //We expect a successful connection - c.connectBlocking(); - c.closeBlocking(); - httpHeaders.clear(); - httpHeaders.put( "Origin", "localhost" ); - httpHeaders.put( "cookie", "username=nemo" ); - c = new ExampleClient( new URI( "ws://localhost:8887" ) , httpHeaders); - //We expect no successful connection - c.connectBlocking(); - } + public static void main(String[] args) throws URISyntaxException, InterruptedException { + Map httpHeaders = new HashMap(); + httpHeaders.put("Cookie", "test"); + ExampleClient c = new ExampleClient(new URI("ws://localhost:8887"), httpHeaders); + //We expect no successful connection + c.connectBlocking(); + httpHeaders.put("Cookie", "username=nemo"); + c = new ExampleClient(new URI("ws://localhost:8887"), httpHeaders); + //Wer expect a successful connection + c.connectBlocking(); + c.closeBlocking(); + httpHeaders.put("Access-Control-Allow-Origin", "*"); + c = new ExampleClient(new URI("ws://localhost:8887"), httpHeaders); + //We expect no successful connection + c.connectBlocking(); + c.closeBlocking(); + httpHeaders.clear(); + httpHeaders.put("Origin", "localhost:8887"); + httpHeaders.put("Cookie", "username=nemo"); + c = new ExampleClient(new URI("ws://localhost:8887"), httpHeaders); + //We expect a successful connection + c.connectBlocking(); + c.closeBlocking(); + httpHeaders.clear(); + httpHeaders.put("Origin", "localhost"); + httpHeaders.put("cookie", "username=nemo"); + c = new ExampleClient(new URI("ws://localhost:8887"), httpHeaders); + //We expect no successful connection + c.connectBlocking(); + } } diff --git a/src/main/example/ExampleClient.java b/src/main/example/ExampleClient.java index c71343a0f..a9d32c4d0 100644 --- a/src/main/example/ExampleClient.java +++ b/src/main/example/ExampleClient.java @@ -33,48 +33,54 @@ import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ServerHandshake; -/** This example demonstrates how to create a websocket connection to a server. Only the most important callbacks are overloaded. */ +/** + * This example demonstrates how to create a websocket connection to a server. Only the most + * important callbacks are overloaded. + */ public class ExampleClient extends WebSocketClient { - public ExampleClient( URI serverUri , Draft draft ) { - super( serverUri, draft ); - } + public ExampleClient(URI serverUri, Draft draft) { + super(serverUri, draft); + } - public ExampleClient( URI serverURI ) { - super( serverURI ); - } + public ExampleClient(URI serverURI) { + super(serverURI); + } - public ExampleClient( URI serverUri, Map httpHeaders ) { - super(serverUri, httpHeaders); - } + public ExampleClient(URI serverUri, Map httpHeaders) { + super(serverUri, httpHeaders); + } - @Override - public void onOpen( ServerHandshake handshakedata ) { - send("Hello, it is me. Mario :)"); - System.out.println( "opened connection" ); - // if you plan to refuse connection based on ip or httpfields overload: onWebsocketHandshakeReceivedAsClient - } + @Override + public void onOpen(ServerHandshake handshakedata) { + send("Hello, it is me. Mario :)"); + System.out.println("opened connection"); + // if you plan to refuse connection based on ip or httpfields overload: onWebsocketHandshakeReceivedAsClient + } - @Override - public void onMessage( String message ) { - System.out.println( "received: " + message ); - } + @Override + public void onMessage(String message) { + System.out.println("received: " + message); + } - @Override - public void onClose( int code, String reason, boolean remote ) { - // The codecodes are documented in class org.java_websocket.framing.CloseFrame - System.out.println( "Connection closed by " + ( remote ? "remote peer" : "us" ) + " Code: " + code + " Reason: " + reason ); - } + @Override + public void onClose(int code, String reason, boolean remote) { + // The codecodes are documented in class org.java_websocket.framing.CloseFrame + System.out.println( + "Connection closed by " + (remote ? "remote peer" : "us") + " Code: " + code + " Reason: " + + reason); + } - @Override - public void onError( Exception ex ) { - ex.printStackTrace(); - // if the error is fatal then onClose will be called additionally - } + @Override + public void onError(Exception ex) { + ex.printStackTrace(); + // if the error is fatal then onClose will be called additionally + } - public static void main( String[] args ) throws URISyntaxException { - ExampleClient c = new ExampleClient( new URI( "ws://localhost:8887" )); // more about drafts here: http://github.com/TooTallNate/Java-WebSocket/wiki/Drafts - c.connect(); - } + public static void main(String[] args) throws URISyntaxException { + ExampleClient c = new ExampleClient(new URI( + "ws://localhost:8887")); // more about drafts here: http://github.com/TooTallNate/Java-WebSocket/wiki/Drafts + c.connect(); + } } \ No newline at end of file diff --git a/src/main/example/FragmentedFramesExample.java b/src/main/example/FragmentedFramesExample.java index aeb2cd868..52fce6ef5 100644 --- a/src/main/example/FragmentedFramesExample.java +++ b/src/main/example/FragmentedFramesExample.java @@ -35,47 +35,51 @@ import org.java_websocket.enums.Opcode; /** - * This example shows how to send fragmented frames.
    - * For information on when to used fragmented frames see http://tools.ietf.org/html/rfc6455#section-5.4
    - * Fragmented and normal messages can not be mixed. - * One is however allowed to mix them with control messages like ping/pong. - * + * This example shows how to send fragmented frames.
    For information on when to used fragmented + * frames see http://tools.ietf.org/html/rfc6455#section-5.4
    Fragmented and normal messages can + * not be mixed. One is however allowed to mix them with control messages like ping/pong. + * * @see WebSocket#sendFragmentedFrame(Opcode, ByteBuffer, boolean) **/ public class FragmentedFramesExample { - public static void main( String[] args ) throws URISyntaxException , IOException , InterruptedException { - // WebSocketImpl.DEBUG = true; // will give extra output - WebSocketClient websocket = new ExampleClient( new URI( "ws://localhost:8887" )); - if( !websocket.connectBlocking() ) { - System.err.println( "Could not connect to the server." ); - return; - } + public static void main(String[] args) + throws URISyntaxException, IOException, InterruptedException { + // WebSocketImpl.DEBUG = true; // will give extra output + + WebSocketClient websocket = new ExampleClient(new URI("ws://localhost:8887")); + if (!websocket.connectBlocking()) { + System.err.println("Could not connect to the server."); + return; + } - System.out.println( "This example shows how to send fragmented(continuous) messages." ); + System.out.println("This example shows how to send fragmented(continuous) messages."); - BufferedReader stdin = new BufferedReader( new InputStreamReader( System.in ) ); - while ( websocket.isOpen() ) { - System.out.println( "Please type in a loooooong line(which then will be send in 2 byte fragments):" ); - String longline = stdin.readLine(); - ByteBuffer longelinebuffer = ByteBuffer.wrap( longline.getBytes() ); - longelinebuffer.rewind(); + BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); + while (websocket.isOpen()) { + System.out + .println("Please type in a loooooong line(which then will be send in 2 byte fragments):"); + String longline = stdin.readLine(); + ByteBuffer longelinebuffer = ByteBuffer.wrap(longline.getBytes()); + longelinebuffer.rewind(); - for( int position = 2 ; ; position += 2 ) { - if( position < longelinebuffer.capacity() ) { - longelinebuffer.limit( position ); - websocket.sendFragmentedFrame( Opcode.TEXT, longelinebuffer, false );// when sending binary data one should use Opcode.BINARY - assert ( longelinebuffer.remaining() == 0 ); - // after calling sendFragmentedFrame one may reuse the buffer given to the method immediately - } else { - longelinebuffer.limit( longelinebuffer.capacity() ); - websocket.sendFragmentedFrame( Opcode.TEXT, longelinebuffer, true );// sending the last frame - break; - } + for (int position = 2; ; position += 2) { + if (position < longelinebuffer.capacity()) { + longelinebuffer.limit(position); + websocket.sendFragmentedFrame(Opcode.TEXT, longelinebuffer, + false);// when sending binary data one should use Opcode.BINARY + assert (longelinebuffer.remaining() == 0); + // after calling sendFragmentedFrame one may reuse the buffer given to the method immediately + } else { + longelinebuffer.limit(longelinebuffer.capacity()); + websocket + .sendFragmentedFrame(Opcode.TEXT, longelinebuffer, true);// sending the last frame + break; + } - } - System.out.println( "You can not type in the next long message or press Ctr-C to exit." ); - } - System.out.println( "FragmentedFramesExample terminated" ); - } + } + System.out.println("You can not type in the next long message or press Ctr-C to exit."); + } + System.out.println("FragmentedFramesExample terminated"); + } } diff --git a/src/main/example/PerMessageDeflateExample.java b/src/main/example/PerMessageDeflateExample.java index 94bc3fd2d..b557029d5 100644 --- a/src/main/example/PerMessageDeflateExample.java +++ b/src/main/example/PerMessageDeflateExample.java @@ -13,60 +13,71 @@ import java.util.Collections; /** - * This class only serves the purpose of showing how to enable PerMessageDeflateExtension for both server and client sockets.
    - * Extensions are required to be registered in + * This class only serves the purpose of showing how to enable PerMessageDeflateExtension for both + * server and client sockets.
    Extensions are required to be registered in + * * @see Draft objects and both * @see WebSocketClient and * @see WebSocketServer accept a - * @see Draft object in their constructors. - * This example shows how to achieve it for both server and client sockets. - * Once the connection has been established, PerMessageDeflateExtension will be enabled - * and any messages (binary or text) will be compressed/decompressed automatically.
    - * Since no additional code is required when sending or receiving messages, this example skips those parts. + * @see Draft object in their constructors. This example shows how to achieve it for both server and + * client sockets. Once the connection has been established, PerMessageDeflateExtension will be + * enabled and any messages (binary or text) will be compressed/decompressed automatically.
    + * Since no additional code is required when sending or receiving messages, this example skips those + * parts. */ public class PerMessageDeflateExample { - private static final Draft perMessageDeflateDraft = new Draft_6455(new PerMessageDeflateExtension()); - private static final int PORT = 8887; + private static final Draft perMessageDeflateDraft = new Draft_6455( + new PerMessageDeflateExtension()); + private static final int PORT = 8887; - private static class DeflateClient extends WebSocketClient { + private static class DeflateClient extends WebSocketClient { - public DeflateClient() throws URISyntaxException { - super(new URI("ws://localhost:" + PORT), perMessageDeflateDraft); - } + public DeflateClient() throws URISyntaxException { + super(new URI("ws://localhost:" + PORT), perMessageDeflateDraft); + } - @Override - public void onOpen(ServerHandshake handshakedata) { } + @Override + public void onOpen(ServerHandshake handshakedata) { + } - @Override - public void onMessage(String message) { } + @Override + public void onMessage(String message) { + } - @Override - public void onClose(int code, String reason, boolean remote) { } + @Override + public void onClose(int code, String reason, boolean remote) { + } - @Override - public void onError(Exception ex) { } + @Override + public void onError(Exception ex) { } + } - private static class DeflateServer extends WebSocketServer { + private static class DeflateServer extends WebSocketServer { - public DeflateServer() { - super(new InetSocketAddress(PORT), Collections.singletonList(perMessageDeflateDraft)); - } + public DeflateServer() { + super(new InetSocketAddress(PORT), Collections.singletonList(perMessageDeflateDraft)); + } - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { } + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { } + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } - @Override - public void onMessage(WebSocket conn, String message) { } + @Override + public void onMessage(WebSocket conn, String message) { + } - @Override - public void onError(WebSocket conn, Exception ex) { } + @Override + public void onError(WebSocket conn, Exception ex) { + } - @Override - public void onStart() { } + @Override + public void onStart() { } + } } diff --git a/src/main/example/ProxyClientExample.java b/src/main/example/ProxyClientExample.java index fbd5a8a64..4241359ed 100644 --- a/src/main/example/ProxyClientExample.java +++ b/src/main/example/ProxyClientExample.java @@ -29,9 +29,10 @@ import java.net.URISyntaxException; public class ProxyClientExample { - public static void main( String[] args ) throws URISyntaxException { - ExampleClient c = new ExampleClient( new URI( "ws://echo.websocket.org" ) ); - c.setProxy( new Proxy( Proxy.Type.HTTP, new InetSocketAddress( "proxyaddress", 80 ) ) ); - c.connect(); - } + + public static void main(String[] args) throws URISyntaxException { + ExampleClient c = new ExampleClient(new URI("ws://echo.websocket.org")); + c.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxyaddress", 80))); + c.connect(); + } } diff --git a/src/main/example/ReconnectClientExample.java b/src/main/example/ReconnectClientExample.java index ee607e47b..1eaebe1b3 100644 --- a/src/main/example/ReconnectClientExample.java +++ b/src/main/example/ReconnectClientExample.java @@ -32,23 +32,24 @@ * Simple example to reconnect blocking and non-blocking. */ public class ReconnectClientExample { - public static void main( String[] args ) throws URISyntaxException, InterruptedException { - ExampleClient c = new ExampleClient( new URI( "ws://localhost:8887" ) ); - //Connect to a server normally - c.connectBlocking(); - c.send( "hi" ); - Thread.sleep( 10 ); - c.closeBlocking(); - //Disconnect manually and reconnect blocking - c.reconnectBlocking(); - c.send( "it's" ); - Thread.sleep( 10000 ); - c.closeBlocking(); - //Disconnect manually and reconnect - c.reconnect(); - Thread.sleep( 100 ); - c.send( "me" ); - Thread.sleep( 100 ); - c.closeBlocking(); - } + + public static void main(String[] args) throws URISyntaxException, InterruptedException { + ExampleClient c = new ExampleClient(new URI("ws://localhost:8887")); + //Connect to a server normally + c.connectBlocking(); + c.send("hi"); + Thread.sleep(10); + c.closeBlocking(); + //Disconnect manually and reconnect blocking + c.reconnectBlocking(); + c.send("it's"); + Thread.sleep(10000); + c.closeBlocking(); + //Disconnect manually and reconnect + c.reconnect(); + Thread.sleep(100); + c.send("me"); + Thread.sleep(100); + c.closeBlocking(); + } } diff --git a/src/main/example/SSLClientExample.java b/src/main/example/SSLClientExample.java index d85fb85a7..98746e36b 100644 --- a/src/main/example/SSLClientExample.java +++ b/src/main/example/SSLClientExample.java @@ -42,83 +42,85 @@ class WebSocketChatClient extends WebSocketClient { - public WebSocketChatClient( URI serverUri ) { - super( serverUri ); - } + public WebSocketChatClient(URI serverUri) { + super(serverUri); + } - @Override - public void onOpen( ServerHandshake handshakedata ) { - System.out.println( "Connected" ); + @Override + public void onOpen(ServerHandshake handshakedata) { + System.out.println("Connected"); - } + } - @Override - public void onMessage( String message ) { - System.out.println( "got: " + message ); + @Override + public void onMessage(String message) { + System.out.println("got: " + message); - } + } - @Override - public void onClose( int code, String reason, boolean remote ) { - System.out.println( "Disconnected" ); + @Override + public void onClose(int code, String reason, boolean remote) { + System.out.println("Disconnected"); - } + } - @Override - public void onError( Exception ex ) { - ex.printStackTrace(); + @Override + public void onError(Exception ex) { + ex.printStackTrace(); - } + } } public class SSLClientExample { - /* - * Keystore with certificate created like so (in JKS format): - * - *keytool -genkey -keyalg RSA -validity 3650 -keystore "keystore.jks" -storepass "storepassword" -keypass "keypassword" -alias "default" -dname "CN=127.0.0.1, OU=MyOrgUnit, O=MyOrg, L=MyCity, S=MyRegion, C=MyCountry" - */ - public static void main( String[] args ) throws Exception { - WebSocketChatClient chatclient = new WebSocketChatClient( new URI( "wss://localhost:8887" ) ); - - // load up the key store - String STORETYPE = "JKS"; - String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks").toString(); - String STOREPASSWORD = "storepassword"; - String KEYPASSWORD = "keypassword"; - - KeyStore ks = KeyStore.getInstance( STORETYPE ); - File kf = new File( KEYSTORE ); - ks.load( new FileInputStream( kf ), STOREPASSWORD.toCharArray() ); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" ); - kmf.init( ks, KEYPASSWORD.toCharArray() ); - TrustManagerFactory tmf = TrustManagerFactory.getInstance( "SunX509" ); - tmf.init( ks ); - - SSLContext sslContext = null; - sslContext = SSLContext.getInstance( "TLS" ); - sslContext.init( kmf.getKeyManagers(), tmf.getTrustManagers(), null ); - // sslContext.init( null, null, null ); // will use java's default key and trust store which is sufficient unless you deal with self-signed certificates - - SSLSocketFactory factory = sslContext.getSocketFactory();// (SSLSocketFactory) SSLSocketFactory.getDefault(); - - chatclient.setSocketFactory( factory ); - - chatclient.connectBlocking(); - - BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) ); - while ( true ) { - String line = reader.readLine(); - if( line.equals( "close" ) ) { - chatclient.closeBlocking(); - } else if ( line.equals( "open" ) ) { - chatclient.reconnect(); - } else { - chatclient.send( line ); - } - } - - } + /* + * Keystore with certificate created like so (in JKS format): + * + *keytool -genkey -keyalg RSA -validity 3650 -keystore "keystore.jks" -storepass "storepassword" -keypass "keypassword" -alias "default" -dname "CN=127.0.0.1, OU=MyOrgUnit, O=MyOrg, L=MyCity, S=MyRegion, C=MyCountry" + */ + public static void main(String[] args) throws Exception { + WebSocketChatClient chatclient = new WebSocketChatClient(new URI("wss://localhost:8887")); + + // load up the key store + String STORETYPE = "JKS"; + String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks") + .toString(); + String STOREPASSWORD = "storepassword"; + String KEYPASSWORD = "keypassword"; + + KeyStore ks = KeyStore.getInstance(STORETYPE); + File kf = new File(KEYSTORE); + ks.load(new FileInputStream(kf), STOREPASSWORD.toCharArray()); + + KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); + kmf.init(ks, KEYPASSWORD.toCharArray()); + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(ks); + + SSLContext sslContext = null; + sslContext = SSLContext.getInstance("TLS"); + sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + // sslContext.init( null, null, null ); // will use java's default key and trust store which is sufficient unless you deal with self-signed certificates + + SSLSocketFactory factory = sslContext + .getSocketFactory();// (SSLSocketFactory) SSLSocketFactory.getDefault(); + + chatclient.setSocketFactory(factory); + + chatclient.connectBlocking(); + + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + while (true) { + String line = reader.readLine(); + if (line.equals("close")) { + chatclient.closeBlocking(); + } else if (line.equals("open")) { + chatclient.reconnect(); + } else { + chatclient.send(line); + } + } + + } } diff --git a/src/main/example/SSLServerCustomWebsocketFactoryExample.java b/src/main/example/SSLServerCustomWebsocketFactoryExample.java index 3d834e027..2c98dac5b 100644 --- a/src/main/example/SSLServerCustomWebsocketFactoryExample.java +++ b/src/main/example/SSLServerCustomWebsocketFactoryExample.java @@ -43,49 +43,52 @@ */ public class SSLServerCustomWebsocketFactoryExample { - /* - * Keystore with certificate created like so (in JKS format): - * - *keytool -genkey -validity 3650 -keystore "keystore.jks" -storepass "storepassword" -keypass "keypassword" -alias "default" -dname "CN=127.0.0.1, OU=MyOrgUnit, O=MyOrg, L=MyCity, S=MyRegion, C=MyCountry" - */ - public static void main(String[] args) throws Exception { - ChatServer chatserver = new ChatServer(8887); // Firefox does allow multible ssl connection only via port 443 //tested on FF16 + /* + * Keystore with certificate created like so (in JKS format): + * + *keytool -genkey -validity 3650 -keystore "keystore.jks" -storepass "storepassword" -keypass "keypassword" -alias "default" -dname "CN=127.0.0.1, OU=MyOrgUnit, O=MyOrg, L=MyCity, S=MyRegion, C=MyCountry" + */ + public static void main(String[] args) throws Exception { + ChatServer chatserver = new ChatServer( + 8887); // Firefox does allow multible ssl connection only via port 443 //tested on FF16 - // load up the key store - String STORETYPE = "JKS"; - String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks").toString(); - String STOREPASSWORD = "storepassword"; - String KEYPASSWORD = "keypassword"; + // load up the key store + String STORETYPE = "JKS"; + String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks") + .toString(); + String STOREPASSWORD = "storepassword"; + String KEYPASSWORD = "keypassword"; - KeyStore ks = KeyStore.getInstance(STORETYPE); - File kf = new File(KEYSTORE); - ks.load(new FileInputStream(kf), STOREPASSWORD.toCharArray()); + KeyStore ks = KeyStore.getInstance(STORETYPE); + File kf = new File(KEYSTORE); + ks.load(new FileInputStream(kf), STOREPASSWORD.toCharArray()); - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, KEYPASSWORD.toCharArray()); - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ks); + KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); + kmf.init(ks, KEYPASSWORD.toCharArray()); + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(ks); - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - //Lets remove some ciphers and protocols - SSLEngine engine = sslContext.createSSLEngine(); - List ciphers = new ArrayList( Arrays.asList(engine.getEnabledCipherSuites())); - ciphers.remove("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"); - List protocols = new ArrayList( Arrays.asList(engine.getEnabledProtocols())); - protocols.remove("SSLv3"); - CustomSSLWebSocketServerFactory factory = new CustomSSLWebSocketServerFactory(sslContext, protocols.toArray(new String[]{}), ciphers.toArray(new String[]{})); + //Lets remove some ciphers and protocols + SSLEngine engine = sslContext.createSSLEngine(); + List ciphers = new ArrayList(Arrays.asList(engine.getEnabledCipherSuites())); + ciphers.remove("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"); + List protocols = new ArrayList(Arrays.asList(engine.getEnabledProtocols())); + protocols.remove("SSLv3"); + CustomSSLWebSocketServerFactory factory = new CustomSSLWebSocketServerFactory(sslContext, + protocols.toArray(new String[]{}), ciphers.toArray(new String[]{})); - // Different example just using specific ciphers and protocols + // Different example just using specific ciphers and protocols /* String[] enabledProtocols = {"TLSv1.2"}; String[] enabledCipherSuites = {"TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA"}; CustomSSLWebSocketServerFactory factory = new CustomSSLWebSocketServerFactory(sslContext, enabledProtocols,enabledCipherSuites); */ - chatserver.setWebSocketFactory(factory); + chatserver.setWebSocketFactory(factory); - chatserver.start(); + chatserver.start(); - } + } } diff --git a/src/main/example/SSLServerExample.java b/src/main/example/SSLServerExample.java index a72f56b99..9d1f714ad 100644 --- a/src/main/example/SSLServerExample.java +++ b/src/main/example/SSLServerExample.java @@ -39,36 +39,38 @@ public class SSLServerExample { - /* - * Keystore with certificate created like so (in JKS format): - * - *keytool -genkey -keyalg RSA -validity 3650 -keystore "keystore.jks" -storepass "storepassword" -keypass "keypassword" -alias "default" -dname "CN=127.0.0.1, OU=MyOrgUnit, O=MyOrg, L=MyCity, S=MyRegion, C=MyCountry" - */ - public static void main( String[] args ) throws Exception { - ChatServer chatserver = new ChatServer( 8887 ); // Firefox does allow multible ssl connection only via port 443 //tested on FF16 + /* + * Keystore with certificate created like so (in JKS format): + * + *keytool -genkey -keyalg RSA -validity 3650 -keystore "keystore.jks" -storepass "storepassword" -keypass "keypassword" -alias "default" -dname "CN=127.0.0.1, OU=MyOrgUnit, O=MyOrg, L=MyCity, S=MyRegion, C=MyCountry" + */ + public static void main(String[] args) throws Exception { + ChatServer chatserver = new ChatServer( + 8887); // Firefox does allow multible ssl connection only via port 443 //tested on FF16 - // load up the key store - String STORETYPE = "JKS"; - String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks").toString(); - String STOREPASSWORD = "storepassword"; - String KEYPASSWORD = "keypassword"; + // load up the key store + String STORETYPE = "JKS"; + String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks") + .toString(); + String STOREPASSWORD = "storepassword"; + String KEYPASSWORD = "keypassword"; - KeyStore ks = KeyStore.getInstance( STORETYPE ); - File kf = new File( KEYSTORE ); - ks.load( new FileInputStream( kf ), STOREPASSWORD.toCharArray() ); + KeyStore ks = KeyStore.getInstance(STORETYPE); + File kf = new File(KEYSTORE); + ks.load(new FileInputStream(kf), STOREPASSWORD.toCharArray()); - KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" ); - kmf.init( ks, KEYPASSWORD.toCharArray() ); - TrustManagerFactory tmf = TrustManagerFactory.getInstance( "SunX509" ); - tmf.init( ks ); + KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); + kmf.init(ks, KEYPASSWORD.toCharArray()); + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(ks); - SSLContext sslContext = null; - sslContext = SSLContext.getInstance( "TLS" ); - sslContext.init( kmf.getKeyManagers(), tmf.getTrustManagers(), null ); + SSLContext sslContext = null; + sslContext = SSLContext.getInstance("TLS"); + sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - chatserver.setWebSocketFactory( new DefaultSSLWebSocketServerFactory( sslContext ) ); + chatserver.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext)); - chatserver.start(); + chatserver.start(); - } + } } diff --git a/src/main/example/SSLServerLetsEncryptExample.java b/src/main/example/SSLServerLetsEncryptExample.java index 10e61340f..5f32d1a50 100644 --- a/src/main/example/SSLServerLetsEncryptExample.java +++ b/src/main/example/SSLServerLetsEncryptExample.java @@ -47,85 +47,89 @@ /** - * SSL Example using the LetsEncrypt certificate - * See https://github.com/TooTallNate/Java-WebSocket/wiki/Getting-a-SSLContext-from-different-sources#getting-a-sslcontext-using-a-lets-encrypt-certificate + * SSL Example using the LetsEncrypt certificate See https://github.com/TooTallNate/Java-WebSocket/wiki/Getting-a-SSLContext-from-different-sources#getting-a-sslcontext-using-a-lets-encrypt-certificate */ public class SSLServerLetsEncryptExample { - public static void main( String[] args ) throws Exception { - ChatServer chatserver = new ChatServer( 8887 ); - - SSLContext context = getContext(); - if( context != null ) { - chatserver.setWebSocketFactory( new DefaultSSLWebSocketServerFactory( getContext() ) ); - } - chatserver.setConnectionLostTimeout( 30 ); - chatserver.start(); - - } - - private static SSLContext getContext() { - SSLContext context; - String password = "CHANGEIT"; - String pathname = "pem"; - try { - context = SSLContext.getInstance( "TLS" ); - - byte[] certBytes = parseDERFromPEM( getBytes( new File( pathname + File.separator + "cert.pem" ) ), "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----" ); - byte[] keyBytes = parseDERFromPEM( getBytes( new File( pathname + File.separator + "privkey.pem" ) ), "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----" ); - - X509Certificate cert = generateCertificateFromDER( certBytes ); - RSAPrivateKey key = generatePrivateKeyFromDER( keyBytes ); - - KeyStore keystore = KeyStore.getInstance( "JKS" ); - keystore.load( null ); - keystore.setCertificateEntry( "cert-alias", cert ); - keystore.setKeyEntry( "key-alias", key, password.toCharArray(), new Certificate[]{ cert } ); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" ); - kmf.init( keystore, password.toCharArray() ); - - KeyManager[] km = kmf.getKeyManagers(); - - context.init( km, null, null ); - } catch ( Exception e ) { - context = null; - } - return context; - } - - private static byte[] parseDERFromPEM( byte[] pem, String beginDelimiter, String endDelimiter ) { - String data = new String( pem ); - String[] tokens = data.split( beginDelimiter ); - tokens = tokens[1].split( endDelimiter ); - return DatatypeConverter.parseBase64Binary( tokens[0] ); - } - - private static RSAPrivateKey generatePrivateKeyFromDER( byte[] keyBytes ) throws InvalidKeySpecException, NoSuchAlgorithmException { - PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec( keyBytes ); - - KeyFactory factory = KeyFactory.getInstance( "RSA" ); - - return ( RSAPrivateKey ) factory.generatePrivate( spec ); - } - - private static X509Certificate generateCertificateFromDER( byte[] certBytes ) throws CertificateException { - CertificateFactory factory = CertificateFactory.getInstance( "X.509" ); - - return ( X509Certificate ) factory.generateCertificate( new ByteArrayInputStream( certBytes ) ); - } - - private static byte[] getBytes( File file ) { - byte[] bytesArray = new byte[( int ) file.length()]; - - FileInputStream fis = null; - try { - fis = new FileInputStream( file ); - fis.read( bytesArray ); //read file into bytes[] - fis.close(); - } catch ( IOException e ) { - e.printStackTrace(); - } - return bytesArray; - } + public static void main(String[] args) throws Exception { + ChatServer chatserver = new ChatServer(8887); + + SSLContext context = getContext(); + if (context != null) { + chatserver.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(getContext())); + } + chatserver.setConnectionLostTimeout(30); + chatserver.start(); + + } + + private static SSLContext getContext() { + SSLContext context; + String password = "CHANGEIT"; + String pathname = "pem"; + try { + context = SSLContext.getInstance("TLS"); + + byte[] certBytes = parseDERFromPEM(getBytes(new File(pathname + File.separator + "cert.pem")), + "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----"); + byte[] keyBytes = parseDERFromPEM( + getBytes(new File(pathname + File.separator + "privkey.pem")), + "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----"); + + X509Certificate cert = generateCertificateFromDER(certBytes); + RSAPrivateKey key = generatePrivateKeyFromDER(keyBytes); + + KeyStore keystore = KeyStore.getInstance("JKS"); + keystore.load(null); + keystore.setCertificateEntry("cert-alias", cert); + keystore.setKeyEntry("key-alias", key, password.toCharArray(), new Certificate[]{cert}); + + KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); + kmf.init(keystore, password.toCharArray()); + + KeyManager[] km = kmf.getKeyManagers(); + + context.init(km, null, null); + } catch (Exception e) { + context = null; + } + return context; + } + + private static byte[] parseDERFromPEM(byte[] pem, String beginDelimiter, String endDelimiter) { + String data = new String(pem); + String[] tokens = data.split(beginDelimiter); + tokens = tokens[1].split(endDelimiter); + return DatatypeConverter.parseBase64Binary(tokens[0]); + } + + private static RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) + throws InvalidKeySpecException, NoSuchAlgorithmException { + PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); + + KeyFactory factory = KeyFactory.getInstance("RSA"); + + return (RSAPrivateKey) factory.generatePrivate(spec); + } + + private static X509Certificate generateCertificateFromDER(byte[] certBytes) + throws CertificateException { + CertificateFactory factory = CertificateFactory.getInstance("X.509"); + + return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certBytes)); + } + + private static byte[] getBytes(File file) { + byte[] bytesArray = new byte[(int) file.length()]; + + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + fis.read(bytesArray); //read file into bytes[] + fis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return bytesArray; + } } diff --git a/src/main/example/SecWebSocketProtocolClientExample.java b/src/main/example/SecWebSocketProtocolClientExample.java index 45b99d114..9f12f2d20 100644 --- a/src/main/example/SecWebSocketProtocolClientExample.java +++ b/src/main/example/SecWebSocketProtocolClientExample.java @@ -39,17 +39,19 @@ */ public class SecWebSocketProtocolClientExample { - public static void main( String[] args ) throws URISyntaxException { - // This draft only allows you to use the specific Sec-WebSocket-Protocol without a fallback. - Draft_6455 draft_ocppOnly = new Draft_6455(Collections.emptyList(), Collections.singletonList(new Protocol("ocpp2.0"))); + public static void main(String[] args) throws URISyntaxException { + // This draft only allows you to use the specific Sec-WebSocket-Protocol without a fallback. + Draft_6455 draft_ocppOnly = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("ocpp2.0"))); - // This draft allows the specific Sec-WebSocket-Protocol and also provides a fallback, if the other endpoint does not accept the specific Sec-WebSocket-Protocol - ArrayList protocols = new ArrayList(); - protocols.add(new Protocol("ocpp2.0")); - protocols.add(new Protocol("")); - Draft_6455 draft_ocppAndFallBack = new Draft_6455(Collections.emptyList(), protocols); + // This draft allows the specific Sec-WebSocket-Protocol and also provides a fallback, if the other endpoint does not accept the specific Sec-WebSocket-Protocol + ArrayList protocols = new ArrayList(); + protocols.add(new Protocol("ocpp2.0")); + protocols.add(new Protocol("")); + Draft_6455 draft_ocppAndFallBack = new Draft_6455(Collections.emptyList(), + protocols); - ExampleClient c = new ExampleClient( new URI( "ws://echo.websocket.org" ), draft_ocppAndFallBack ); - c.connect(); - } + ExampleClient c = new ExampleClient(new URI("ws://echo.websocket.org"), draft_ocppAndFallBack); + c.connect(); + } } diff --git a/src/main/example/SecWebSocketProtocolServerExample.java b/src/main/example/SecWebSocketProtocolServerExample.java index 911961240..9a2790d36 100644 --- a/src/main/example/SecWebSocketProtocolServerExample.java +++ b/src/main/example/SecWebSocketProtocolServerExample.java @@ -38,17 +38,19 @@ */ public class SecWebSocketProtocolServerExample { - public static void main( String[] args ) throws URISyntaxException { - // This draft only allows you to use the specific Sec-WebSocket-Protocol without a fallback. - Draft_6455 draft_ocppOnly = new Draft_6455(Collections.emptyList(), Collections.singletonList(new Protocol("ocpp2.0"))); + public static void main(String[] args) throws URISyntaxException { + // This draft only allows you to use the specific Sec-WebSocket-Protocol without a fallback. + Draft_6455 draft_ocppOnly = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("ocpp2.0"))); - // This draft allows the specific Sec-WebSocket-Protocol and also provides a fallback, if the other endpoint does not accept the specific Sec-WebSocket-Protocol - ArrayList protocols = new ArrayList(); - protocols.add(new Protocol("ocpp2.0")); - protocols.add(new Protocol("")); - Draft_6455 draft_ocppAndFallBack = new Draft_6455(Collections.emptyList(), protocols); + // This draft allows the specific Sec-WebSocket-Protocol and also provides a fallback, if the other endpoint does not accept the specific Sec-WebSocket-Protocol + ArrayList protocols = new ArrayList(); + protocols.add(new Protocol("ocpp2.0")); + protocols.add(new Protocol("")); + Draft_6455 draft_ocppAndFallBack = new Draft_6455(Collections.emptyList(), + protocols); - ChatServer chatServer = new ChatServer(8887, draft_ocppOnly); - chatServer.start(); - } + ChatServer chatServer = new ChatServer(8887, draft_ocppOnly); + chatServer.start(); + } } diff --git a/src/main/example/ServerAdditionalHeaderExample.java b/src/main/example/ServerAdditionalHeaderExample.java index b284abd5b..1aa99c499 100644 --- a/src/main/example/ServerAdditionalHeaderExample.java +++ b/src/main/example/ServerAdditionalHeaderExample.java @@ -38,43 +38,45 @@ /** * This example shows how to add additional headers to your server handshake response - * + *

    * For this you have to override onWebsocketHandshakeReceivedAsServer in your WebSocketServer class - * + *

    * We are simple adding the additional header "Access-Control-Allow-Origin" to our server response */ public class ServerAdditionalHeaderExample extends ChatServer { - public ServerAdditionalHeaderExample( int port ) { - super( new InetSocketAddress( port )); - } + public ServerAdditionalHeaderExample(int port) { + super(new InetSocketAddress(port)); + } - @Override - public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer( WebSocket conn, Draft draft, ClientHandshake request) throws InvalidDataException { - ServerHandshakeBuilder builder = super.onWebsocketHandshakeReceivedAsServer( conn, draft, request ); - builder.put( "Access-Control-Allow-Origin" , "*"); - return builder; - } + @Override + public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft, + ClientHandshake request) throws InvalidDataException { + ServerHandshakeBuilder builder = super + .onWebsocketHandshakeReceivedAsServer(conn, draft, request); + builder.put("Access-Control-Allow-Origin", "*"); + return builder; + } - public static void main( String[] args ) throws InterruptedException , IOException { - int port = 8887; // 843 flash policy port - try { - port = Integer.parseInt( args[ 0 ] ); - } catch ( Exception ex ) { - } - ServerAdditionalHeaderExample s = new ServerAdditionalHeaderExample( port ); - s.start(); - System.out.println( "Server started on port: " + s.getPort() ); + public static void main(String[] args) throws InterruptedException, IOException { + int port = 8887; // 843 flash policy port + try { + port = Integer.parseInt(args[0]); + } catch (Exception ex) { + } + ServerAdditionalHeaderExample s = new ServerAdditionalHeaderExample(port); + s.start(); + System.out.println("Server started on port: " + s.getPort()); - BufferedReader sysin = new BufferedReader( new InputStreamReader( System.in ) ); - while ( true ) { - String in = sysin.readLine(); - s.broadcast( in ); - if( in.equals( "exit" ) ) { - s.stop(1000); - break; - } - } - } + BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in)); + while (true) { + String in = sysin.readLine(); + s.broadcast(in); + if (in.equals("exit")) { + s.stop(1000); + break; + } + } + } } diff --git a/src/main/example/ServerRejectHandshakeExample.java b/src/main/example/ServerRejectHandshakeExample.java index de312851e..9c53eb38b 100644 --- a/src/main/example/ServerRejectHandshakeExample.java +++ b/src/main/example/ServerRejectHandshakeExample.java @@ -38,58 +38,60 @@ /** * This example shows how to reject a handshake as a server from a client. - * + *

    * For this you have to override onWebsocketHandshakeReceivedAsServer in your WebSocketServer class */ public class ServerRejectHandshakeExample extends ChatServer { - public ServerRejectHandshakeExample( int port ) { - super( new InetSocketAddress( port )); - } + public ServerRejectHandshakeExample(int port) { + super(new InetSocketAddress(port)); + } - @Override - public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer( WebSocket conn, Draft draft, ClientHandshake request) throws InvalidDataException { - ServerHandshakeBuilder builder = super.onWebsocketHandshakeReceivedAsServer( conn, draft, request ); - //In this example we don't allow any resource descriptor ( "ws://localhost:8887/?roomid=1 will be rejected but ws://localhost:8887 is fine) - if (! request.getResourceDescriptor().equals( "/" )) { - throw new InvalidDataException( CloseFrame.POLICY_VALIDATION, "Not accepted!"); - } - //If there are no cookies set reject it as well. - if (!request.hasFieldValue( "Cookie" )) { - throw new InvalidDataException( CloseFrame.POLICY_VALIDATION, "Not accepted!"); - } - //If the cookie does not contain a specific value - if (!request.getFieldValue( "Cookie" ).equals( "username=nemo" )) { - throw new InvalidDataException( CloseFrame.POLICY_VALIDATION, "Not accepted!"); - } - //If there is a Origin Field, it has to be localhost:8887 - if (request.hasFieldValue( "Origin" )) { - if (!request.getFieldValue( "Origin" ).equals( "localhost:8887" )) { - throw new InvalidDataException( CloseFrame.POLICY_VALIDATION, "Not accepted!"); - } - } - return builder; - } + @Override + public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft, + ClientHandshake request) throws InvalidDataException { + ServerHandshakeBuilder builder = super + .onWebsocketHandshakeReceivedAsServer(conn, draft, request); + //In this example we don't allow any resource descriptor ( "ws://localhost:8887/?roomid=1 will be rejected but ws://localhost:8887 is fine) + if (!request.getResourceDescriptor().equals("/")) { + throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "Not accepted!"); + } + //If there are no cookies set reject it as well. + if (!request.hasFieldValue("Cookie")) { + throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "Not accepted!"); + } + //If the cookie does not contain a specific value + if (!request.getFieldValue("Cookie").equals("username=nemo")) { + throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "Not accepted!"); + } + //If there is a Origin Field, it has to be localhost:8887 + if (request.hasFieldValue("Origin")) { + if (!request.getFieldValue("Origin").equals("localhost:8887")) { + throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "Not accepted!"); + } + } + return builder; + } - public static void main( String[] args ) throws InterruptedException , IOException { - int port = 8887; // 843 flash policy port - try { - port = Integer.parseInt( args[ 0 ] ); - } catch ( Exception ex ) { - } - ServerRejectHandshakeExample s = new ServerRejectHandshakeExample( port ); - s.start(); - System.out.println( "Server started on port: " + s.getPort() ); + public static void main(String[] args) throws InterruptedException, IOException { + int port = 8887; // 843 flash policy port + try { + port = Integer.parseInt(args[0]); + } catch (Exception ex) { + } + ServerRejectHandshakeExample s = new ServerRejectHandshakeExample(port); + s.start(); + System.out.println("Server started on port: " + s.getPort()); - BufferedReader sysin = new BufferedReader( new InputStreamReader( System.in ) ); - while ( true ) { - String in = sysin.readLine(); - s.broadcast( in ); - if( in.equals( "exit" ) ) { - s.stop(1000); - break; - } - } - } + BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in)); + while (true) { + String in = sysin.readLine(); + s.broadcast(in); + if (in.equals("exit")) { + s.stop(1000); + break; + } + } + } } diff --git a/src/main/example/ServerStressTest.java b/src/main/example/ServerStressTest.java index e641a0eb3..c15907da4 100644 --- a/src/main/example/ServerStressTest.java +++ b/src/main/example/ServerStressTest.java @@ -49,194 +49,202 @@ import org.java_websocket.exceptions.WebsocketNotConnectedException; public class ServerStressTest extends JFrame { - private JSlider clients; - private JSlider interval; - private JSlider joinrate; - private JButton start, stop, reset; - private JLabel joinratelabel = new JLabel(); - private JLabel clientslabel = new JLabel(); - private JLabel intervallabel = new JLabel(); - private JTextField uriinput = new JTextField( "ws://localhost:8887" ); - private JTextArea text = new JTextArea( "payload" ); - private Timer timer = new Timer( true ); - private Thread adjustthread; - - private int notyetconnected = 0; - - public ServerStressTest() { - setTitle( "ServerStressTest" ); - setDefaultCloseOperation( EXIT_ON_CLOSE ); - start = new JButton( "Start" ); - start.addActionListener( new ActionListener() { - - @Override - public void actionPerformed( ActionEvent e ) { - start.setEnabled( false ); - stop.setEnabled( true ); - reset.setEnabled( false ); - interval.setEnabled( false ); - clients.setEnabled( false ); - - stopAdjust(); - adjustthread = new Thread( new Runnable() { - @Override - public void run() { - try { - adjust(); - } catch ( InterruptedException e ) { - System.out.println( "adjust chanced" ); - } - } - } ); - adjustthread.start(); - - } - } ); - stop = new JButton( "Stop" ); - stop.setEnabled( false ); - stop.addActionListener( new ActionListener() { - - @Override - public void actionPerformed( ActionEvent e ) { - timer.cancel(); - stopAdjust(); - start.setEnabled( true ); - stop.setEnabled( false ); - reset.setEnabled( true ); - joinrate.setEnabled( true ); - interval.setEnabled( true ); - clients.setEnabled( true ); - } - } ); - reset = new JButton( "reset" ); - reset.setEnabled( true ); - reset.addActionListener( new ActionListener() { - - @Override - public void actionPerformed( ActionEvent e ) { - while ( !websockets.isEmpty() ) - websockets.remove( 0 ).close(); - - } - } ); - joinrate = new JSlider( 0, 5000 ); - joinrate.addChangeListener( new ChangeListener() { - @Override - public void stateChanged( ChangeEvent e ) { - joinratelabel.setText( "Joinrate: " + joinrate.getValue() + " ms " ); - } - } ); - clients = new JSlider( 0, 10000 ); - clients.addChangeListener( new ChangeListener() { - - @Override - public void stateChanged( ChangeEvent e ) { - clientslabel.setText( "Clients: " + clients.getValue() ); - - } - } ); - interval = new JSlider( 0, 5000 ); - interval.addChangeListener( new ChangeListener() { - - @Override - public void stateChanged( ChangeEvent e ) { - intervallabel.setText( "Interval: " + interval.getValue() + " ms " ); - - } - } ); - - setSize( 300, 400 ); - setLayout( new GridLayout( 10, 1, 10, 10 ) ); - add( new JLabel( "URI" ) ); - add( uriinput ); - add( joinratelabel ); - add( joinrate ); - add( clientslabel ); - add( clients ); - add( intervallabel ); - add( interval ); - JPanel south = new JPanel( new FlowLayout( FlowLayout.CENTER ) ); - add( text ); - add( south ); - - south.add( start ); - south.add( stop ); - south.add( reset ); - - joinrate.setValue( 200 ); - interval.setValue( 1000 ); - clients.setValue( 1 ); - - } - - List websockets = Collections.synchronizedList( new LinkedList() ); - URI uri; - public void adjust() throws InterruptedException { - System.out.println( "Adjust" ); - try { - uri = new URI( uriinput.getText() ); - } catch ( URISyntaxException e ) { - e.printStackTrace(); - } - int totalclients = clients.getValue(); - while ( websockets.size() < totalclients ) { - WebSocketClient cl = new ExampleClient( uri ) { - @Override - public void onClose( int code, String reason, boolean remote ) { - System.out.println( "Closed duo " + code + " " + reason ); - clients.setValue( websockets.size() ); - websockets.remove( this ); - } - }; - - cl.connect(); - clients.setValue( websockets.size() ); - websockets.add( cl ); - Thread.sleep( joinrate.getValue() ); - } - while ( websockets.size() > clients.getValue() ) { - websockets.remove( 0 ).close(); - } - timer = new Timer( true ); - timer.scheduleAtFixedRate( new TimerTask() { - @Override - public void run() { - send(); - } - }, 0, interval.getValue() ); - - } - - public void stopAdjust() { - if( adjustthread != null ) { - adjustthread.interrupt(); - try { - adjustthread.join(); - } catch ( InterruptedException e ) { - e.printStackTrace(); - } - } - } - public void send() { - notyetconnected = 0; - String payload = text.getText(); - long time1 = System.currentTimeMillis(); - synchronized ( websockets ) { - for( WebSocketClient cl : websockets ) { - try { - cl.send( payload ); - } catch ( WebsocketNotConnectedException e ) { - notyetconnected++; - } - } - } - System.out.println( websockets.size() + "/" + notyetconnected + " clients sent \"" + payload + "\"" + ( System.currentTimeMillis() - time1 ) ); - } - /** - * @param args - */ - public static void main( String[] args ) { - new ServerStressTest().setVisible( true ); - } + + private JSlider clients; + private JSlider interval; + private JSlider joinrate; + private JButton start, stop, reset; + private JLabel joinratelabel = new JLabel(); + private JLabel clientslabel = new JLabel(); + private JLabel intervallabel = new JLabel(); + private JTextField uriinput = new JTextField("ws://localhost:8887"); + private JTextArea text = new JTextArea("payload"); + private Timer timer = new Timer(true); + private Thread adjustthread; + + private int notyetconnected = 0; + + public ServerStressTest() { + setTitle("ServerStressTest"); + setDefaultCloseOperation(EXIT_ON_CLOSE); + start = new JButton("Start"); + start.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + start.setEnabled(false); + stop.setEnabled(true); + reset.setEnabled(false); + interval.setEnabled(false); + clients.setEnabled(false); + + stopAdjust(); + adjustthread = new Thread(new Runnable() { + @Override + public void run() { + try { + adjust(); + } catch (InterruptedException e) { + System.out.println("adjust chanced"); + } + } + }); + adjustthread.start(); + + } + }); + stop = new JButton("Stop"); + stop.setEnabled(false); + stop.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + timer.cancel(); + stopAdjust(); + start.setEnabled(true); + stop.setEnabled(false); + reset.setEnabled(true); + joinrate.setEnabled(true); + interval.setEnabled(true); + clients.setEnabled(true); + } + }); + reset = new JButton("reset"); + reset.setEnabled(true); + reset.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + while (!websockets.isEmpty()) { + websockets.remove(0).close(); + } + + } + }); + joinrate = new JSlider(0, 5000); + joinrate.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + joinratelabel.setText("Joinrate: " + joinrate.getValue() + " ms "); + } + }); + clients = new JSlider(0, 10000); + clients.addChangeListener(new ChangeListener() { + + @Override + public void stateChanged(ChangeEvent e) { + clientslabel.setText("Clients: " + clients.getValue()); + + } + }); + interval = new JSlider(0, 5000); + interval.addChangeListener(new ChangeListener() { + + @Override + public void stateChanged(ChangeEvent e) { + intervallabel.setText("Interval: " + interval.getValue() + " ms "); + + } + }); + + setSize(300, 400); + setLayout(new GridLayout(10, 1, 10, 10)); + add(new JLabel("URI")); + add(uriinput); + add(joinratelabel); + add(joinrate); + add(clientslabel); + add(clients); + add(intervallabel); + add(interval); + JPanel south = new JPanel(new FlowLayout(FlowLayout.CENTER)); + add(text); + add(south); + + south.add(start); + south.add(stop); + south.add(reset); + + joinrate.setValue(200); + interval.setValue(1000); + clients.setValue(1); + + } + + List websockets = Collections + .synchronizedList(new LinkedList()); + URI uri; + + public void adjust() throws InterruptedException { + System.out.println("Adjust"); + try { + uri = new URI(uriinput.getText()); + } catch (URISyntaxException e) { + e.printStackTrace(); + } + int totalclients = clients.getValue(); + while (websockets.size() < totalclients) { + WebSocketClient cl = new ExampleClient(uri) { + @Override + public void onClose(int code, String reason, boolean remote) { + System.out.println("Closed duo " + code + " " + reason); + clients.setValue(websockets.size()); + websockets.remove(this); + } + }; + + cl.connect(); + clients.setValue(websockets.size()); + websockets.add(cl); + Thread.sleep(joinrate.getValue()); + } + while (websockets.size() > clients.getValue()) { + websockets.remove(0).close(); + } + timer = new Timer(true); + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + send(); + } + }, 0, interval.getValue()); + + } + + public void stopAdjust() { + if (adjustthread != null) { + adjustthread.interrupt(); + try { + adjustthread.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + public void send() { + notyetconnected = 0; + String payload = text.getText(); + long time1 = System.currentTimeMillis(); + synchronized (websockets) { + for (WebSocketClient cl : websockets) { + try { + cl.send(payload); + } catch (WebsocketNotConnectedException e) { + notyetconnected++; + } + } + } + System.out.println( + websockets.size() + "/" + notyetconnected + " clients sent \"" + payload + "\"" + ( + System.currentTimeMillis() - time1)); + } + + /** + * @param args + */ + public static void main(String[] args) { + new ServerStressTest().setVisible(true); + } } diff --git a/src/main/example/TwoWaySSLServerExample.java b/src/main/example/TwoWaySSLServerExample.java index 694e43cda..1ee488089 100644 --- a/src/main/example/TwoWaySSLServerExample.java +++ b/src/main/example/TwoWaySSLServerExample.java @@ -37,43 +37,47 @@ import java.security.KeyStore; /** - * Copy of SSLServerExample except we use @link SSLEngineWebSocketServerFactory to customize clientMode/ClientAuth to force client to present a cert. - * Example of Two-way ssl/MutualAuthentication/ClientAuthentication + * Copy of SSLServerExample except we use @link SSLEngineWebSocketServerFactory to customize + * clientMode/ClientAuth to force client to present a cert. Example of Two-way + * ssl/MutualAuthentication/ClientAuthentication */ public class TwoWaySSLServerExample { - /* - * Keystore with certificate created like so (in JKS format): - * - *keytool -genkey -keyalg RSA -validity 3650 -keystore "keystore.jks" -storepass "storepassword" -keypass "keypassword" -alias "default" -dname "CN=127.0.0.1, OU=MyOrgUnit, O=MyOrg, L=MyCity, S=MyRegion, C=MyCountry" - */ - public static void main( String[] args ) throws Exception { - ChatServer chatserver = new ChatServer( 8887 ); // Firefox does allow multible ssl connection only via port 443 //tested on FF16 + /* + * Keystore with certificate created like so (in JKS format): + * + *keytool -genkey -keyalg RSA -validity 3650 -keystore "keystore.jks" -storepass "storepassword" -keypass "keypassword" -alias "default" -dname "CN=127.0.0.1, OU=MyOrgUnit, O=MyOrg, L=MyCity, S=MyRegion, C=MyCountry" + */ + public static void main(String[] args) throws Exception { + ChatServer chatserver = new ChatServer( + 8887); // Firefox does allow multible ssl connection only via port 443 //tested on FF16 - // load up the key store - String STORETYPE = "JKS"; - String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks").toString(); - String STOREPASSWORD = "storepassword"; - String KEYPASSWORD = "keypassword"; + // load up the key store + String STORETYPE = "JKS"; + String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks") + .toString(); + String STOREPASSWORD = "storepassword"; + String KEYPASSWORD = "keypassword"; - KeyStore ks = KeyStore.getInstance( STORETYPE ); - File kf = new File( KEYSTORE ); - ks.load( new FileInputStream( kf ), STOREPASSWORD.toCharArray() ); + KeyStore ks = KeyStore.getInstance(STORETYPE); + File kf = new File(KEYSTORE); + ks.load(new FileInputStream(kf), STOREPASSWORD.toCharArray()); - KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" ); - kmf.init( ks, KEYPASSWORD.toCharArray() ); - TrustManagerFactory tmf = TrustManagerFactory.getInstance( "SunX509" ); - tmf.init( ks ); + KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); + kmf.init(ks, KEYPASSWORD.toCharArray()); + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(ks); - SSLContext sslContext = SSLContext.getInstance( "TLS" ); - sslContext.init( kmf.getKeyManagers(), tmf.getTrustManagers(), null ); + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - SSLParameters sslParameters = new SSLParameters(); - // This is all we need - sslParameters.setNeedClientAuth(true); - chatserver.setWebSocketFactory( new SSLParametersWebSocketServerFactory(sslContext, sslParameters)); + SSLParameters sslParameters = new SSLParameters(); + // This is all we need + sslParameters.setNeedClientAuth(true); + chatserver + .setWebSocketFactory(new SSLParametersWebSocketServerFactory(sslContext, sslParameters)); - chatserver.start(); + chatserver.start(); - } + } } diff --git a/src/main/java/org/java_websocket/AbstractWebSocket.java b/src/main/java/org/java_websocket/AbstractWebSocket.java index d39c898ec..a5dcb39d8 100644 --- a/src/main/java/org/java_websocket/AbstractWebSocket.java +++ b/src/main/java/org/java_websocket/AbstractWebSocket.java @@ -43,246 +43,267 @@ */ public abstract class AbstractWebSocket extends WebSocketAdapter { - /** - * Logger instance - * - * @since 1.4.0 - */ - private final Logger log = LoggerFactory.getLogger(AbstractWebSocket.class); + /** + * Logger instance + * + * @since 1.4.0 + */ + private final Logger log = LoggerFactory.getLogger(AbstractWebSocket.class); - /** - * Attribute which allows you to deactivate the Nagle's algorithm - * @since 1.3.3 - */ - private boolean tcpNoDelay; + /** + * Attribute which allows you to deactivate the Nagle's algorithm + * + * @since 1.3.3 + */ + private boolean tcpNoDelay; - /** - * Attribute which allows you to enable/disable the SO_REUSEADDR socket option. - * @since 1.3.5 - */ - private boolean reuseAddr; + /** + * Attribute which allows you to enable/disable the SO_REUSEADDR socket option. + * + * @since 1.3.5 + */ + private boolean reuseAddr; - /** - * Attribute for a service that triggers lost connection checking - * @since 1.4.1 - */ - private ScheduledExecutorService connectionLostCheckerService; - /** - * Attribute for a task that checks for lost connections - * @since 1.4.1 - */ - private ScheduledFuture connectionLostCheckerFuture; + /** + * Attribute for a service that triggers lost connection checking + * + * @since 1.4.1 + */ + private ScheduledExecutorService connectionLostCheckerService; + /** + * Attribute for a task that checks for lost connections + * + * @since 1.4.1 + */ + private ScheduledFuture connectionLostCheckerFuture; - /** - * Attribute for the lost connection check interval in nanoseconds - * @since 1.3.4 - */ - private long connectionLostTimeout = TimeUnit.SECONDS.toNanos(60); + /** + * Attribute for the lost connection check interval in nanoseconds + * + * @since 1.3.4 + */ + private long connectionLostTimeout = TimeUnit.SECONDS.toNanos(60); - /** - * Attribute to keep track if the WebSocket Server/Client is running/connected - * @since 1.3.9 - */ - private boolean websocketRunning = false; + /** + * Attribute to keep track if the WebSocket Server/Client is running/connected + * + * @since 1.3.9 + */ + private boolean websocketRunning = false; - /** - * Attribute to sync on - */ - private final Object syncConnectionLost = new Object(); - /** - * Get the interval checking for lost connections - * Default is 60 seconds - * @return the interval in seconds - * @since 1.3.4 - */ - public int getConnectionLostTimeout() { - synchronized (syncConnectionLost) { - return (int) TimeUnit.NANOSECONDS.toSeconds(connectionLostTimeout); - } - } + /** + * Attribute to sync on + */ + private final Object syncConnectionLost = new Object(); - /** - * Setter for the interval checking for lost connections - * A value lower or equal 0 results in the check to be deactivated - * - * @param connectionLostTimeout the interval in seconds - * @since 1.3.4 - */ - public void setConnectionLostTimeout( int connectionLostTimeout ) { - synchronized (syncConnectionLost) { - this.connectionLostTimeout = TimeUnit.SECONDS.toNanos(connectionLostTimeout); - if (this.connectionLostTimeout <= 0) { - log.trace("Connection lost timer stopped"); - cancelConnectionLostTimer(); - return; - } - if (this.websocketRunning) { - log.trace("Connection lost timer restarted"); - //Reset all the pings - try { - ArrayList connections = new ArrayList(getConnections()); - WebSocketImpl webSocketImpl; - for (WebSocket conn : connections) { - if (conn instanceof WebSocketImpl) { - webSocketImpl = (WebSocketImpl) conn; - webSocketImpl.updateLastPong(); - } - } - } catch (Exception e) { - log.error("Exception during connection lost restart", e); - } - restartConnectionLostTimer(); - } - } + /** + * Get the interval checking for lost connections Default is 60 seconds + * + * @return the interval in seconds + * @since 1.3.4 + */ + public int getConnectionLostTimeout() { + synchronized (syncConnectionLost) { + return (int) TimeUnit.NANOSECONDS.toSeconds(connectionLostTimeout); } + } - /** - * Stop the connection lost timer - * @since 1.3.4 - */ - protected void stopConnectionLostTimer() { - synchronized (syncConnectionLost) { - if (connectionLostCheckerService != null || connectionLostCheckerFuture != null) { - this.websocketRunning = false; - log.trace("Connection lost timer stopped"); - cancelConnectionLostTimer(); + /** + * Setter for the interval checking for lost connections A value lower or equal 0 results in the + * check to be deactivated + * + * @param connectionLostTimeout the interval in seconds + * @since 1.3.4 + */ + public void setConnectionLostTimeout(int connectionLostTimeout) { + synchronized (syncConnectionLost) { + this.connectionLostTimeout = TimeUnit.SECONDS.toNanos(connectionLostTimeout); + if (this.connectionLostTimeout <= 0) { + log.trace("Connection lost timer stopped"); + cancelConnectionLostTimer(); + return; + } + if (this.websocketRunning) { + log.trace("Connection lost timer restarted"); + //Reset all the pings + try { + ArrayList connections = new ArrayList(getConnections()); + WebSocketImpl webSocketImpl; + for (WebSocket conn : connections) { + if (conn instanceof WebSocketImpl) { + webSocketImpl = (WebSocketImpl) conn; + webSocketImpl.updateLastPong(); } + } + } catch (Exception e) { + log.error("Exception during connection lost restart", e); } + restartConnectionLostTimer(); + } } - /** - * Start the connection lost timer - * @since 1.3.4 - */ - protected void startConnectionLostTimer() { - synchronized (syncConnectionLost) { - if (this.connectionLostTimeout <= 0) { - log.trace("Connection lost timer deactivated"); - return; - } - log.trace("Connection lost timer started"); - this.websocketRunning = true; - restartConnectionLostTimer(); - } + } + + /** + * Stop the connection lost timer + * + * @since 1.3.4 + */ + protected void stopConnectionLostTimer() { + synchronized (syncConnectionLost) { + if (connectionLostCheckerService != null || connectionLostCheckerFuture != null) { + this.websocketRunning = false; + log.trace("Connection lost timer stopped"); + cancelConnectionLostTimer(); + } } + } - /** - * This methods allows the reset of the connection lost timer in case of a changed parameter - * @since 1.3.4 - */ - private void restartConnectionLostTimer() { - cancelConnectionLostTimer(); - connectionLostCheckerService = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("connectionLostChecker")); - Runnable connectionLostChecker = new Runnable() { + /** + * Start the connection lost timer + * + * @since 1.3.4 + */ + protected void startConnectionLostTimer() { + synchronized (syncConnectionLost) { + if (this.connectionLostTimeout <= 0) { + log.trace("Connection lost timer deactivated"); + return; + } + log.trace("Connection lost timer started"); + this.websocketRunning = true; + restartConnectionLostTimer(); + } + } - /** - * Keep the connections in a separate list to not cause deadlocks - */ - private ArrayList connections = new ArrayList( ); - @Override - public void run() { - connections.clear(); - try { - connections.addAll( getConnections() ); - long minimumPongTime = (long) (System.nanoTime() - ( connectionLostTimeout * 1.5 )); - for( WebSocket conn : connections ) { - executeConnectionLostDetection(conn, minimumPongTime); - } - } catch ( Exception e ) { - //Ignore this exception - } - connections.clear(); - } - }; + /** + * This methods allows the reset of the connection lost timer in case of a changed parameter + * + * @since 1.3.4 + */ + private void restartConnectionLostTimer() { + cancelConnectionLostTimer(); + connectionLostCheckerService = Executors + .newSingleThreadScheduledExecutor(new NamedThreadFactory("connectionLostChecker")); + Runnable connectionLostChecker = new Runnable() { - connectionLostCheckerFuture = connectionLostCheckerService.scheduleAtFixedRate(connectionLostChecker, connectionLostTimeout, connectionLostTimeout, TimeUnit.NANOSECONDS); - } + /** + * Keep the connections in a separate list to not cause deadlocks + */ + private ArrayList connections = new ArrayList(); - /** - * Send a ping to the endpoint or close the connection since the other endpoint did not respond with a ping - * @param webSocket the websocket instance - * @param minimumPongTime the lowest/oldest allowable last pong time (in nanoTime) before we consider the connection to be lost - */ - private void executeConnectionLostDetection(WebSocket webSocket, long minimumPongTime) { - if (!(webSocket instanceof WebSocketImpl)) { - return; - } - WebSocketImpl webSocketImpl = (WebSocketImpl) webSocket; - if( webSocketImpl.getLastPong() < minimumPongTime ) { - log.trace("Closing connection due to no pong received: {}", webSocketImpl); - webSocketImpl.closeConnection( CloseFrame.ABNORMAL_CLOSE, "The connection was closed because the other endpoint did not respond with a pong in time. For more information check: https://github.com/TooTallNate/Java-WebSocket/wiki/Lost-connection-detection" ); - } else { - if( webSocketImpl.isOpen() ) { - webSocketImpl.sendPing(); - } else { - log.trace("Trying to ping a non open connection: {}", webSocketImpl); - } - } - } + @Override + public void run() { + connections.clear(); + try { + connections.addAll(getConnections()); + long minimumPongTime = (long) (System.nanoTime() - (connectionLostTimeout * 1.5)); + for (WebSocket conn : connections) { + executeConnectionLostDetection(conn, minimumPongTime); + } + } catch (Exception e) { + //Ignore this exception + } + connections.clear(); + } + }; - /** - * Getter to get all the currently available connections - * @return the currently available connections - * @since 1.3.4 - */ - protected abstract Collection getConnections(); + connectionLostCheckerFuture = connectionLostCheckerService + .scheduleAtFixedRate(connectionLostChecker, connectionLostTimeout, connectionLostTimeout, + TimeUnit.NANOSECONDS); + } - /** - * Cancel any running timer for the connection lost detection - * @since 1.3.4 - */ - private void cancelConnectionLostTimer() { - if( connectionLostCheckerService != null ) { - connectionLostCheckerService.shutdownNow(); - connectionLostCheckerService = null; - } - if( connectionLostCheckerFuture != null ) { - connectionLostCheckerFuture.cancel(false); - connectionLostCheckerFuture = null; - } + /** + * Send a ping to the endpoint or close the connection since the other endpoint did not respond + * with a ping + * + * @param webSocket the websocket instance + * @param minimumPongTime the lowest/oldest allowable last pong time (in nanoTime) before we + * consider the connection to be lost + */ + private void executeConnectionLostDetection(WebSocket webSocket, long minimumPongTime) { + if (!(webSocket instanceof WebSocketImpl)) { + return; } - - /** - * Tests if TCP_NODELAY is enabled. - * - * @return a boolean indicating whether or not TCP_NODELAY is enabled for new connections. - * @since 1.3.3 - */ - public boolean isTcpNoDelay() { - return tcpNoDelay; + WebSocketImpl webSocketImpl = (WebSocketImpl) webSocket; + if (webSocketImpl.getLastPong() < minimumPongTime) { + log.trace("Closing connection due to no pong received: {}", webSocketImpl); + webSocketImpl.closeConnection(CloseFrame.ABNORMAL_CLOSE, + "The connection was closed because the other endpoint did not respond with a pong in time. For more information check: https://github.com/TooTallNate/Java-WebSocket/wiki/Lost-connection-detection"); + } else { + if (webSocketImpl.isOpen()) { + webSocketImpl.sendPing(); + } else { + log.trace("Trying to ping a non open connection: {}", webSocketImpl); + } } + } - /** - * Setter for tcpNoDelay - *

    - * Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm) for new connections - * - * @param tcpNoDelay true to enable TCP_NODELAY, false to disable. - * @since 1.3.3 - */ - public void setTcpNoDelay( boolean tcpNoDelay ) { - this.tcpNoDelay = tcpNoDelay; + /** + * Getter to get all the currently available connections + * + * @return the currently available connections + * @since 1.3.4 + */ + protected abstract Collection getConnections(); + + /** + * Cancel any running timer for the connection lost detection + * + * @since 1.3.4 + */ + private void cancelConnectionLostTimer() { + if (connectionLostCheckerService != null) { + connectionLostCheckerService.shutdownNow(); + connectionLostCheckerService = null; + } + if (connectionLostCheckerFuture != null) { + connectionLostCheckerFuture.cancel(false); + connectionLostCheckerFuture = null; } + } + + /** + * Tests if TCP_NODELAY is enabled. + * + * @return a boolean indicating whether or not TCP_NODELAY is enabled for new connections. + * @since 1.3.3 + */ + public boolean isTcpNoDelay() { + return tcpNoDelay; + } + + /** + * Setter for tcpNoDelay + *

    + * Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm) for new connections + * + * @param tcpNoDelay true to enable TCP_NODELAY, false to disable. + * @since 1.3.3 + */ + public void setTcpNoDelay(boolean tcpNoDelay) { + this.tcpNoDelay = tcpNoDelay; + } - /** - * Tests Tests if SO_REUSEADDR is enabled. - * - * @return a boolean indicating whether or not SO_REUSEADDR is enabled. - * @since 1.3.5 - */ - public boolean isReuseAddr() { - return reuseAddr; - } + /** + * Tests Tests if SO_REUSEADDR is enabled. + * + * @return a boolean indicating whether or not SO_REUSEADDR is enabled. + * @since 1.3.5 + */ + public boolean isReuseAddr() { + return reuseAddr; + } - /** - * Setter for soReuseAddr - *

    - * Enable/disable SO_REUSEADDR for the socket - * - * @param reuseAddr whether to enable or disable SO_REUSEADDR - * @since 1.3.5 - */ - public void setReuseAddr( boolean reuseAddr ) { - this.reuseAddr = reuseAddr; - } + /** + * Setter for soReuseAddr + *

    + * Enable/disable SO_REUSEADDR for the socket + * + * @param reuseAddr whether to enable or disable SO_REUSEADDR + * @since 1.3.5 + */ + public void setReuseAddr(boolean reuseAddr) { + this.reuseAddr = reuseAddr; + } } diff --git a/src/main/java/org/java_websocket/AbstractWrappedByteChannel.java b/src/main/java/org/java_websocket/AbstractWrappedByteChannel.java index 093c99350..33e6ddcc9 100644 --- a/src/main/java/org/java_websocket/AbstractWrappedByteChannel.java +++ b/src/main/java/org/java_websocket/AbstractWrappedByteChannel.java @@ -36,74 +36,76 @@ @Deprecated public class AbstractWrappedByteChannel implements WrappedByteChannel { - private final ByteChannel channel; - - /** - * @deprecated - */ - @Deprecated - public AbstractWrappedByteChannel( ByteChannel towrap ) { - this.channel = towrap; - } - - /** - * @deprecated - */ - @Deprecated - public AbstractWrappedByteChannel( WrappedByteChannel towrap ) { - this.channel = towrap; - } - - @Override - public int read( ByteBuffer dst ) throws IOException { - return channel.read( dst ); - } - - @Override - public boolean isOpen() { - return channel.isOpen(); - } - - @Override - public void close() throws IOException { - channel.close(); - } - - @Override - public int write( ByteBuffer src ) throws IOException { - return channel.write( src ); - } - - @Override - public boolean isNeedWrite() { - return channel instanceof WrappedByteChannel && ((WrappedByteChannel) channel).isNeedWrite(); - } - - @Override - public void writeMore() throws IOException { - if( channel instanceof WrappedByteChannel ) - ( (WrappedByteChannel) channel ).writeMore(); - - } - - @Override - public boolean isNeedRead() { - return channel instanceof WrappedByteChannel && ((WrappedByteChannel) channel).isNeedRead(); - - } - - @Override - public int readMore( ByteBuffer dst ) throws IOException { - return channel instanceof WrappedByteChannel ? ( (WrappedByteChannel) channel ).readMore( dst ) : 0; - } - - @Override - public boolean isBlocking() { - if( channel instanceof SocketChannel ) - return ( (SocketChannel) channel ).isBlocking(); - else if( channel instanceof WrappedByteChannel ) - return ( (WrappedByteChannel) channel ).isBlocking(); - return false; - } + private final ByteChannel channel; + + /** + * @deprecated + */ + @Deprecated + public AbstractWrappedByteChannel(ByteChannel towrap) { + this.channel = towrap; + } + + /** + * @deprecated + */ + @Deprecated + public AbstractWrappedByteChannel(WrappedByteChannel towrap) { + this.channel = towrap; + } + + @Override + public int read(ByteBuffer dst) throws IOException { + return channel.read(dst); + } + + @Override + public boolean isOpen() { + return channel.isOpen(); + } + + @Override + public void close() throws IOException { + channel.close(); + } + + @Override + public int write(ByteBuffer src) throws IOException { + return channel.write(src); + } + + @Override + public boolean isNeedWrite() { + return channel instanceof WrappedByteChannel && ((WrappedByteChannel) channel).isNeedWrite(); + } + + @Override + public void writeMore() throws IOException { + if (channel instanceof WrappedByteChannel) { + ((WrappedByteChannel) channel).writeMore(); + } + + } + + @Override + public boolean isNeedRead() { + return channel instanceof WrappedByteChannel && ((WrappedByteChannel) channel).isNeedRead(); + + } + + @Override + public int readMore(ByteBuffer dst) throws IOException { + return channel instanceof WrappedByteChannel ? ((WrappedByteChannel) channel).readMore(dst) : 0; + } + + @Override + public boolean isBlocking() { + if (channel instanceof SocketChannel) { + return ((SocketChannel) channel).isBlocking(); + } else if (channel instanceof WrappedByteChannel) { + return ((WrappedByteChannel) channel).isBlocking(); + } + return false; + } } diff --git a/src/main/java/org/java_websocket/SSLSocketChannel.java b/src/main/java/org/java_websocket/SSLSocketChannel.java index a3c0dc30f..11fc2eab7 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel.java @@ -46,476 +46,495 @@ /** * A class that represents an SSL/TLS peer, and can be extended to create a client or a server. - * - * It makes use of the JSSE framework, and specifically the {@link SSLEngine} logic, which - * is described by Oracle as "an advanced API, not appropriate for casual use", since - * it requires the user to implement much of the communication establishment procedure himself. - * More information about it can be found here: http://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#SSLEngine - * - * {@link SSLSocketChannel} implements the handshake protocol, required to establish a connection between two peers, - * which is common for both client and server and provides the abstract {@link SSLSocketChannel#read(ByteBuffer)} and - * {@link SSLSocketChannel#write(ByteBuffer)} (String)} methods, that need to be implemented by the specific SSL/TLS peer - * that is going to extend this class. + *

    + * It makes use of the JSSE framework, and specifically the {@link SSLEngine} logic, which is + * described by Oracle as "an advanced API, not appropriate for casual use", since it requires the + * user to implement much of the communication establishment procedure himself. More information + * about it can be found here: http://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#SSLEngine + *

    + * {@link SSLSocketChannel} implements the handshake protocol, required to establish a connection + * between two peers, which is common for both client and server and provides the abstract {@link + * SSLSocketChannel#read(ByteBuffer)} and {@link SSLSocketChannel#write(ByteBuffer)} (String)} + * methods, that need to be implemented by the specific SSL/TLS peer that is going to extend this + * class. * * @author Alex Karnezis - *

    - * Modified by marci4 to allow the usage as a ByteChannel - *

    - * Permission for usage received at May 25, 2017 by Alex Karnezis + *

    + * Modified by marci4 to allow the usage as a ByteChannel + *

    + * Permission for usage received at May 25, 2017 by Alex Karnezis */ public class SSLSocketChannel implements WrappedByteChannel, ByteChannel, ISSLChannel { - /** - * Logger instance - * - * @since 1.4.0 - */ - private final Logger log = LoggerFactory.getLogger(SSLSocketChannel.class); - - /** - * The underlying socket channel - */ - private final SocketChannel socketChannel; - - /** - * The engine which will be used for un-/wrapping of buffers - */ - private final SSLEngine engine; - - - /** - * Will contain this peer's application data in plaintext, that will be later encrypted - * using {@link SSLEngine#wrap(ByteBuffer, ByteBuffer)} and sent to the other peer. This buffer can typically - * be of any size, as long as it is large enough to contain this peer's outgoing messages. - * If this peer tries to send a message bigger than buffer's capacity a {@link BufferOverflowException} - * will be thrown. - */ - private ByteBuffer myAppData; - - /** - * Will contain this peer's encrypted data, that will be generated after {@link SSLEngine#wrap(ByteBuffer, ByteBuffer)} - * is applied on {@link SSLSocketChannel#myAppData}. It should be initialized using {@link SSLSession#getPacketBufferSize()}, - * which returns the size up to which, SSL/TLS packets will be generated from the engine under a session. - * All SSLEngine network buffers should be sized at least this large to avoid insufficient space problems when performing wrap and unwrap calls. - */ - private ByteBuffer myNetData; - - /** - * Will contain the other peer's (decrypted) application data. It must be large enough to hold the application data - * from any peer. Can be initialized with {@link SSLSession#getApplicationBufferSize()} for an estimation - * of the other peer's application data and should be enlarged if this size is not enough. - */ - private ByteBuffer peerAppData; - - /** - * Will contain the other peer's encrypted data. The SSL/TLS protocols specify that implementations should produce packets containing at most 16 KB of plaintext, - * so a buffer sized to this value should normally cause no capacity problems. However, some implementations violate the specification and generate large records up to 32 KB. - * If the {@link SSLEngine#unwrap(ByteBuffer, ByteBuffer)} detects large inbound packets, the buffer sizes returned by SSLSession will be updated dynamically, so the this peer - * should check for overflow conditions and enlarge the buffer using the session's (updated) buffer size. - */ - private ByteBuffer peerNetData; - - /** - * Will be used to execute tasks that may emerge during handshake in parallel with the server's main thread. - */ - private ExecutorService executor; - - - public SSLSocketChannel( SocketChannel inputSocketChannel, SSLEngine inputEngine, ExecutorService inputExecutor, SelectionKey key ) throws IOException { - if( inputSocketChannel == null || inputEngine == null || executor == inputExecutor ) - throw new IllegalArgumentException( "parameter must not be null" ); - - this.socketChannel = inputSocketChannel; - this.engine = inputEngine; - this.executor = inputExecutor; - myNetData = ByteBuffer.allocate( engine.getSession().getPacketBufferSize() ); - peerNetData = ByteBuffer.allocate( engine.getSession().getPacketBufferSize() ); - this.engine.beginHandshake(); - if( doHandshake() ) { - if( key != null ) { - key.interestOps( key.interestOps() | SelectionKey.OP_WRITE ); - } - } else { - try { - socketChannel.close(); - } catch ( IOException e ) { - log.error("Exception during the closing of the channel", e); - } - } - } - - @Override - public synchronized int read( ByteBuffer dst ) throws IOException { - if( !dst.hasRemaining() ) { - return 0; - } - if( peerAppData.hasRemaining() ) { - peerAppData.flip(); - return ByteBufferUtils.transferByteBuffer( peerAppData, dst ); - } - peerNetData.compact(); - - int bytesRead = socketChannel.read( peerNetData ); - /* - * If bytesRead are 0 put we still have some data in peerNetData still to an unwrap (for testcase 1.1.6) - */ - if( bytesRead > 0 || peerNetData.hasRemaining() ) { - peerNetData.flip(); - while( peerNetData.hasRemaining() ) { - peerAppData.compact(); - SSLEngineResult result; - try { - result = engine.unwrap( peerNetData, peerAppData ); - } catch ( SSLException e ) { - log.error("SSLException during unwrap", e); - throw e; - } - switch(result.getStatus()) { - case OK: - peerAppData.flip(); - return ByteBufferUtils.transferByteBuffer( peerAppData, dst ); - case BUFFER_UNDERFLOW: - peerAppData.flip(); - return ByteBufferUtils.transferByteBuffer( peerAppData, dst ); - case BUFFER_OVERFLOW: - peerAppData = enlargeApplicationBuffer( peerAppData ); - return read(dst); - case CLOSED: - closeConnection(); - dst.clear(); - return -1; - default: - throw new IllegalStateException( "Invalid SSL status: " + result.getStatus() ); - } - } - } else if( bytesRead < 0 ) { - handleEndOfStream(); - } - ByteBufferUtils.transferByteBuffer( peerAppData, dst ); - return bytesRead; - } - - @Override - public synchronized int write( ByteBuffer output ) throws IOException { - int num = 0; - while( output.hasRemaining() ) { - // The loop has a meaning for (outgoing) messages larger than 16KB. - // Every wrap call will remove 16KB from the original message and send it to the remote peer. - myNetData.clear(); - SSLEngineResult result = engine.wrap( output, myNetData ); - switch(result.getStatus()) { - case OK: - myNetData.flip(); - while( myNetData.hasRemaining() ) { - num += socketChannel.write( myNetData ); - } - break; - case BUFFER_OVERFLOW: - myNetData = enlargePacketBuffer( myNetData ); - break; - case BUFFER_UNDERFLOW: - throw new SSLException( "Buffer underflow occurred after a wrap. I don't think we should ever get here." ); - case CLOSED: - closeConnection(); - return 0; - default: - throw new IllegalStateException( "Invalid SSL status: " + result.getStatus() ); - } - } - return num; - } - - /** - * Implements the handshake protocol between two peers, required for the establishment of the SSL/TLS connection. - * During the handshake, encryption configuration information - such as the list of available cipher suites - will be exchanged - * and if the handshake is successful will lead to an established SSL/TLS session. - *

    - *

    - * A typical handshake will usually contain the following steps: - *

    - *

      - *
    • 1. wrap: ClientHello
    • - *
    • 2. unwrap: ServerHello/Cert/ServerHelloDone
    • - *
    • 3. wrap: ClientKeyExchange
    • - *
    • 4. wrap: ChangeCipherSpec
    • - *
    • 5. wrap: Finished
    • - *
    • 6. unwrap: ChangeCipherSpec
    • - *
    • 7. unwrap: Finished
    • - *
    - *

    - * Handshake is also used during the end of the session, in order to properly close the connection between the two peers. - * A proper connection close will typically include the one peer sending a CLOSE message to another, and then wait for - * the other's CLOSE message to close the transport link. The other peer from his perspective would read a CLOSE message - * from his peer and then enter the handshake procedure to send his own CLOSE message as well. - * - * @return True if the connection handshake was successful or false if an error occurred. - * @throws IOException - if an error occurs during read/write to the socket channel. - */ - private boolean doHandshake() throws IOException { - SSLEngineResult result; - HandshakeStatus handshakeStatus; - - // NioSslPeer's fields myAppData and peerAppData are supposed to be large enough to hold all message data the peer - // will send and expects to receive from the other peer respectively. Since the messages to be exchanged will usually be less - // than 16KB long the capacity of these fields should also be smaller. Here we initialize these two local buffers - // to be used for the handshake, while keeping client's buffers at the same size. - int appBufferSize = engine.getSession().getApplicationBufferSize(); - myAppData = ByteBuffer.allocate( appBufferSize ); - peerAppData = ByteBuffer.allocate( appBufferSize ); - myNetData.clear(); - peerNetData.clear(); - - handshakeStatus = engine.getHandshakeStatus(); - boolean handshakeComplete = false; - while( !handshakeComplete) { - switch(handshakeStatus) { - case FINISHED: - handshakeComplete = !this.peerNetData.hasRemaining(); - if (handshakeComplete) - return true; - socketChannel.write(this.peerNetData); - break; - case NEED_UNWRAP: - if( socketChannel.read( peerNetData ) < 0 ) { - if( engine.isInboundDone() && engine.isOutboundDone() ) { - return false; - } - try { - engine.closeInbound(); - } catch ( SSLException e ) { - //Ignore, can't do anything against this exception - } - engine.closeOutbound(); - // After closeOutbound the engine will be set to WRAP state, in order to try to send a close message to the client. - handshakeStatus = engine.getHandshakeStatus(); - break; - } - peerNetData.flip(); - try { - result = engine.unwrap( peerNetData, peerAppData ); - peerNetData.compact(); - handshakeStatus = result.getHandshakeStatus(); - } catch ( SSLException sslException ) { - engine.closeOutbound(); - handshakeStatus = engine.getHandshakeStatus(); - break; - } - switch(result.getStatus()) { - case OK: - break; - case BUFFER_OVERFLOW: - // Will occur when peerAppData's capacity is smaller than the data derived from peerNetData's unwrap. - peerAppData = enlargeApplicationBuffer( peerAppData ); - break; - case BUFFER_UNDERFLOW: - // Will occur either when no data was read from the peer or when the peerNetData buffer was too small to hold all peer's data. - peerNetData = handleBufferUnderflow( peerNetData ); - break; - case CLOSED: - if( engine.isOutboundDone() ) { - return false; - } else { - engine.closeOutbound(); - handshakeStatus = engine.getHandshakeStatus(); - break; - } - default: - throw new IllegalStateException( "Invalid SSL status: " + result.getStatus() ); - } - break; - case NEED_WRAP: - myNetData.clear(); - try { - result = engine.wrap( myAppData, myNetData ); - handshakeStatus = result.getHandshakeStatus(); - } catch ( SSLException sslException ) { - engine.closeOutbound(); - handshakeStatus = engine.getHandshakeStatus(); - break; - } - switch(result.getStatus()) { - case OK: - myNetData.flip(); - while( myNetData.hasRemaining() ) { - socketChannel.write( myNetData ); - } - break; - case BUFFER_OVERFLOW: - // Will occur if there is not enough space in myNetData buffer to write all the data that would be generated by the method wrap. - // Since myNetData is set to session's packet size we should not get to this point because SSLEngine is supposed - // to produce messages smaller or equal to that, but a general handling would be the following: - myNetData = enlargePacketBuffer( myNetData ); - break; - case BUFFER_UNDERFLOW: - throw new SSLException( "Buffer underflow occurred after a wrap. I don't think we should ever get here." ); - case CLOSED: - try { - myNetData.flip(); - while( myNetData.hasRemaining() ) { - socketChannel.write( myNetData ); - } - // At this point the handshake status will probably be NEED_UNWRAP so we make sure that peerNetData is clear to read. - peerNetData.clear(); - } catch ( Exception e ) { - handshakeStatus = engine.getHandshakeStatus(); - } - break; - default: - throw new IllegalStateException( "Invalid SSL status: " + result.getStatus() ); - } - break; - case NEED_TASK: - Runnable task; - while( ( task = engine.getDelegatedTask() ) != null ) { - executor.execute( task ); - } - handshakeStatus = engine.getHandshakeStatus(); - break; - - case NOT_HANDSHAKING: - break; - default: - throw new IllegalStateException( "Invalid SSL status: " + handshakeStatus ); - } - } - - return true; - - } - - /** - * Enlarging a packet buffer (peerNetData or myNetData) - * - * @param buffer the buffer to enlarge - * @return the enlarged buffer - */ - private ByteBuffer enlargePacketBuffer( ByteBuffer buffer ) { - return enlargeBuffer( buffer, engine.getSession().getPacketBufferSize() ); - } - - /** - * Enlarging a packet buffer (peerAppData or myAppData) - * - * @param buffer the buffer to enlarge - * @return the enlarged buffer - */ - private ByteBuffer enlargeApplicationBuffer( ByteBuffer buffer ) { - return enlargeBuffer( buffer, engine.getSession().getApplicationBufferSize() ); - } - - /** - * Compares sessionProposedCapacity with buffer's capacity. If buffer's capacity is smaller, - * returns a buffer with the proposed capacity. If it's equal or larger, returns a buffer - * with capacity twice the size of the initial one. - * - * @param buffer - the buffer to be enlarged. - * @param sessionProposedCapacity - the minimum size of the new buffer, proposed by {@link SSLSession}. - * @return A new buffer with a larger capacity. - */ - private ByteBuffer enlargeBuffer( ByteBuffer buffer, int sessionProposedCapacity ) { - if( sessionProposedCapacity > buffer.capacity() ) { - buffer = ByteBuffer.allocate( sessionProposedCapacity ); - } else { - buffer = ByteBuffer.allocate( buffer.capacity() * 2 ); - } - return buffer; - } - - /** - * Handles {@link SSLEngineResult.Status#BUFFER_UNDERFLOW}. Will check if the buffer is already filled, and if there is no space problem - * will return the same buffer, so the client tries to read again. If the buffer is already filled will try to enlarge the buffer either to - * session's proposed size or to a larger capacity. A buffer underflow can happen only after an unwrap, so the buffer will always be a - * peerNetData buffer. - * - * @param buffer - will always be peerNetData buffer. - * @return The same buffer if there is no space problem or a new buffer with the same data but more space. - */ - private ByteBuffer handleBufferUnderflow( ByteBuffer buffer ) { - if( engine.getSession().getPacketBufferSize() < buffer.limit() ) { - return buffer; - } else { - ByteBuffer replaceBuffer = enlargePacketBuffer( buffer ); - buffer.flip(); - replaceBuffer.put( buffer ); - return replaceBuffer; - } - } - - /** - * This method should be called when this peer wants to explicitly close the connection - * or when a close message has arrived from the other peer, in order to provide an orderly shutdown. - *

    - * It first calls {@link SSLEngine#closeOutbound()} which prepares this peer to send its own close message and - * sets {@link SSLEngine} to the NEED_WRAP state. Then, it delegates the exchange of close messages - * to the handshake method and finally, it closes socket channel. - * - * @throws IOException if an I/O error occurs to the socket channel. - */ - private void closeConnection() throws IOException { - engine.closeOutbound(); - try { - doHandshake(); - } catch ( IOException e ) { - //Just ignore this exception since we are closing the connection already - } - socketChannel.close(); - } - - /** - * In addition to orderly shutdowns, an unorderly shutdown may occur, when the transport link (socket channel) - * is severed before close messages are exchanged. This may happen by getting an -1 or {@link IOException} - * when trying to read from the socket channel, or an {@link IOException} when trying to write to it. - * In both cases {@link SSLEngine#closeInbound()} should be called and then try to follow the standard procedure. - * - * @throws IOException if an I/O error occurs to the socket channel. - */ - private void handleEndOfStream() throws IOException { - try { - engine.closeInbound(); - } catch ( Exception e ) { - log.error( "This engine was forced to close inbound, without having received the proper SSL/TLS close notification message from the peer, due to end of stream." ); - } - closeConnection(); - } - - @Override - public boolean isNeedWrite() { - return false; - } - - @Override - public void writeMore() throws IOException { - //Nothing to do since we write out all the data in a while loop - } - - @Override - public boolean isNeedRead() { - return peerNetData.hasRemaining() || peerAppData.hasRemaining(); - } - - @Override - public int readMore( ByteBuffer dst ) throws IOException { - return read( dst ); - } - - @Override - public boolean isBlocking() { - return socketChannel.isBlocking(); - } - - - @Override - public boolean isOpen() { - return socketChannel.isOpen(); - } - - @Override - public void close() throws IOException { - closeConnection(); - } - - @Override - public SSLEngine getSSLEngine() { - return engine; - } + /** + * Logger instance + * + * @since 1.4.0 + */ + private final Logger log = LoggerFactory.getLogger(SSLSocketChannel.class); + + /** + * The underlying socket channel + */ + private final SocketChannel socketChannel; + + /** + * The engine which will be used for un-/wrapping of buffers + */ + private final SSLEngine engine; + + + /** + * Will contain this peer's application data in plaintext, that will be later encrypted using + * {@link SSLEngine#wrap(ByteBuffer, ByteBuffer)} and sent to the other peer. This buffer can + * typically be of any size, as long as it is large enough to contain this peer's outgoing + * messages. If this peer tries to send a message bigger than buffer's capacity a {@link + * BufferOverflowException} will be thrown. + */ + private ByteBuffer myAppData; + + /** + * Will contain this peer's encrypted data, that will be generated after {@link + * SSLEngine#wrap(ByteBuffer, ByteBuffer)} is applied on {@link SSLSocketChannel#myAppData}. It + * should be initialized using {@link SSLSession#getPacketBufferSize()}, which returns the size up + * to which, SSL/TLS packets will be generated from the engine under a session. All SSLEngine + * network buffers should be sized at least this large to avoid insufficient space problems when + * performing wrap and unwrap calls. + */ + private ByteBuffer myNetData; + + /** + * Will contain the other peer's (decrypted) application data. It must be large enough to hold the + * application data from any peer. Can be initialized with {@link SSLSession#getApplicationBufferSize()} + * for an estimation of the other peer's application data and should be enlarged if this size is + * not enough. + */ + private ByteBuffer peerAppData; + + /** + * Will contain the other peer's encrypted data. The SSL/TLS protocols specify that + * implementations should produce packets containing at most 16 KB of plaintext, so a buffer sized + * to this value should normally cause no capacity problems. However, some implementations violate + * the specification and generate large records up to 32 KB. If the {@link + * SSLEngine#unwrap(ByteBuffer, ByteBuffer)} detects large inbound packets, the buffer sizes + * returned by SSLSession will be updated dynamically, so the this peer should check for overflow + * conditions and enlarge the buffer using the session's (updated) buffer size. + */ + private ByteBuffer peerNetData; + + /** + * Will be used to execute tasks that may emerge during handshake in parallel with the server's + * main thread. + */ + private ExecutorService executor; + + + public SSLSocketChannel(SocketChannel inputSocketChannel, SSLEngine inputEngine, + ExecutorService inputExecutor, SelectionKey key) throws IOException { + if (inputSocketChannel == null || inputEngine == null || executor == inputExecutor) { + throw new IllegalArgumentException("parameter must not be null"); + } + + this.socketChannel = inputSocketChannel; + this.engine = inputEngine; + this.executor = inputExecutor; + myNetData = ByteBuffer.allocate(engine.getSession().getPacketBufferSize()); + peerNetData = ByteBuffer.allocate(engine.getSession().getPacketBufferSize()); + this.engine.beginHandshake(); + if (doHandshake()) { + if (key != null) { + key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); + } + } else { + try { + socketChannel.close(); + } catch (IOException e) { + log.error("Exception during the closing of the channel", e); + } + } + } + + @Override + public synchronized int read(ByteBuffer dst) throws IOException { + if (!dst.hasRemaining()) { + return 0; + } + if (peerAppData.hasRemaining()) { + peerAppData.flip(); + return ByteBufferUtils.transferByteBuffer(peerAppData, dst); + } + peerNetData.compact(); + + int bytesRead = socketChannel.read(peerNetData); + /* + * If bytesRead are 0 put we still have some data in peerNetData still to an unwrap (for testcase 1.1.6) + */ + if (bytesRead > 0 || peerNetData.hasRemaining()) { + peerNetData.flip(); + while (peerNetData.hasRemaining()) { + peerAppData.compact(); + SSLEngineResult result; + try { + result = engine.unwrap(peerNetData, peerAppData); + } catch (SSLException e) { + log.error("SSLException during unwrap", e); + throw e; + } + switch (result.getStatus()) { + case OK: + peerAppData.flip(); + return ByteBufferUtils.transferByteBuffer(peerAppData, dst); + case BUFFER_UNDERFLOW: + peerAppData.flip(); + return ByteBufferUtils.transferByteBuffer(peerAppData, dst); + case BUFFER_OVERFLOW: + peerAppData = enlargeApplicationBuffer(peerAppData); + return read(dst); + case CLOSED: + closeConnection(); + dst.clear(); + return -1; + default: + throw new IllegalStateException("Invalid SSL status: " + result.getStatus()); + } + } + } else if (bytesRead < 0) { + handleEndOfStream(); + } + ByteBufferUtils.transferByteBuffer(peerAppData, dst); + return bytesRead; + } + + @Override + public synchronized int write(ByteBuffer output) throws IOException { + int num = 0; + while (output.hasRemaining()) { + // The loop has a meaning for (outgoing) messages larger than 16KB. + // Every wrap call will remove 16KB from the original message and send it to the remote peer. + myNetData.clear(); + SSLEngineResult result = engine.wrap(output, myNetData); + switch (result.getStatus()) { + case OK: + myNetData.flip(); + while (myNetData.hasRemaining()) { + num += socketChannel.write(myNetData); + } + break; + case BUFFER_OVERFLOW: + myNetData = enlargePacketBuffer(myNetData); + break; + case BUFFER_UNDERFLOW: + throw new SSLException( + "Buffer underflow occurred after a wrap. I don't think we should ever get here."); + case CLOSED: + closeConnection(); + return 0; + default: + throw new IllegalStateException("Invalid SSL status: " + result.getStatus()); + } + } + return num; + } + + /** + * Implements the handshake protocol between two peers, required for the establishment of the + * SSL/TLS connection. During the handshake, encryption configuration information - such as the + * list of available cipher suites - will be exchanged and if the handshake is successful will + * lead to an established SSL/TLS session. + *

    + *

    + * A typical handshake will usually contain the following steps: + *

    + *

      + *
    • 1. wrap: ClientHello
    • + *
    • 2. unwrap: ServerHello/Cert/ServerHelloDone
    • + *
    • 3. wrap: ClientKeyExchange
    • + *
    • 4. wrap: ChangeCipherSpec
    • + *
    • 5. wrap: Finished
    • + *
    • 6. unwrap: ChangeCipherSpec
    • + *
    • 7. unwrap: Finished
    • + *
    + *

    + * Handshake is also used during the end of the session, in order to properly close the connection between the two peers. + * A proper connection close will typically include the one peer sending a CLOSE message to another, and then wait for + * the other's CLOSE message to close the transport link. The other peer from his perspective would read a CLOSE message + * from his peer and then enter the handshake procedure to send his own CLOSE message as well. + * + * @return True if the connection handshake was successful or false if an error occurred. + * @throws IOException - if an error occurs during read/write to the socket channel. + */ + private boolean doHandshake() throws IOException { + SSLEngineResult result; + HandshakeStatus handshakeStatus; + + // NioSslPeer's fields myAppData and peerAppData are supposed to be large enough to hold all message data the peer + // will send and expects to receive from the other peer respectively. Since the messages to be exchanged will usually be less + // than 16KB long the capacity of these fields should also be smaller. Here we initialize these two local buffers + // to be used for the handshake, while keeping client's buffers at the same size. + int appBufferSize = engine.getSession().getApplicationBufferSize(); + myAppData = ByteBuffer.allocate(appBufferSize); + peerAppData = ByteBuffer.allocate(appBufferSize); + myNetData.clear(); + peerNetData.clear(); + + handshakeStatus = engine.getHandshakeStatus(); + boolean handshakeComplete = false; + while (!handshakeComplete) { + switch (handshakeStatus) { + case FINISHED: + handshakeComplete = !this.peerNetData.hasRemaining(); + if (handshakeComplete) { + return true; + } + socketChannel.write(this.peerNetData); + break; + case NEED_UNWRAP: + if (socketChannel.read(peerNetData) < 0) { + if (engine.isInboundDone() && engine.isOutboundDone()) { + return false; + } + try { + engine.closeInbound(); + } catch (SSLException e) { + //Ignore, can't do anything against this exception + } + engine.closeOutbound(); + // After closeOutbound the engine will be set to WRAP state, in order to try to send a close message to the client. + handshakeStatus = engine.getHandshakeStatus(); + break; + } + peerNetData.flip(); + try { + result = engine.unwrap(peerNetData, peerAppData); + peerNetData.compact(); + handshakeStatus = result.getHandshakeStatus(); + } catch (SSLException sslException) { + engine.closeOutbound(); + handshakeStatus = engine.getHandshakeStatus(); + break; + } + switch (result.getStatus()) { + case OK: + break; + case BUFFER_OVERFLOW: + // Will occur when peerAppData's capacity is smaller than the data derived from peerNetData's unwrap. + peerAppData = enlargeApplicationBuffer(peerAppData); + break; + case BUFFER_UNDERFLOW: + // Will occur either when no data was read from the peer or when the peerNetData buffer was too small to hold all peer's data. + peerNetData = handleBufferUnderflow(peerNetData); + break; + case CLOSED: + if (engine.isOutboundDone()) { + return false; + } else { + engine.closeOutbound(); + handshakeStatus = engine.getHandshakeStatus(); + break; + } + default: + throw new IllegalStateException("Invalid SSL status: " + result.getStatus()); + } + break; + case NEED_WRAP: + myNetData.clear(); + try { + result = engine.wrap(myAppData, myNetData); + handshakeStatus = result.getHandshakeStatus(); + } catch (SSLException sslException) { + engine.closeOutbound(); + handshakeStatus = engine.getHandshakeStatus(); + break; + } + switch (result.getStatus()) { + case OK: + myNetData.flip(); + while (myNetData.hasRemaining()) { + socketChannel.write(myNetData); + } + break; + case BUFFER_OVERFLOW: + // Will occur if there is not enough space in myNetData buffer to write all the data that would be generated by the method wrap. + // Since myNetData is set to session's packet size we should not get to this point because SSLEngine is supposed + // to produce messages smaller or equal to that, but a general handling would be the following: + myNetData = enlargePacketBuffer(myNetData); + break; + case BUFFER_UNDERFLOW: + throw new SSLException( + "Buffer underflow occurred after a wrap. I don't think we should ever get here."); + case CLOSED: + try { + myNetData.flip(); + while (myNetData.hasRemaining()) { + socketChannel.write(myNetData); + } + // At this point the handshake status will probably be NEED_UNWRAP so we make sure that peerNetData is clear to read. + peerNetData.clear(); + } catch (Exception e) { + handshakeStatus = engine.getHandshakeStatus(); + } + break; + default: + throw new IllegalStateException("Invalid SSL status: " + result.getStatus()); + } + break; + case NEED_TASK: + Runnable task; + while ((task = engine.getDelegatedTask()) != null) { + executor.execute(task); + } + handshakeStatus = engine.getHandshakeStatus(); + break; + + case NOT_HANDSHAKING: + break; + default: + throw new IllegalStateException("Invalid SSL status: " + handshakeStatus); + } + } + + return true; + + } + + /** + * Enlarging a packet buffer (peerNetData or myNetData) + * + * @param buffer the buffer to enlarge + * @return the enlarged buffer + */ + private ByteBuffer enlargePacketBuffer(ByteBuffer buffer) { + return enlargeBuffer(buffer, engine.getSession().getPacketBufferSize()); + } + + /** + * Enlarging a packet buffer (peerAppData or myAppData) + * + * @param buffer the buffer to enlarge + * @return the enlarged buffer + */ + private ByteBuffer enlargeApplicationBuffer(ByteBuffer buffer) { + return enlargeBuffer(buffer, engine.getSession().getApplicationBufferSize()); + } + + /** + * Compares sessionProposedCapacity with buffer's capacity. If buffer's capacity is + * smaller, returns a buffer with the proposed capacity. If it's equal or larger, returns a buffer + * with capacity twice the size of the initial one. + * + * @param buffer - the buffer to be enlarged. + * @param sessionProposedCapacity - the minimum size of the new buffer, proposed by {@link + * SSLSession}. + * @return A new buffer with a larger capacity. + */ + private ByteBuffer enlargeBuffer(ByteBuffer buffer, int sessionProposedCapacity) { + if (sessionProposedCapacity > buffer.capacity()) { + buffer = ByteBuffer.allocate(sessionProposedCapacity); + } else { + buffer = ByteBuffer.allocate(buffer.capacity() * 2); + } + return buffer; + } + + /** + * Handles {@link SSLEngineResult.Status#BUFFER_UNDERFLOW}. Will check if the buffer is already + * filled, and if there is no space problem will return the same buffer, so the client tries to + * read again. If the buffer is already filled will try to enlarge the buffer either to session's + * proposed size or to a larger capacity. A buffer underflow can happen only after an unwrap, so + * the buffer will always be a peerNetData buffer. + * + * @param buffer - will always be peerNetData buffer. + * @return The same buffer if there is no space problem or a new buffer with the same data but + * more space. + */ + private ByteBuffer handleBufferUnderflow(ByteBuffer buffer) { + if (engine.getSession().getPacketBufferSize() < buffer.limit()) { + return buffer; + } else { + ByteBuffer replaceBuffer = enlargePacketBuffer(buffer); + buffer.flip(); + replaceBuffer.put(buffer); + return replaceBuffer; + } + } + + /** + * This method should be called when this peer wants to explicitly close the connection or when a + * close message has arrived from the other peer, in order to provide an orderly shutdown. + *

    + * It first calls {@link SSLEngine#closeOutbound()} which prepares this peer to send its own close + * message and sets {@link SSLEngine} to the NEED_WRAP state. Then, it delegates the + * exchange of close messages to the handshake method and finally, it closes socket channel. + * + * @throws IOException if an I/O error occurs to the socket channel. + */ + private void closeConnection() throws IOException { + engine.closeOutbound(); + try { + doHandshake(); + } catch (IOException e) { + //Just ignore this exception since we are closing the connection already + } + socketChannel.close(); + } + + /** + * In addition to orderly shutdowns, an unorderly shutdown may occur, when the transport link + * (socket channel) is severed before close messages are exchanged. This may happen by getting an + * -1 or {@link IOException} when trying to read from the socket channel, or an {@link + * IOException} when trying to write to it. In both cases {@link SSLEngine#closeInbound()} should + * be called and then try to follow the standard procedure. + * + * @throws IOException if an I/O error occurs to the socket channel. + */ + private void handleEndOfStream() throws IOException { + try { + engine.closeInbound(); + } catch (Exception e) { + log.error( + "This engine was forced to close inbound, without having received the proper SSL/TLS close notification message from the peer, due to end of stream."); + } + closeConnection(); + } + + @Override + public boolean isNeedWrite() { + return false; + } + + @Override + public void writeMore() throws IOException { + //Nothing to do since we write out all the data in a while loop + } + + @Override + public boolean isNeedRead() { + return peerNetData.hasRemaining() || peerAppData.hasRemaining(); + } + + @Override + public int readMore(ByteBuffer dst) throws IOException { + return read(dst); + } + + @Override + public boolean isBlocking() { + return socketChannel.isBlocking(); + } + + + @Override + public boolean isOpen() { + return socketChannel.isOpen(); + } + + @Override + public void close() throws IOException { + closeConnection(); + } + + @Override + public SSLEngine getSSLEngine() { + return engine; + } } \ No newline at end of file diff --git a/src/main/java/org/java_websocket/SSLSocketChannel2.java b/src/main/java/org/java_websocket/SSLSocketChannel2.java index ccf21fc26..9689ae2d1 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel2.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel2.java @@ -55,409 +55,443 @@ */ public class SSLSocketChannel2 implements ByteChannel, WrappedByteChannel, ISSLChannel { - /** - * This object is used to feed the {@link SSLEngine}'s wrap and unwrap methods during the handshake phase. - **/ - protected static ByteBuffer emptybuffer = ByteBuffer.allocate( 0 ); - - /** - * Logger instance - * - * @since 1.4.0 - */ - private final Logger log = LoggerFactory.getLogger(SSLSocketChannel2.class); - - protected ExecutorService exec; - - protected List> tasks; - - /** raw payload incoming */ - protected ByteBuffer inData; - /** encrypted data outgoing */ - protected ByteBuffer outCrypt; - /** encrypted data incoming */ - protected ByteBuffer inCrypt; - - /** the underlying channel */ - protected SocketChannel socketChannel; - /** used to set interestOP SelectionKey.OP_WRITE for the underlying channel */ - protected SelectionKey selectionKey; - - protected SSLEngine sslEngine; - protected SSLEngineResult readEngineResult; - protected SSLEngineResult writeEngineResult; - - /** - * Should be used to count the buffer allocations. - * But because of #190 where HandshakeStatus.FINISHED is not properly returned by nio wrap/unwrap this variable is used to check whether {@link #createBuffers(SSLSession)} needs to be called. - **/ - protected int bufferallocations = 0; - - public SSLSocketChannel2( SocketChannel channel , SSLEngine sslEngine , ExecutorService exec , SelectionKey key ) throws IOException { - if( channel == null || sslEngine == null || exec == null ) - throw new IllegalArgumentException( "parameter must not be null" ); - - this.socketChannel = channel; - this.sslEngine = sslEngine; - this.exec = exec; - - readEngineResult = writeEngineResult = new SSLEngineResult( Status.BUFFER_UNDERFLOW, sslEngine.getHandshakeStatus(), 0, 0 ); // init to prevent NPEs - - tasks = new ArrayList>( 3 ); - if( key != null ) { - key.interestOps( key.interestOps() | SelectionKey.OP_WRITE ); - this.selectionKey = key; - } - createBuffers( sslEngine.getSession() ); - // kick off handshake - socketChannel.write( wrap( emptybuffer ) );// initializes res - processHandshake(); + /** + * This object is used to feed the {@link SSLEngine}'s wrap and unwrap methods during the + * handshake phase. + **/ + protected static ByteBuffer emptybuffer = ByteBuffer.allocate(0); + + /** + * Logger instance + * + * @since 1.4.0 + */ + private final Logger log = LoggerFactory.getLogger(SSLSocketChannel2.class); + + protected ExecutorService exec; + + protected List> tasks; + + /** + * raw payload incoming + */ + protected ByteBuffer inData; + /** + * encrypted data outgoing + */ + protected ByteBuffer outCrypt; + /** + * encrypted data incoming + */ + protected ByteBuffer inCrypt; + + /** + * the underlying channel + */ + protected SocketChannel socketChannel; + /** + * used to set interestOP SelectionKey.OP_WRITE for the underlying channel + */ + protected SelectionKey selectionKey; + + protected SSLEngine sslEngine; + protected SSLEngineResult readEngineResult; + protected SSLEngineResult writeEngineResult; + + /** + * Should be used to count the buffer allocations. But because of #190 where + * HandshakeStatus.FINISHED is not properly returned by nio wrap/unwrap this variable is used to + * check whether {@link #createBuffers(SSLSession)} needs to be called. + **/ + protected int bufferallocations = 0; + + public SSLSocketChannel2(SocketChannel channel, SSLEngine sslEngine, ExecutorService exec, + SelectionKey key) throws IOException { + if (channel == null || sslEngine == null || exec == null) { + throw new IllegalArgumentException("parameter must not be null"); } - private void consumeFutureUninterruptible( Future f ) { - try { - while ( true ) { - try { - f.get(); - break; - } catch ( InterruptedException e ) { - Thread.currentThread().interrupt(); - } - } - } catch ( ExecutionException e ) { - throw new RuntimeException( e ); - } - } + this.socketChannel = channel; + this.sslEngine = sslEngine; + this.exec = exec; - /** - * This method will do whatever necessary to process the sslEngine handshake. - * Thats why it's called both from the {@link #read(ByteBuffer)} and {@link #write(ByteBuffer)} - **/ - private synchronized void processHandshake() throws IOException { - if( sslEngine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING ) - return; // since this may be called either from a reading or a writing thread and because this method is synchronized it is necessary to double check if we are still handshaking. - if( !tasks.isEmpty() ) { - Iterator> it = tasks.iterator(); - while ( it.hasNext() ) { - Future f = it.next(); - if( f.isDone() ) { - it.remove(); - } else { - if( isBlocking() ) - consumeFutureUninterruptible( f ); - return; - } - } - } - - if( sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP ) { - if( !isBlocking() || readEngineResult.getStatus() == Status.BUFFER_UNDERFLOW ) { - inCrypt.compact(); - int read = socketChannel.read( inCrypt ); - if( read == -1 ) { - throw new IOException( "connection closed unexpectedly by peer" ); - } - inCrypt.flip(); - } - inData.compact(); - unwrap(); - if( readEngineResult.getHandshakeStatus() == HandshakeStatus.FINISHED ) { - createBuffers( sslEngine.getSession() ); - return; - } - } - consumeDelegatedTasks(); - if( tasks.isEmpty() || sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_WRAP ) { - socketChannel.write( wrap( emptybuffer ) ); - if( writeEngineResult.getHandshakeStatus() == HandshakeStatus.FINISHED ) { - createBuffers( sslEngine.getSession() ); - return; - } - } - assert ( sslEngine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING );// this function could only leave NOT_HANDSHAKING after createBuffers was called unless #190 occurs which means that nio wrap/unwrap never return HandshakeStatus.FINISHED + readEngineResult = writeEngineResult = new SSLEngineResult(Status.BUFFER_UNDERFLOW, + sslEngine.getHandshakeStatus(), 0, 0); // init to prevent NPEs - bufferallocations = 1; // look at variable declaration why this line exists and #190. Without this line buffers would not be be recreated when #190 AND a rehandshake occur. - } - private synchronized ByteBuffer wrap( ByteBuffer b ) throws SSLException { - outCrypt.compact(); - writeEngineResult = sslEngine.wrap( b, outCrypt ); - outCrypt.flip(); - return outCrypt; + tasks = new ArrayList>(3); + if (key != null) { + key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); + this.selectionKey = key; } - - /** - * performs the unwrap operation by unwrapping from {@link #inCrypt} to {@link #inData} - **/ - private synchronized ByteBuffer unwrap() throws SSLException { - int rem; - //There are some ssl test suites, which get around the selector.select() call, which cause an infinite unwrap and 100% cpu usage (see #459 and #458) - if(readEngineResult.getStatus() == SSLEngineResult.Status.CLOSED && sslEngine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING){ - try { - close(); - } catch (IOException e) { - //Not really interesting - } + createBuffers(sslEngine.getSession()); + // kick off handshake + socketChannel.write(wrap(emptybuffer));// initializes res + processHandshake(); + } + + private void consumeFutureUninterruptible(Future f) { + try { + while (true) { + try { + f.get(); + break; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); } - do { - rem = inData.remaining(); - readEngineResult = sslEngine.unwrap( inCrypt, inData ); - } while ( readEngineResult.getStatus() == SSLEngineResult.Status.OK && ( rem != inData.remaining() || sslEngine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP ) ); - inData.flip(); - return inData; + } + } catch (ExecutionException e) { + throw new RuntimeException(e); } - - protected void consumeDelegatedTasks() { - Runnable task; - while ( ( task = sslEngine.getDelegatedTask() ) != null ) { - tasks.add( exec.submit( task ) ); - // task.run(); - } + } + + /** + * This method will do whatever necessary to process the sslEngine handshake. Thats why it's + * called both from the {@link #read(ByteBuffer)} and {@link #write(ByteBuffer)} + **/ + private synchronized void processHandshake() throws IOException { + if (sslEngine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING) { + return; // since this may be called either from a reading or a writing thread and because this method is synchronized it is necessary to double check if we are still handshaking. } - - protected void createBuffers( SSLSession session ) { - saveCryptedData(); // save any remaining data in inCrypt - int netBufferMax = session.getPacketBufferSize(); - int appBufferMax = Math.max(session.getApplicationBufferSize(), netBufferMax); - - if( inData == null ) { - inData = ByteBuffer.allocate( appBufferMax ); - outCrypt = ByteBuffer.allocate( netBufferMax ); - inCrypt = ByteBuffer.allocate( netBufferMax ); + if (!tasks.isEmpty()) { + Iterator> it = tasks.iterator(); + while (it.hasNext()) { + Future f = it.next(); + if (f.isDone()) { + it.remove(); } else { - if( inData.capacity() != appBufferMax ) - inData = ByteBuffer.allocate( appBufferMax ); - if( outCrypt.capacity() != netBufferMax ) - outCrypt = ByteBuffer.allocate( netBufferMax ); - if( inCrypt.capacity() != netBufferMax ) - inCrypt = ByteBuffer.allocate( netBufferMax ); - } - if (inData.remaining() != 0 && log.isTraceEnabled()) { - log.trace(new String( inData.array(), inData.position(), inData.remaining())); - } - inData.rewind(); - inData.flip(); - if (inCrypt.remaining() != 0 && log.isTraceEnabled()) { - log.trace(new String( inCrypt.array(), inCrypt.position(), inCrypt.remaining())); - } - inCrypt.rewind(); - inCrypt.flip(); - outCrypt.rewind(); - outCrypt.flip(); - bufferallocations++; - } - - public int write( ByteBuffer src ) throws IOException { - if( !isHandShakeComplete() ) { - processHandshake(); - return 0; + if (isBlocking()) { + consumeFutureUninterruptible(f); + } + return; } - // assert ( bufferallocations > 1 ); //see #190 - //if( bufferallocations <= 1 ) { - // createBuffers( sslEngine.getSession() ); - //} - int num = socketChannel.write( wrap( src ) ); - if (writeEngineResult.getStatus() == SSLEngineResult.Status.CLOSED) { - throw new EOFException("Connection is closed"); - } - return num; - + } } - /** - * Blocks when in blocking mode until at least one byte has been decoded.
    - * When not in blocking mode 0 may be returned. - * - * @return the number of bytes read. - **/ - public int read(ByteBuffer dst) throws IOException { - tryRestoreCryptedData(); - while (true) { - if (!dst.hasRemaining()) - return 0; - if (!isHandShakeComplete()) { - if (isBlocking()) { - while (!isHandShakeComplete()) { - processHandshake(); - } - } else { - processHandshake(); - if (!isHandShakeComplete()) { - return 0; - } - } - } - // assert ( bufferallocations > 1 ); //see #190 - //if( bufferallocations <= 1 ) { - // createBuffers( sslEngine.getSession() ); - //} - /* 1. When "dst" is smaller than "inData" readRemaining will fill "dst" with data decoded in a previous read call. - * 2. When "inCrypt" contains more data than "inData" has remaining space, unwrap has to be called on more time(readRemaining) - */ - int purged = readRemaining(dst); - if (purged != 0) - return purged; - - /* We only continue when we really need more data from the network. - * Thats the case if inData is empty or inCrypt holds to less data than necessary for decryption - */ - assert (inData.position() == 0); - inData.clear(); - - if (!inCrypt.hasRemaining()) - inCrypt.clear(); - else - inCrypt.compact(); - - if (isBlocking() || readEngineResult.getStatus() == Status.BUFFER_UNDERFLOW) - if (socketChannel.read(inCrypt) == -1) { - return -1; - } - inCrypt.flip(); - unwrap(); - - int transferred = transfereTo(inData, dst); - if (transferred == 0 && isBlocking()) { - continue; - } - return transferred; + if (sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) { + if (!isBlocking() || readEngineResult.getStatus() == Status.BUFFER_UNDERFLOW) { + inCrypt.compact(); + int read = socketChannel.read(inCrypt); + if (read == -1) { + throw new IOException("connection closed unexpectedly by peer"); } + inCrypt.flip(); + } + inData.compact(); + unwrap(); + if (readEngineResult.getHandshakeStatus() == HandshakeStatus.FINISHED) { + createBuffers(sslEngine.getSession()); + return; + } } - /** - * {@link #read(ByteBuffer)} may not be to leave all buffers(inData, inCrypt) - **/ - private int readRemaining( ByteBuffer dst ) throws SSLException { - if( inData.hasRemaining() ) { - return transfereTo( inData, dst ); - } - if( !inData.hasRemaining() ) - inData.clear(); - tryRestoreCryptedData(); - // test if some bytes left from last read (e.g. BUFFER_UNDERFLOW) - if( inCrypt.hasRemaining() ) { - unwrap(); - int amount = transfereTo( inData, dst ); - if (readEngineResult.getStatus() == SSLEngineResult.Status.CLOSED) { - return -1; - } - if( amount > 0 ) - return amount; - } - return 0; + consumeDelegatedTasks(); + if (tasks.isEmpty() + || sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_WRAP) { + socketChannel.write(wrap(emptybuffer)); + if (writeEngineResult.getHandshakeStatus() == HandshakeStatus.FINISHED) { + createBuffers(sslEngine.getSession()); + return; + } } - - public boolean isConnected() { - return socketChannel.isConnected(); + assert (sslEngine.getHandshakeStatus() + != HandshakeStatus.NOT_HANDSHAKING);// this function could only leave NOT_HANDSHAKING after createBuffers was called unless #190 occurs which means that nio wrap/unwrap never return HandshakeStatus.FINISHED + + bufferallocations = 1; // look at variable declaration why this line exists and #190. Without this line buffers would not be be recreated when #190 AND a rehandshake occur. + } + + private synchronized ByteBuffer wrap(ByteBuffer b) throws SSLException { + outCrypt.compact(); + writeEngineResult = sslEngine.wrap(b, outCrypt); + outCrypt.flip(); + return outCrypt; + } + + /** + * performs the unwrap operation by unwrapping from {@link #inCrypt} to {@link #inData} + **/ + private synchronized ByteBuffer unwrap() throws SSLException { + int rem; + //There are some ssl test suites, which get around the selector.select() call, which cause an infinite unwrap and 100% cpu usage (see #459 and #458) + if (readEngineResult.getStatus() == SSLEngineResult.Status.CLOSED + && sslEngine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING) { + try { + close(); + } catch (IOException e) { + //Not really interesting + } } - - public void close() throws IOException { - sslEngine.closeOutbound(); - sslEngine.getSession().invalidate(); - if( socketChannel.isOpen() ) - socketChannel.write( wrap( emptybuffer ) );// FIXME what if not all bytes can be written - socketChannel.close(); + do { + rem = inData.remaining(); + readEngineResult = sslEngine.unwrap(inCrypt, inData); + } while (readEngineResult.getStatus() == SSLEngineResult.Status.OK && (rem != inData.remaining() + || sslEngine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP)); + inData.flip(); + return inData; + } + + protected void consumeDelegatedTasks() { + Runnable task; + while ((task = sslEngine.getDelegatedTask()) != null) { + tasks.add(exec.submit(task)); + // task.run(); } - - private boolean isHandShakeComplete() { - HandshakeStatus status = sslEngine.getHandshakeStatus(); - return status == SSLEngineResult.HandshakeStatus.FINISHED || status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING; + } + + protected void createBuffers(SSLSession session) { + saveCryptedData(); // save any remaining data in inCrypt + int netBufferMax = session.getPacketBufferSize(); + int appBufferMax = Math.max(session.getApplicationBufferSize(), netBufferMax); + + if (inData == null) { + inData = ByteBuffer.allocate(appBufferMax); + outCrypt = ByteBuffer.allocate(netBufferMax); + inCrypt = ByteBuffer.allocate(netBufferMax); + } else { + if (inData.capacity() != appBufferMax) { + inData = ByteBuffer.allocate(appBufferMax); + } + if (outCrypt.capacity() != netBufferMax) { + outCrypt = ByteBuffer.allocate(netBufferMax); + } + if (inCrypt.capacity() != netBufferMax) { + inCrypt = ByteBuffer.allocate(netBufferMax); + } } - - public SelectableChannel configureBlocking( boolean b ) throws IOException { - return socketChannel.configureBlocking( b ); + if (inData.remaining() != 0 && log.isTraceEnabled()) { + log.trace(new String(inData.array(), inData.position(), inData.remaining())); } - - public boolean connect( SocketAddress remote ) throws IOException { - return socketChannel.connect( remote ); + inData.rewind(); + inData.flip(); + if (inCrypt.remaining() != 0 && log.isTraceEnabled()) { + log.trace(new String(inCrypt.array(), inCrypt.position(), inCrypt.remaining())); } - - public boolean finishConnect() throws IOException { - return socketChannel.finishConnect(); + inCrypt.rewind(); + inCrypt.flip(); + outCrypt.rewind(); + outCrypt.flip(); + bufferallocations++; + } + + public int write(ByteBuffer src) throws IOException { + if (!isHandShakeComplete()) { + processHandshake(); + return 0; } - - public Socket socket() { - return socketChannel.socket(); + // assert ( bufferallocations > 1 ); //see #190 + //if( bufferallocations <= 1 ) { + // createBuffers( sslEngine.getSession() ); + //} + int num = socketChannel.write(wrap(src)); + if (writeEngineResult.getStatus() == SSLEngineResult.Status.CLOSED) { + throw new EOFException("Connection is closed"); } - - public boolean isInboundDone() { - return sslEngine.isInboundDone(); + return num; + + } + + /** + * Blocks when in blocking mode until at least one byte has been decoded.
    When not in blocking + * mode 0 may be returned. + * + * @return the number of bytes read. + **/ + public int read(ByteBuffer dst) throws IOException { + tryRestoreCryptedData(); + while (true) { + if (!dst.hasRemaining()) { + return 0; + } + if (!isHandShakeComplete()) { + if (isBlocking()) { + while (!isHandShakeComplete()) { + processHandshake(); + } + } else { + processHandshake(); + if (!isHandShakeComplete()) { + return 0; + } + } + } + // assert ( bufferallocations > 1 ); //see #190 + //if( bufferallocations <= 1 ) { + // createBuffers( sslEngine.getSession() ); + //} + /* 1. When "dst" is smaller than "inData" readRemaining will fill "dst" with data decoded in a previous read call. + * 2. When "inCrypt" contains more data than "inData" has remaining space, unwrap has to be called on more time(readRemaining) + */ + int purged = readRemaining(dst); + if (purged != 0) { + return purged; + } + + /* We only continue when we really need more data from the network. + * Thats the case if inData is empty or inCrypt holds to less data than necessary for decryption + */ + assert (inData.position() == 0); + inData.clear(); + + if (!inCrypt.hasRemaining()) { + inCrypt.clear(); + } else { + inCrypt.compact(); + } + + if (isBlocking() || readEngineResult.getStatus() == Status.BUFFER_UNDERFLOW) { + if (socketChannel.read(inCrypt) == -1) { + return -1; + } + } + inCrypt.flip(); + unwrap(); + + int transferred = transfereTo(inData, dst); + if (transferred == 0 && isBlocking()) { + continue; + } + return transferred; } - - @Override - public boolean isOpen() { - return socketChannel.isOpen(); + } + + /** + * {@link #read(ByteBuffer)} may not be to leave all buffers(inData, inCrypt) + **/ + private int readRemaining(ByteBuffer dst) throws SSLException { + if (inData.hasRemaining()) { + return transfereTo(inData, dst); } - - @Override - public boolean isNeedWrite() { - return outCrypt.hasRemaining() || !isHandShakeComplete(); // FIXME this condition can cause high cpu load during handshaking when network is slow + if (!inData.hasRemaining()) { + inData.clear(); } - - @Override - public void writeMore() throws IOException { - write( outCrypt ); + tryRestoreCryptedData(); + // test if some bytes left from last read (e.g. BUFFER_UNDERFLOW) + if (inCrypt.hasRemaining()) { + unwrap(); + int amount = transfereTo(inData, dst); + if (readEngineResult.getStatus() == SSLEngineResult.Status.CLOSED) { + return -1; + } + if (amount > 0) { + return amount; + } } - - @Override - public boolean isNeedRead() { - return saveCryptData != null || inData.hasRemaining() || ( inCrypt.hasRemaining() && readEngineResult.getStatus() != Status.BUFFER_UNDERFLOW && readEngineResult.getStatus() != Status.CLOSED ); + return 0; + } + + public boolean isConnected() { + return socketChannel.isConnected(); + } + + public void close() throws IOException { + sslEngine.closeOutbound(); + sslEngine.getSession().invalidate(); + if (socketChannel.isOpen()) { + socketChannel.write(wrap(emptybuffer));// FIXME what if not all bytes can be written } - - @Override - public int readMore( ByteBuffer dst ) throws SSLException { - return readRemaining( dst ); + socketChannel.close(); + } + + private boolean isHandShakeComplete() { + HandshakeStatus status = sslEngine.getHandshakeStatus(); + return status == SSLEngineResult.HandshakeStatus.FINISHED + || status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING; + } + + public SelectableChannel configureBlocking(boolean b) throws IOException { + return socketChannel.configureBlocking(b); + } + + public boolean connect(SocketAddress remote) throws IOException { + return socketChannel.connect(remote); + } + + public boolean finishConnect() throws IOException { + return socketChannel.finishConnect(); + } + + public Socket socket() { + return socketChannel.socket(); + } + + public boolean isInboundDone() { + return sslEngine.isInboundDone(); + } + + @Override + public boolean isOpen() { + return socketChannel.isOpen(); + } + + @Override + public boolean isNeedWrite() { + return outCrypt.hasRemaining() + || !isHandShakeComplete(); // FIXME this condition can cause high cpu load during handshaking when network is slow + } + + @Override + public void writeMore() throws IOException { + write(outCrypt); + } + + @Override + public boolean isNeedRead() { + return saveCryptData != null || inData.hasRemaining() || (inCrypt.hasRemaining() + && readEngineResult.getStatus() != Status.BUFFER_UNDERFLOW + && readEngineResult.getStatus() != Status.CLOSED); + } + + @Override + public int readMore(ByteBuffer dst) throws SSLException { + return readRemaining(dst); + } + + private int transfereTo(ByteBuffer from, ByteBuffer to) { + int fremain = from.remaining(); + int toremain = to.remaining(); + if (fremain > toremain) { + // FIXME there should be a more efficient transfer method + int limit = Math.min(fremain, toremain); + for (int i = 0; i < limit; i++) { + to.put(from.get()); + } + return limit; + } else { + to.put(from); + return fremain; } - private int transfereTo( ByteBuffer from, ByteBuffer to ) { - int fremain = from.remaining(); - int toremain = to.remaining(); - if( fremain > toremain ) { - // FIXME there should be a more efficient transfer method - int limit = Math.min( fremain, toremain ); - for( int i = 0 ; i < limit ; i++ ) { - to.put( from.get() ); - } - return limit; - } else { - to.put( from ); - return fremain; - } + } - } + @Override + public boolean isBlocking() { + return socketChannel.isBlocking(); + } - @Override - public boolean isBlocking() { - return socketChannel.isBlocking(); - } + @Override + public SSLEngine getSSLEngine() { + return sslEngine; + } - @Override - public SSLEngine getSSLEngine() { - return sslEngine; - } + // to avoid complexities with inCrypt, extra unwrapped data after SSL handshake will be saved off in a byte array + // and the inserted back on first read + private byte[] saveCryptData = null; - // to avoid complexities with inCrypt, extra unwrapped data after SSL handshake will be saved off in a byte array - // and the inserted back on first read - private byte[] saveCryptData = null; - private void saveCryptedData() - { - // did we find any extra data? - if (inCrypt != null && inCrypt.remaining() > 0) - { - int saveCryptSize = inCrypt.remaining(); - saveCryptData = new byte[saveCryptSize]; - inCrypt.get(saveCryptData); - } + private void saveCryptedData() { + // did we find any extra data? + if (inCrypt != null && inCrypt.remaining() > 0) { + int saveCryptSize = inCrypt.remaining(); + saveCryptData = new byte[saveCryptSize]; + inCrypt.get(saveCryptData); } - - private void tryRestoreCryptedData() - { - // was there any extra data, then put into inCrypt and clean up - if ( saveCryptData != null ) - { - inCrypt.clear(); - inCrypt.put( saveCryptData ); - inCrypt.flip(); - saveCryptData = null; - } + } + + private void tryRestoreCryptedData() { + // was there any extra data, then put into inCrypt and clean up + if (saveCryptData != null) { + inCrypt.clear(); + inCrypt.put(saveCryptData); + inCrypt.flip(); + saveCryptData = null; } + } } \ No newline at end of file diff --git a/src/main/java/org/java_websocket/SocketChannelIOHelper.java b/src/main/java/org/java_websocket/SocketChannelIOHelper.java index ba1575288..14fb58b7c 100644 --- a/src/main/java/org/java_websocket/SocketChannelIOHelper.java +++ b/src/main/java/org/java_websocket/SocketChannelIOHelper.java @@ -33,77 +33,84 @@ public class SocketChannelIOHelper { - private SocketChannelIOHelper() { - throw new IllegalStateException("Utility class"); - } + private SocketChannelIOHelper() { + throw new IllegalStateException("Utility class"); + } - public static boolean read( final ByteBuffer buf, WebSocketImpl ws, ByteChannel channel ) throws IOException { - buf.clear(); - int read = channel.read( buf ); - buf.flip(); + public static boolean read(final ByteBuffer buf, WebSocketImpl ws, ByteChannel channel) + throws IOException { + buf.clear(); + int read = channel.read(buf); + buf.flip(); - if( read == -1 ) { - ws.eot(); - return false; - } - return read != 0; - } + if (read == -1) { + ws.eot(); + return false; + } + return read != 0; + } - /** - * @see WrappedByteChannel#readMore(ByteBuffer) - * @param buf The ByteBuffer to read from - * @param ws The WebSocketImpl associated with the channels - * @param channel The channel to read from - * @return returns Whether there is more data left which can be obtained via {@link WrappedByteChannel#readMore(ByteBuffer)} - * @throws IOException May be thrown by {@link WrappedByteChannel#readMore(ByteBuffer)}# - **/ - public static boolean readMore( final ByteBuffer buf, WebSocketImpl ws, WrappedByteChannel channel ) throws IOException { - buf.clear(); - int read = channel.readMore( buf ); - buf.flip(); + /** + * @param buf The ByteBuffer to read from + * @param ws The WebSocketImpl associated with the channels + * @param channel The channel to read from + * @return returns Whether there is more data left which can be obtained via {@link + * WrappedByteChannel#readMore(ByteBuffer)} + * @throws IOException May be thrown by {@link WrappedByteChannel#readMore(ByteBuffer)}# + * @see WrappedByteChannel#readMore(ByteBuffer) + **/ + public static boolean readMore(final ByteBuffer buf, WebSocketImpl ws, WrappedByteChannel channel) + throws IOException { + buf.clear(); + int read = channel.readMore(buf); + buf.flip(); - if( read == -1 ) { - ws.eot(); - return false; - } - return channel.isNeedRead(); - } + if (read == -1) { + ws.eot(); + return false; + } + return channel.isNeedRead(); + } - /** Returns whether the whole outQueue has been flushed - * @param ws The WebSocketImpl associated with the channels - * @param sockchannel The channel to write to - * @throws IOException May be thrown by {@link WrappedByteChannel#writeMore()} - * @return returns Whether there is more data to write - */ - public static boolean batch( WebSocketImpl ws, ByteChannel sockchannel ) throws IOException { - if (ws == null) { - return false; - } - ByteBuffer buffer = ws.outQueue.peek(); - WrappedByteChannel c = null; + /** + * Returns whether the whole outQueue has been flushed + * + * @param ws The WebSocketImpl associated with the channels + * @param sockchannel The channel to write to + * @return returns Whether there is more data to write + * @throws IOException May be thrown by {@link WrappedByteChannel#writeMore()} + */ + public static boolean batch(WebSocketImpl ws, ByteChannel sockchannel) throws IOException { + if (ws == null) { + return false; + } + ByteBuffer buffer = ws.outQueue.peek(); + WrappedByteChannel c = null; - if( buffer == null ) { - if( sockchannel instanceof WrappedByteChannel ) { - c = (WrappedByteChannel) sockchannel; - if( c.isNeedWrite() ) { - c.writeMore(); - } - } - } else { - do {// FIXME writing as much as possible is unfair!! - /*int written = */sockchannel.write( buffer ); - if( buffer.remaining() > 0 ) { - return false; - } else { - ws.outQueue.poll(); // Buffer finished. Remove it. - buffer = ws.outQueue.peek(); - } - } while ( buffer != null ); - } + if (buffer == null) { + if (sockchannel instanceof WrappedByteChannel) { + c = (WrappedByteChannel) sockchannel; + if (c.isNeedWrite()) { + c.writeMore(); + } + } + } else { + do {// FIXME writing as much as possible is unfair!! + /*int written = */ + sockchannel.write(buffer); + if (buffer.remaining() > 0) { + return false; + } else { + ws.outQueue.poll(); // Buffer finished. Remove it. + buffer = ws.outQueue.peek(); + } + } while (buffer != null); + } - if( ws.outQueue.isEmpty() && ws.isFlushAndClose() && ws.getDraft() != null && ws.getDraft().getRole() != null && ws.getDraft().getRole() == Role.SERVER ) {// - ws.closeConnection(); - } - return c == null || !((WrappedByteChannel) sockchannel).isNeedWrite(); - } + if (ws.outQueue.isEmpty() && ws.isFlushAndClose() && ws.getDraft() != null + && ws.getDraft().getRole() != null && ws.getDraft().getRole() == Role.SERVER) {// + ws.closeConnection(); + } + return c == null || !((WrappedByteChannel) sockchannel).isNeedWrite(); + } } diff --git a/src/main/java/org/java_websocket/WebSocket.java b/src/main/java/org/java_websocket/WebSocket.java index 652d45359..3c23b8c20 100644 --- a/src/main/java/org/java_websocket/WebSocket.java +++ b/src/main/java/org/java_websocket/WebSocket.java @@ -40,197 +40,213 @@ public interface WebSocket { - /** - * sends the closing handshake. - * may be send in response to an other handshake. - * @param code the closing code - * @param message the closing message - */ - void close( int code, String message ); - - /** - * sends the closing handshake. - * may be send in response to an other handshake. - * @param code the closing code - */ - void close( int code ); - - /** Convenience function which behaves like close(CloseFrame.NORMAL) */ - void close(); - - /** - * This will close the connection immediately without a proper close handshake. - * The code and the message therefore won't be transferred over the wire also they will be forwarded to onClose/onWebsocketClose. - * @param code the closing code - * @param message the closing message - **/ - void closeConnection( int code, String message ); - - /** - * Send Text data to the other end. - * - * @param text the text data to send - * @throws WebsocketNotConnectedException websocket is not yet connected - */ - void send( String text ); - - /** - * Send Binary data (plain bytes) to the other end. - * - * @param bytes the binary data to send - * @throws IllegalArgumentException the data is null - * @throws WebsocketNotConnectedException websocket is not yet connected - */ - void send( ByteBuffer bytes ); - - /** - * Send Binary data (plain bytes) to the other end. - * - * @param bytes the byte array to send - * @throws IllegalArgumentException the data is null - * @throws WebsocketNotConnectedException websocket is not yet connected - */ - void send( byte[] bytes ); - - /** - * Send a frame to the other end - * @param framedata the frame to send to the other end - */ - void sendFrame( Framedata framedata ); - - /** - * Send a collection of frames to the other end - * @param frames the frames to send to the other end - */ - void sendFrame( Collection frames ); - - /** - * Send a ping to the other end - * @throws WebsocketNotConnectedException websocket is not yet connected - */ - void sendPing(); - - /** - * Allows to send continuous/fragmented frames conveniently.
    - * For more into on this frame type see http://tools.ietf.org/html/rfc6455#section-5.4
    - * - * If the first frame you send is also the last then it is not a fragmented frame and will received via onMessage instead of onFragmented even though it was send by this method. - * - * @param op - * This is only important for the first frame in the sequence. Opcode.TEXT, Opcode.BINARY are allowed. - * @param buffer - * The buffer which contains the payload. It may have no bytes remaining. - * @param fin - * true means the current frame is the last in the sequence. - **/ - void sendFragmentedFrame( Opcode op, ByteBuffer buffer, boolean fin ); - - /** - * Checks if the websocket has buffered data - * @return has the websocket buffered data - */ - boolean hasBufferedData(); - - /** - * Returns the address of the endpoint this socket is connected to, or{@code null} if it is unconnected. - * - * @return never returns null - */ - InetSocketAddress getRemoteSocketAddress(); - - /** - * Returns the address of the endpoint this socket is bound to. - * - * @return never returns null - */ - InetSocketAddress getLocalSocketAddress(); - - /** - * Is the websocket in the state OPEN - * @return state equals ReadyState.OPEN - */ - boolean isOpen(); - - /** - * Is the websocket in the state CLOSING - * @return state equals ReadyState.CLOSING - */ - boolean isClosing(); - - /** - * Returns true when no further frames may be submitted
    - * This happens before the socket connection is closed. - * @return true when no further frames may be submitted - */ - boolean isFlushAndClose(); - - /** - * Is the websocket in the state CLOSED - * @return state equals ReadyState.CLOSED - */ - boolean isClosed(); - - /** - * Getter for the draft - * @return the used draft - */ - Draft getDraft(); - - /** - * Retrieve the WebSocket 'ReadyState'. - * This represents the state of the connection. - * It returns a numerical value, as per W3C WebSockets specs. - * - * @return Returns '0 = CONNECTING', '1 = OPEN', '2 = CLOSING' or '3 = CLOSED' - */ - ReadyState getReadyState(); - - /** - * Returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2
    - * If the opening handshake has not yet happened it will return null. - * @return Returns the decoded path component of this URI. - **/ - String getResourceDescriptor(); - - /** - * Setter for an attachment on the socket connection. - * The attachment may be of any type. - * - * @param attachment The object to be attached to the user - * @param The type of the attachment - * @since 1.3.7 - **/ - void setAttachment(T attachment); - - /** - * Getter for the connection attachment. - * - * @param The type of the attachment - * @return Returns the user attachment - * @since 1.3.7 - **/ - T getAttachment(); - - /** - * Does this websocket use an encrypted (wss/ssl) or unencrypted (ws) connection - * @return true, if the websocket does use wss and therefore has a SSLSession - * @since 1.4.1 - */ - boolean hasSSLSupport(); - - /** - * Returns the ssl session of websocket, if ssl/wss is used for this instance. - * @return the ssl session of this websocket instance - * @throws IllegalArgumentException the underlying channel does not use ssl (use hasSSLSupport() to check) - * @since 1.4.1 - */ - SSLSession getSSLSession() throws IllegalArgumentException; - - /** - * Returns the used Sec-WebSocket-Protocol for this websocket connection - * @return the Sec-WebSocket-Protocol or null, if no draft available - * @throws IllegalArgumentException the underlying draft does not support a Sec-WebSocket-Protocol - * @since 1.5.2 - */ - IProtocol getProtocol(); + /** + * sends the closing handshake. may be send in response to an other handshake. + * + * @param code the closing code + * @param message the closing message + */ + void close(int code, String message); + + /** + * sends the closing handshake. may be send in response to an other handshake. + * + * @param code the closing code + */ + void close(int code); + + /** + * Convenience function which behaves like close(CloseFrame.NORMAL) + */ + void close(); + + /** + * This will close the connection immediately without a proper close handshake. The code and the + * message therefore won't be transferred over the wire also they will be forwarded to + * onClose/onWebsocketClose. + * + * @param code the closing code + * @param message the closing message + **/ + void closeConnection(int code, String message); + + /** + * Send Text data to the other end. + * + * @param text the text data to send + * @throws WebsocketNotConnectedException websocket is not yet connected + */ + void send(String text); + + /** + * Send Binary data (plain bytes) to the other end. + * + * @param bytes the binary data to send + * @throws IllegalArgumentException the data is null + * @throws WebsocketNotConnectedException websocket is not yet connected + */ + void send(ByteBuffer bytes); + + /** + * Send Binary data (plain bytes) to the other end. + * + * @param bytes the byte array to send + * @throws IllegalArgumentException the data is null + * @throws WebsocketNotConnectedException websocket is not yet connected + */ + void send(byte[] bytes); + + /** + * Send a frame to the other end + * + * @param framedata the frame to send to the other end + */ + void sendFrame(Framedata framedata); + + /** + * Send a collection of frames to the other end + * + * @param frames the frames to send to the other end + */ + void sendFrame(Collection frames); + + /** + * Send a ping to the other end + * + * @throws WebsocketNotConnectedException websocket is not yet connected + */ + void sendPing(); + + /** + * Allows to send continuous/fragmented frames conveniently.
    For more into on this frame type + * see http://tools.ietf.org/html/rfc6455#section-5.4
    + *

    + * If the first frame you send is also the last then it is not a fragmented frame and will + * received via onMessage instead of onFragmented even though it was send by this method. + * + * @param op This is only important for the first frame in the sequence. Opcode.TEXT, + * Opcode.BINARY are allowed. + * @param buffer The buffer which contains the payload. It may have no bytes remaining. + * @param fin true means the current frame is the last in the sequence. + **/ + void sendFragmentedFrame(Opcode op, ByteBuffer buffer, boolean fin); + + /** + * Checks if the websocket has buffered data + * + * @return has the websocket buffered data + */ + boolean hasBufferedData(); + + /** + * Returns the address of the endpoint this socket is connected to, or{@code null} if it is + * unconnected. + * + * @return never returns null + */ + InetSocketAddress getRemoteSocketAddress(); + + /** + * Returns the address of the endpoint this socket is bound to. + * + * @return never returns null + */ + InetSocketAddress getLocalSocketAddress(); + + /** + * Is the websocket in the state OPEN + * + * @return state equals ReadyState.OPEN + */ + boolean isOpen(); + + /** + * Is the websocket in the state CLOSING + * + * @return state equals ReadyState.CLOSING + */ + boolean isClosing(); + + /** + * Returns true when no further frames may be submitted
    This happens before the socket + * connection is closed. + * + * @return true when no further frames may be submitted + */ + boolean isFlushAndClose(); + + /** + * Is the websocket in the state CLOSED + * + * @return state equals ReadyState.CLOSED + */ + boolean isClosed(); + + /** + * Getter for the draft + * + * @return the used draft + */ + Draft getDraft(); + + /** + * Retrieve the WebSocket 'ReadyState'. This represents the state of the connection. It returns a + * numerical value, as per W3C WebSockets specs. + * + * @return Returns '0 = CONNECTING', '1 = OPEN', '2 = CLOSING' or '3 = CLOSED' + */ + ReadyState getReadyState(); + + /** + * Returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2
    + * If the opening handshake has not yet happened it will return null. + * + * @return Returns the decoded path component of this URI. + **/ + String getResourceDescriptor(); + + /** + * Setter for an attachment on the socket connection. The attachment may be of any type. + * + * @param attachment The object to be attached to the user + * @param The type of the attachment + * @since 1.3.7 + **/ + void setAttachment(T attachment); + + /** + * Getter for the connection attachment. + * + * @param The type of the attachment + * @return Returns the user attachment + * @since 1.3.7 + **/ + T getAttachment(); + + /** + * Does this websocket use an encrypted (wss/ssl) or unencrypted (ws) connection + * + * @return true, if the websocket does use wss and therefore has a SSLSession + * @since 1.4.1 + */ + boolean hasSSLSupport(); + + /** + * Returns the ssl session of websocket, if ssl/wss is used for this instance. + * + * @return the ssl session of this websocket instance + * @throws IllegalArgumentException the underlying channel does not use ssl (use hasSSLSupport() + * to check) + * @since 1.4.1 + */ + SSLSession getSSLSession() throws IllegalArgumentException; + + /** + * Returns the used Sec-WebSocket-Protocol for this websocket connection + * + * @return the Sec-WebSocket-Protocol or null, if no draft available + * @throws IllegalArgumentException the underlying draft does not support a Sec-WebSocket-Protocol + * @since 1.5.2 + */ + IProtocol getProtocol(); } \ No newline at end of file diff --git a/src/main/java/org/java_websocket/WebSocketAdapter.java b/src/main/java/org/java_websocket/WebSocketAdapter.java index 9281c259c..e60215f8c 100644 --- a/src/main/java/org/java_websocket/WebSocketAdapter.java +++ b/src/main/java/org/java_websocket/WebSocketAdapter.java @@ -36,69 +36,78 @@ import org.java_websocket.handshake.ServerHandshakeBuilder; /** - * This class default implements all methods of the WebSocketListener that can be overridden optionally when advances functionalities is needed.
    + * This class default implements all methods of the WebSocketListener that can be overridden + * optionally when advances functionalities is needed.
    **/ public abstract class WebSocketAdapter implements WebSocketListener { - private PingFrame pingFrame; + private PingFrame pingFrame; - /** - * This default implementation does not do anything. Go ahead and overwrite it. - * - * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeReceivedAsServer(WebSocket, Draft, ClientHandshake) - */ - @Override - public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer( WebSocket conn, Draft draft, ClientHandshake request ) throws InvalidDataException { - return new HandshakeImpl1Server(); - } + /** + * This default implementation does not do anything. Go ahead and overwrite it. + * + * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeReceivedAsServer(WebSocket, + * Draft, ClientHandshake) + */ + @Override + public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft, + ClientHandshake request) throws InvalidDataException { + return new HandshakeImpl1Server(); + } - @Override - public void onWebsocketHandshakeReceivedAsClient( WebSocket conn, ClientHandshake request, ServerHandshake response ) throws InvalidDataException { - //To overwrite - } + @Override + public void onWebsocketHandshakeReceivedAsClient(WebSocket conn, ClientHandshake request, + ServerHandshake response) throws InvalidDataException { + //To overwrite + } - /** - * This default implementation does not do anything which will cause the connections to always progress. - * - * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeSentAsClient(WebSocket, ClientHandshake) - */ - @Override - public void onWebsocketHandshakeSentAsClient( WebSocket conn, ClientHandshake request ) throws InvalidDataException { - //To overwrite - } + /** + * This default implementation does not do anything which will cause the connections to always + * progress. + * + * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeSentAsClient(WebSocket, + * ClientHandshake) + */ + @Override + public void onWebsocketHandshakeSentAsClient(WebSocket conn, ClientHandshake request) + throws InvalidDataException { + //To overwrite + } - /** - * This default implementation will send a pong in response to the received ping. - * The pong frame will have the same payload as the ping frame. - * - * @see org.java_websocket.WebSocketListener#onWebsocketPing(WebSocket, Framedata) - */ - @Override - public void onWebsocketPing( WebSocket conn, Framedata f ) { - conn.sendFrame( new PongFrame( (PingFrame)f ) ); - } + /** + * This default implementation will send a pong in response to the received ping. The pong frame + * will have the same payload as the ping frame. + * + * @see org.java_websocket.WebSocketListener#onWebsocketPing(WebSocket, Framedata) + */ + @Override + public void onWebsocketPing(WebSocket conn, Framedata f) { + conn.sendFrame(new PongFrame((PingFrame) f)); + } - /** - * This default implementation does not do anything. Go ahead and overwrite it. - * - * @see org.java_websocket.WebSocketListener#onWebsocketPong(WebSocket, Framedata) - */ - @Override - public void onWebsocketPong( WebSocket conn, Framedata f ) { - //To overwrite - } + /** + * This default implementation does not do anything. Go ahead and overwrite it. + * + * @see org.java_websocket.WebSocketListener#onWebsocketPong(WebSocket, Framedata) + */ + @Override + public void onWebsocketPong(WebSocket conn, Framedata f) { + //To overwrite + } - /** - * Default implementation for onPreparePing, returns a (cached) PingFrame that has no application data. - * @see org.java_websocket.WebSocketListener#onPreparePing(WebSocket) - * - * @param conn The WebSocket connection from which the ping frame will be sent. - * @return PingFrame to be sent. - */ - @Override - public PingFrame onPreparePing(WebSocket conn) { - if(pingFrame == null) - pingFrame = new PingFrame(); - return pingFrame; - } + /** + * Default implementation for onPreparePing, returns a (cached) PingFrame that has no application + * data. + * + * @param conn The WebSocket connection from which the ping frame will be sent. + * @return PingFrame to be sent. + * @see org.java_websocket.WebSocketListener#onPreparePing(WebSocket) + */ + @Override + public PingFrame onPreparePing(WebSocket conn) { + if (pingFrame == null) { + pingFrame = new PingFrame(); + } + return pingFrame; + } } diff --git a/src/main/java/org/java_websocket/WebSocketFactory.java b/src/main/java/org/java_websocket/WebSocketFactory.java index 8a2bcc022..65de7c550 100644 --- a/src/main/java/org/java_websocket/WebSocketFactory.java +++ b/src/main/java/org/java_websocket/WebSocketFactory.java @@ -30,20 +30,23 @@ import org.java_websocket.drafts.Draft; public interface WebSocketFactory { - /** - * Create a new Websocket with the provided listener, drafts and socket - * @param a The Listener for the WebsocketImpl - * @param d The draft which should be used - * @return A WebsocketImpl - */ - WebSocket createWebSocket( WebSocketAdapter a, Draft d); - /** - * Create a new Websocket with the provided listener, drafts and socket - * @param a The Listener for the WebsocketImpl - * @param drafts The drafts which should be used - * @return A WebsocketImpl - */ - WebSocket createWebSocket( WebSocketAdapter a, List drafts); + /** + * Create a new Websocket with the provided listener, drafts and socket + * + * @param a The Listener for the WebsocketImpl + * @param d The draft which should be used + * @return A WebsocketImpl + */ + WebSocket createWebSocket(WebSocketAdapter a, Draft d); + + /** + * Create a new Websocket with the provided listener, drafts and socket + * + * @param a The Listener for the WebsocketImpl + * @param drafts The drafts which should be used + * @return A WebsocketImpl + */ + WebSocket createWebSocket(WebSocketAdapter a, List drafts); } diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index ac951820b..28041d49b 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -56,812 +56,846 @@ import javax.net.ssl.SSLSession; /** - * Represents one end (client or server) of a single WebSocketImpl connection. - * Takes care of the "handshake" phase, then allows for easy sending of - * text frames, and receiving frames through an event-based model. + * Represents one end (client or server) of a single WebSocketImpl connection. Takes care of the + * "handshake" phase, then allows for easy sending of text frames, and receiving frames through an + * event-based model. */ public class WebSocketImpl implements WebSocket { - /** - * The default port of WebSockets, as defined in the spec. If the nullary - * constructor is used, DEFAULT_PORT will be the port the WebSocketServer - * is binded to. Note that ports under 1024 usually require root permissions. - */ - public static final int DEFAULT_PORT = 80; - - /** - * The default wss port of WebSockets, as defined in the spec. If the nullary - * constructor is used, DEFAULT_WSS_PORT will be the port the WebSocketServer - * is binded to. Note that ports under 1024 usually require root permissions. - */ - public static final int DEFAULT_WSS_PORT = 443; - - /** - * Initial buffer size - */ - public static final int RCVBUF = 16384; - - /** - * Logger instance - * - * @since 1.4.0 - */ - private final Logger log = LoggerFactory.getLogger(WebSocketImpl.class); - - /** - * Queue of buffers that need to be sent to the client. - */ - public final BlockingQueue outQueue; - /** - * Queue of buffers that need to be processed - */ - public final BlockingQueue inQueue; - /** - * The listener to notify of WebSocket events. - */ - private final WebSocketListener wsl; - - private SelectionKey key; - - /** - * the possibly wrapped channel object whose selection is controlled by {@link #key} - */ - private ByteChannel channel; - /** - * Helper variable meant to store the thread which ( exclusively ) triggers this objects decode method. - **/ - private WebSocketWorker workerThread; - /** - * When true no further frames may be submitted to be sent - */ - private boolean flushandclosestate = false; - - /** - * The current state of the connection - */ - private volatile ReadyState readyState = ReadyState.NOT_YET_CONNECTED; - - /** - * A list of drafts available for this websocket - */ - private List knownDrafts; - - /** - * The draft which is used by this websocket - */ - private Draft draft = null; - - /** - * The role which this websocket takes in the connection - */ - private Role role; - - /** - * the bytes of an incomplete received handshake - */ - private ByteBuffer tmpHandshakeBytes = ByteBuffer.allocate( 0 ); - - /** - * stores the handshake sent by this websocket ( Role.CLIENT only ) - */ - private ClientHandshake handshakerequest = null; - - private String closemessage = null; - private Integer closecode = null; - private Boolean closedremotely = null; - - private String resourceDescriptor = null; - - /** - * Attribute, when the last pong was received - */ - private long lastPong = System.nanoTime(); - - /** - * Attribut to synchronize the write - */ - private final Object synchronizeWriteObject = new Object(); - - /** - * Attribute to store connection attachment - * @since 1.3.7 - */ - private Object attachment; - - /** - * Creates a websocket with server role - * - * @param listener The listener for this instance - * @param drafts The drafts which should be used - */ - public WebSocketImpl( WebSocketListener listener, List drafts ) { - this( listener, ( Draft ) null ); - this.role = Role.SERVER; - // draft.copyInstance will be called when the draft is first needed - if( drafts == null || drafts.isEmpty() ) { - knownDrafts = new ArrayList(); - knownDrafts.add( new Draft_6455() ); - } else { - knownDrafts = drafts; - } - } - - /** - * creates a websocket with client role - * - * @param listener The listener for this instance - * @param draft The draft which should be used - */ - public WebSocketImpl( WebSocketListener listener, Draft draft ) { - if( listener == null || ( draft == null && role == Role.SERVER ) )// socket can be null because we want do be able to create the object without already having a bound channel - throw new IllegalArgumentException( "parameters must not be null" ); - this.outQueue = new LinkedBlockingQueue(); - inQueue = new LinkedBlockingQueue(); - this.wsl = listener; - this.role = Role.CLIENT; - if( draft != null ) - this.draft = draft.copyInstance(); - } - - /** - * Method to decode the provided ByteBuffer - * - * @param socketBuffer the ByteBuffer to decode - */ - public void decode( ByteBuffer socketBuffer ) { - assert ( socketBuffer.hasRemaining() ); - log.trace( "process({}): ({})", socketBuffer.remaining(), ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) )); - - if( readyState != ReadyState.NOT_YET_CONNECTED ) { - if( readyState == ReadyState.OPEN ) { - decodeFrames( socketBuffer ); - } - } else { - if( decodeHandshake( socketBuffer ) && (!isClosing() && !isClosed())) { - assert ( tmpHandshakeBytes.hasRemaining() != socketBuffer.hasRemaining() || !socketBuffer.hasRemaining() ); // the buffers will never have remaining bytes at the same time - if( socketBuffer.hasRemaining() ) { - decodeFrames( socketBuffer ); - } else if( tmpHandshakeBytes.hasRemaining() ) { - decodeFrames( tmpHandshakeBytes ); - } - } - } - } - - /** - * Returns whether the handshake phase has is completed. - * In case of a broken handshake this will be never the case. - **/ - private boolean decodeHandshake( ByteBuffer socketBufferNew ) { - ByteBuffer socketBuffer; - if( tmpHandshakeBytes.capacity() == 0 ) { - socketBuffer = socketBufferNew; - } else { - if( tmpHandshakeBytes.remaining() < socketBufferNew.remaining() ) { - ByteBuffer buf = ByteBuffer.allocate( tmpHandshakeBytes.capacity() + socketBufferNew.remaining() ); - tmpHandshakeBytes.flip(); - buf.put( tmpHandshakeBytes ); - tmpHandshakeBytes = buf; - } - - tmpHandshakeBytes.put( socketBufferNew ); - tmpHandshakeBytes.flip(); - socketBuffer = tmpHandshakeBytes; - } - socketBuffer.mark(); - try { - HandshakeState handshakestate; - try { - if( role == Role.SERVER ) { - if( draft == null ) { - for( Draft d : knownDrafts ) { - d = d.copyInstance(); - try { - d.setParseMode( role ); - socketBuffer.reset(); - Handshakedata tmphandshake = d.translateHandshake( socketBuffer ); - if( !( tmphandshake instanceof ClientHandshake ) ) { - log.trace("Closing due to wrong handshake"); - closeConnectionDueToWrongHandshake( new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "wrong http function" ) ); - return false; - } - ClientHandshake handshake = ( ClientHandshake ) tmphandshake; - handshakestate = d.acceptHandshakeAsServer( handshake ); - if( handshakestate == HandshakeState.MATCHED ) { - resourceDescriptor = handshake.getResourceDescriptor(); - ServerHandshakeBuilder response; - try { - response = wsl.onWebsocketHandshakeReceivedAsServer( this, d, handshake ); - } catch ( InvalidDataException e ) { - log.trace("Closing due to wrong handshake. Possible handshake rejection", e); - closeConnectionDueToWrongHandshake( e ); - return false; - } catch ( RuntimeException e ) { - log.error("Closing due to internal server error", e); - wsl.onWebsocketError( this, e ); - closeConnectionDueToInternalServerError( e ); - return false; - } - write( d.createHandshake( d.postProcessHandshakeResponseAsServer( handshake, response ) ) ); - draft = d; - open( handshake ); - return true; - } - } catch ( InvalidHandshakeException e ) { - // go on with an other draft - } - } - if( draft == null ) { - log.trace("Closing due to protocol error: no draft matches"); - closeConnectionDueToWrongHandshake( new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "no draft matches" ) ); - } - return false; - } else { - // special case for multiple step handshakes - Handshakedata tmphandshake = draft.translateHandshake( socketBuffer ); - if( !( tmphandshake instanceof ClientHandshake ) ) { - log.trace("Closing due to protocol error: wrong http function"); - flushAndClose( CloseFrame.PROTOCOL_ERROR, "wrong http function", false ); - return false; - } - ClientHandshake handshake = ( ClientHandshake ) tmphandshake; - handshakestate = draft.acceptHandshakeAsServer( handshake ); - - if( handshakestate == HandshakeState.MATCHED ) { - open( handshake ); - return true; - } else { - log.trace("Closing due to protocol error: the handshake did finally not match"); - close( CloseFrame.PROTOCOL_ERROR, "the handshake did finally not match" ); - } - return false; - } - } else if( role == Role.CLIENT ) { - draft.setParseMode( role ); - Handshakedata tmphandshake = draft.translateHandshake( socketBuffer ); - if( !( tmphandshake instanceof ServerHandshake ) ) { - log.trace("Closing due to protocol error: wrong http function"); - flushAndClose( CloseFrame.PROTOCOL_ERROR, "wrong http function", false ); - return false; - } - ServerHandshake handshake = ( ServerHandshake ) tmphandshake; - handshakestate = draft.acceptHandshakeAsClient( handshakerequest, handshake ); - if( handshakestate == HandshakeState.MATCHED ) { - try { - wsl.onWebsocketHandshakeReceivedAsClient( this, handshakerequest, handshake ); - } catch ( InvalidDataException e ) { - log.trace("Closing due to invalid data exception. Possible handshake rejection", e); - flushAndClose( e.getCloseCode(), e.getMessage(), false ); - return false; - } catch ( RuntimeException e ) { - log.error("Closing since client was never connected", e); - wsl.onWebsocketError( this, e ); - flushAndClose( CloseFrame.NEVER_CONNECTED, e.getMessage(), false ); - return false; - } - open( handshake ); - return true; - } else { - log.trace("Closing due to protocol error: draft {} refuses handshake", draft ); - close( CloseFrame.PROTOCOL_ERROR, "draft " + draft + " refuses handshake" ); - } - } - } catch ( InvalidHandshakeException e ) { - log.trace("Closing due to invalid handshake", e); - close( e ); - } - } catch ( IncompleteHandshakeException e ) { - if( tmpHandshakeBytes.capacity() == 0 ) { - socketBuffer.reset(); - int newsize = e.getPreferredSize(); - if( newsize == 0 ) { - newsize = socketBuffer.capacity() + 16; - } else { - assert ( e.getPreferredSize() >= socketBuffer.remaining() ); - } - tmpHandshakeBytes = ByteBuffer.allocate( newsize ); - - tmpHandshakeBytes.put( socketBufferNew ); - // tmpHandshakeBytes.flip(); - } else { - tmpHandshakeBytes.position( tmpHandshakeBytes.limit() ); - tmpHandshakeBytes.limit( tmpHandshakeBytes.capacity() ); - } - } - return false; - } - - private void decodeFrames( ByteBuffer socketBuffer ) { - List frames; - try { - frames = draft.translateFrame( socketBuffer ); - for( Framedata f : frames ) { - log.trace( "matched frame: {}" , f ); - draft.processFrame( this, f ); - } - } catch ( LimitExceededException e ) { - if (e.getLimit() == Integer.MAX_VALUE) { - log.error("Closing due to invalid size of frame", e); - wsl.onWebsocketError(this, e); - } - close(e); - } catch ( InvalidDataException e ) { - log.error("Closing due to invalid data in frame", e); - wsl.onWebsocketError( this, e ); - close(e); - } - } - - /** - * Close the connection if the received handshake was not correct - * - * @param exception the InvalidDataException causing this problem - */ - private void closeConnectionDueToWrongHandshake( InvalidDataException exception ) { - write( generateHttpResponseDueToError( 404 ) ); - flushAndClose( exception.getCloseCode(), exception.getMessage(), false ); - } - - /** - * Close the connection if there was a server error by a RuntimeException - * - * @param exception the RuntimeException causing this problem - */ - private void closeConnectionDueToInternalServerError( RuntimeException exception ) { - write( generateHttpResponseDueToError( 500 ) ); - flushAndClose( CloseFrame.NEVER_CONNECTED, exception.getMessage(), false ); - } - - /** - * Generate a simple response for the corresponding endpoint to indicate some error - * - * @param errorCode the http error code - * @return the complete response as ByteBuffer - */ - private ByteBuffer generateHttpResponseDueToError( int errorCode ) { - String errorCodeDescription; - switch(errorCode) { - case 404: - errorCodeDescription = "404 WebSocket Upgrade Failure"; - break; - case 500: - default: - errorCodeDescription = "500 Internal Server Error"; - } - return ByteBuffer.wrap( Charsetfunctions.asciiBytes( "HTTP/1.1 " + errorCodeDescription + "\r\nContent-Type: text/html\r\nServer: TooTallNate Java-WebSocket\r\nContent-Length: " + ( 48 + errorCodeDescription.length() ) + "\r\n\r\n

    " + errorCodeDescription + "

    " ) ); - } - - public synchronized void close( int code, String message, boolean remote ) { - if( readyState != ReadyState.CLOSING && readyState != ReadyState.CLOSED ) { - if( readyState == ReadyState.OPEN ) { - if( code == CloseFrame.ABNORMAL_CLOSE ) { - assert ( !remote ); - readyState = ReadyState.CLOSING ; - flushAndClose( code, message, false ); - return; - } - if( draft.getCloseHandshakeType() != CloseHandshakeType.NONE ) { - try { - if( !remote ) { - try { - wsl.onWebsocketCloseInitiated( this, code, message ); - } catch ( RuntimeException e ) { - wsl.onWebsocketError( this, e ); - } - } - if( isOpen() ) { - CloseFrame closeFrame = new CloseFrame(); - closeFrame.setReason( message ); - closeFrame.setCode( code ); - closeFrame.isValid(); - sendFrame( closeFrame ); - } - } catch ( InvalidDataException e ) { - log.error("generated frame is invalid", e); - wsl.onWebsocketError( this, e ); - flushAndClose( CloseFrame.ABNORMAL_CLOSE, "generated frame is invalid", false ); - } - } - flushAndClose( code, message, remote ); - } else if( code == CloseFrame.FLASHPOLICY ) { - assert ( remote ); - flushAndClose( CloseFrame.FLASHPOLICY, message, true ); - } else if( code == CloseFrame.PROTOCOL_ERROR ) { // this endpoint found a PROTOCOL_ERROR - flushAndClose( code, message, remote ); - } else { - flushAndClose( CloseFrame.NEVER_CONNECTED, message, false ); - } - readyState = ReadyState.CLOSING; - tmpHandshakeBytes = null; - return; - } - } - - @Override - public void close( int code, String message ) { - close( code, message, false ); - } - - /** - * This will close the connection immediately without a proper close handshake. - * The code and the message therefore won't be transferred over the wire also they will be forwarded to onClose/onWebsocketClose. - * - * @param code the closing code - * @param message the closing message - * @param remote Indicates who "generated" code.
    - * true means that this endpoint received the code from the other endpoint.
    - * false means this endpoint decided to send the given code,
    - * remote may also be true if this endpoint started the closing handshake since the other endpoint may not simply echo the code but close the connection the same time this endpoint does do but with an other code.
    - **/ - public synchronized void closeConnection( int code, String message, boolean remote ) { - if( readyState == ReadyState.CLOSED ) { - return; - } - //Methods like eot() call this method without calling onClose(). Due to that reason we have to adjust the ReadyState manually - if( readyState == ReadyState.OPEN ) { - if( code == CloseFrame.ABNORMAL_CLOSE ) { - readyState = ReadyState.CLOSING; - } - } - if( key != null ) { - // key.attach( null ); //see issue #114 - key.cancel(); - } - if( channel != null ) { - try { - channel.close(); - } catch ( IOException e ) { - if( e.getMessage() != null && e.getMessage().equals( "Broken pipe" ) ) { - log.trace( "Caught IOException: Broken pipe during closeConnection()", e ); - } else { - log.error("Exception during channel.close()", e); - wsl.onWebsocketError( this, e ); - } - } - } - try { - this.wsl.onWebsocketClose( this, code, message, remote ); - } catch ( RuntimeException e ) { - - wsl.onWebsocketError( this, e ); - } - if( draft != null ) - draft.reset(); - handshakerequest = null; - readyState = ReadyState.CLOSED; - } - - protected void closeConnection( int code, boolean remote ) { - closeConnection( code, "", remote ); - } - - public void closeConnection() { - if( closedremotely == null ) { - throw new IllegalStateException( "this method must be used in conjunction with flushAndClose" ); - } - closeConnection( closecode, closemessage, closedremotely ); - } - - public void closeConnection( int code, String message ) { - closeConnection( code, message, false ); - } - - public synchronized void flushAndClose( int code, String message, boolean remote ) { - if( flushandclosestate ) { - return; - } - closecode = code; - closemessage = message; - closedremotely = remote; - - flushandclosestate = true; - - wsl.onWriteDemand( this ); // ensures that all outgoing frames are flushed before closing the connection - try { - wsl.onWebsocketClosing( this, code, message, remote ); - } catch ( RuntimeException e ) { - log.error("Exception in onWebsocketClosing", e); - wsl.onWebsocketError( this, e ); - } - if( draft != null ) - draft.reset(); - handshakerequest = null; - } - - public void eot() { - if( readyState == ReadyState.NOT_YET_CONNECTED ) { - closeConnection( CloseFrame.NEVER_CONNECTED, true ); - } else if( flushandclosestate ) { - closeConnection( closecode, closemessage, closedremotely ); - } else if( draft.getCloseHandshakeType() == CloseHandshakeType.NONE ) { - closeConnection( CloseFrame.NORMAL, true ); - } else if( draft.getCloseHandshakeType() == CloseHandshakeType.ONEWAY ) { - if( role == Role.SERVER ) - closeConnection( CloseFrame.ABNORMAL_CLOSE, true ); - else - closeConnection( CloseFrame.NORMAL, true ); - } else { - closeConnection( CloseFrame.ABNORMAL_CLOSE, true ); - } - } - - @Override - public void close( int code ) { - close( code, "", false ); - } - - public void close( InvalidDataException e ) { - close( e.getCloseCode(), e.getMessage(), false ); - } - - /** - * Send Text data to the other end. - * - * @throws WebsocketNotConnectedException websocket is not yet connected - */ - @Override - public void send( String text ) { - if( text == null ) - throw new IllegalArgumentException( "Cannot send 'null' data to a WebSocketImpl." ); - send( draft.createFrames( text, role == Role.CLIENT ) ); - } - - /** - * Send Binary data (plain bytes) to the other end. - * - * @throws IllegalArgumentException the data is null - * @throws WebsocketNotConnectedException websocket is not yet connected - */ - @Override - public void send( ByteBuffer bytes ) { - if( bytes == null ) - throw new IllegalArgumentException( "Cannot send 'null' data to a WebSocketImpl." ); - send( draft.createFrames( bytes, role == Role.CLIENT ) ); - } - - @Override - public void send( byte[] bytes ) { - send( ByteBuffer.wrap( bytes ) ); - } - - private void send( Collection frames ) { - if( !isOpen() ) { - throw new WebsocketNotConnectedException(); - } - if( frames == null ) { - throw new IllegalArgumentException(); - } - ArrayList outgoingFrames = new ArrayList(); - for( Framedata f : frames ) { - log.trace( "send frame: {}", f); - outgoingFrames.add( draft.createBinaryFrame( f ) ); - } - write( outgoingFrames ); - } - - @Override - public void sendFragmentedFrame(Opcode op, ByteBuffer buffer, boolean fin ) { - send( draft.continuousFrame( op, buffer, fin ) ); - } - - @Override - public void sendFrame( Collection frames ) { - send( frames ); - } - - @Override - public void sendFrame( Framedata framedata ) { - send( Collections.singletonList( framedata ) ); - } - - public void sendPing() throws NullPointerException { - // Gets a PingFrame from WebSocketListener(wsl) and sends it. - PingFrame pingFrame = wsl.onPreparePing(this); - if(pingFrame == null) - throw new NullPointerException("onPreparePing(WebSocket) returned null. PingFrame to sent can't be null."); - sendFrame(pingFrame); - } - - @Override - public boolean hasBufferedData() { - return !this.outQueue.isEmpty(); - } - - public void startHandshake( ClientHandshakeBuilder handshakedata ) throws InvalidHandshakeException { - // Store the Handshake Request we are about to send - this.handshakerequest = draft.postProcessHandshakeRequestAsClient( handshakedata ); - - resourceDescriptor = handshakedata.getResourceDescriptor(); - assert ( resourceDescriptor != null ); - - // Notify Listener - try { - wsl.onWebsocketHandshakeSentAsClient( this, this.handshakerequest ); - } catch ( InvalidDataException e ) { - // Stop if the client code throws an exception - throw new InvalidHandshakeException( "Handshake data rejected by client." ); - } catch ( RuntimeException e ) { - log.error("Exception in startHandshake", e); - wsl.onWebsocketError( this, e ); - throw new InvalidHandshakeException( "rejected because of " + e ); - } - - // Send - write( draft.createHandshake( this.handshakerequest ) ); - } - - private void write( ByteBuffer buf ) { - log.trace( "write({}): {}", buf.remaining(), buf.remaining() > 1000 ? "too big to display" : new String( buf.array() )); - - outQueue.add( buf ); - wsl.onWriteDemand( this ); - } - - /** - * Write a list of bytebuffer (frames in binary form) into the outgoing queue - * - * @param bufs the list of bytebuffer - */ - private void write( List bufs ) { - synchronized(synchronizeWriteObject) { - for( ByteBuffer b : bufs ) { - write( b ); - } - } - } - - private void open( Handshakedata d ) { - log.trace( "open using draft: {}",draft ); - readyState = ReadyState.OPEN; - try { - wsl.onWebsocketOpen( this, d ); - } catch ( RuntimeException e ) { - wsl.onWebsocketError( this, e ); - } - } - - @Override - public boolean isOpen() { - return readyState == ReadyState.OPEN; - } - - @Override - public boolean isClosing() { - return readyState == ReadyState.CLOSING; - } - - @Override - public boolean isFlushAndClose() { - return flushandclosestate; - } - - @Override - public boolean isClosed() { - return readyState == ReadyState.CLOSED; - } - - @Override - public ReadyState getReadyState() { - return readyState; - } - - /** - * @param key the selection key of this implementation - */ - public void setSelectionKey(SelectionKey key) { - this.key = key; - } - - /** - * @return the selection key of this implementation - */ - public SelectionKey getSelectionKey() { - return key; - } - - @Override - public String toString() { - return super.toString(); // its nice to be able to set breakpoints here - } - - @Override - public InetSocketAddress getRemoteSocketAddress() { - return wsl.getRemoteSocketAddress( this ); - } - - @Override - public InetSocketAddress getLocalSocketAddress() { - return wsl.getLocalSocketAddress( this ); - } - - @Override - public Draft getDraft() { - return draft; - } - - @Override - public void close() { - close( CloseFrame.NORMAL ); - } - - @Override - public String getResourceDescriptor() { - return resourceDescriptor; - } - - /** - * Getter for the last pong received - * - * @return the timestamp for the last received pong - */ - long getLastPong() { - return lastPong; - } - - /** - * Update the timestamp when the last pong was received - */ - public void updateLastPong() { - this.lastPong = System.nanoTime(); - } - - /** - * Getter for the websocket listener - * - * @return the websocket listener associated with this instance - */ - public WebSocketListener getWebSocketListener() { - return wsl; - } - - @Override - @SuppressWarnings("unchecked") - public T getAttachment() { - return (T) attachment; - } - - @Override - public boolean hasSSLSupport() { - return channel instanceof ISSLChannel; - } - - @Override - public SSLSession getSSLSession() { - if (!hasSSLSupport()) { - throw new IllegalArgumentException("This websocket uses ws instead of wss. No SSLSession available."); - } - return ((ISSLChannel) channel).getSSLEngine().getSession(); - } - - @Override - public IProtocol getProtocol() { - if (draft == null) - return null; - if (!(draft instanceof Draft_6455)) - throw new IllegalArgumentException("This draft does not support Sec-WebSocket-Protocol"); - return ((Draft_6455) draft).getProtocol(); - } - - @Override - public void setAttachment(T attachment) { - this.attachment = attachment; - } - - public ByteChannel getChannel() { - return channel; - } - - public void setChannel(ByteChannel channel) { - this.channel = channel; - } - - public WebSocketWorker getWorkerThread() { - return workerThread; - } - - public void setWorkerThread(WebSocketWorker workerThread) { - this.workerThread = workerThread; - } + /** + * The default port of WebSockets, as defined in the spec. If the nullary constructor is used, + * DEFAULT_PORT will be the port the WebSocketServer is binded to. Note that ports under 1024 + * usually require root permissions. + */ + public static final int DEFAULT_PORT = 80; + + /** + * The default wss port of WebSockets, as defined in the spec. If the nullary constructor is used, + * DEFAULT_WSS_PORT will be the port the WebSocketServer is binded to. Note that ports under 1024 + * usually require root permissions. + */ + public static final int DEFAULT_WSS_PORT = 443; + + /** + * Initial buffer size + */ + public static final int RCVBUF = 16384; + + /** + * Logger instance + * + * @since 1.4.0 + */ + private final Logger log = LoggerFactory.getLogger(WebSocketImpl.class); + + /** + * Queue of buffers that need to be sent to the client. + */ + public final BlockingQueue outQueue; + /** + * Queue of buffers that need to be processed + */ + public final BlockingQueue inQueue; + /** + * The listener to notify of WebSocket events. + */ + private final WebSocketListener wsl; + + private SelectionKey key; + + /** + * the possibly wrapped channel object whose selection is controlled by {@link #key} + */ + private ByteChannel channel; + /** + * Helper variable meant to store the thread which ( exclusively ) triggers this objects decode + * method. + **/ + private WebSocketWorker workerThread; + /** + * When true no further frames may be submitted to be sent + */ + private boolean flushandclosestate = false; + + /** + * The current state of the connection + */ + private volatile ReadyState readyState = ReadyState.NOT_YET_CONNECTED; + + /** + * A list of drafts available for this websocket + */ + private List knownDrafts; + + /** + * The draft which is used by this websocket + */ + private Draft draft = null; + + /** + * The role which this websocket takes in the connection + */ + private Role role; + + /** + * the bytes of an incomplete received handshake + */ + private ByteBuffer tmpHandshakeBytes = ByteBuffer.allocate(0); + + /** + * stores the handshake sent by this websocket ( Role.CLIENT only ) + */ + private ClientHandshake handshakerequest = null; + + private String closemessage = null; + private Integer closecode = null; + private Boolean closedremotely = null; + + private String resourceDescriptor = null; + + /** + * Attribute, when the last pong was received + */ + private long lastPong = System.nanoTime(); + + /** + * Attribut to synchronize the write + */ + private final Object synchronizeWriteObject = new Object(); + + /** + * Attribute to store connection attachment + * + * @since 1.3.7 + */ + private Object attachment; + + /** + * Creates a websocket with server role + * + * @param listener The listener for this instance + * @param drafts The drafts which should be used + */ + public WebSocketImpl(WebSocketListener listener, List drafts) { + this(listener, (Draft) null); + this.role = Role.SERVER; + // draft.copyInstance will be called when the draft is first needed + if (drafts == null || drafts.isEmpty()) { + knownDrafts = new ArrayList(); + knownDrafts.add(new Draft_6455()); + } else { + knownDrafts = drafts; + } + } + + /** + * creates a websocket with client role + * + * @param listener The listener for this instance + * @param draft The draft which should be used + */ + public WebSocketImpl(WebSocketListener listener, Draft draft) { + if (listener == null || (draft == null && role + == Role.SERVER))// socket can be null because we want do be able to create the object without already having a bound channel + { + throw new IllegalArgumentException("parameters must not be null"); + } + this.outQueue = new LinkedBlockingQueue(); + inQueue = new LinkedBlockingQueue(); + this.wsl = listener; + this.role = Role.CLIENT; + if (draft != null) { + this.draft = draft.copyInstance(); + } + } + + /** + * Method to decode the provided ByteBuffer + * + * @param socketBuffer the ByteBuffer to decode + */ + public void decode(ByteBuffer socketBuffer) { + assert (socketBuffer.hasRemaining()); + log.trace("process({}): ({})", socketBuffer.remaining(), + (socketBuffer.remaining() > 1000 ? "too big to display" + : new String(socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining()))); + + if (readyState != ReadyState.NOT_YET_CONNECTED) { + if (readyState == ReadyState.OPEN) { + decodeFrames(socketBuffer); + } + } else { + if (decodeHandshake(socketBuffer) && (!isClosing() && !isClosed())) { + assert (tmpHandshakeBytes.hasRemaining() != socketBuffer.hasRemaining() || !socketBuffer + .hasRemaining()); // the buffers will never have remaining bytes at the same time + if (socketBuffer.hasRemaining()) { + decodeFrames(socketBuffer); + } else if (tmpHandshakeBytes.hasRemaining()) { + decodeFrames(tmpHandshakeBytes); + } + } + } + } + + /** + * Returns whether the handshake phase has is completed. In case of a broken handshake this will + * be never the case. + **/ + private boolean decodeHandshake(ByteBuffer socketBufferNew) { + ByteBuffer socketBuffer; + if (tmpHandshakeBytes.capacity() == 0) { + socketBuffer = socketBufferNew; + } else { + if (tmpHandshakeBytes.remaining() < socketBufferNew.remaining()) { + ByteBuffer buf = ByteBuffer + .allocate(tmpHandshakeBytes.capacity() + socketBufferNew.remaining()); + tmpHandshakeBytes.flip(); + buf.put(tmpHandshakeBytes); + tmpHandshakeBytes = buf; + } + + tmpHandshakeBytes.put(socketBufferNew); + tmpHandshakeBytes.flip(); + socketBuffer = tmpHandshakeBytes; + } + socketBuffer.mark(); + try { + HandshakeState handshakestate; + try { + if (role == Role.SERVER) { + if (draft == null) { + for (Draft d : knownDrafts) { + d = d.copyInstance(); + try { + d.setParseMode(role); + socketBuffer.reset(); + Handshakedata tmphandshake = d.translateHandshake(socketBuffer); + if (!(tmphandshake instanceof ClientHandshake)) { + log.trace("Closing due to wrong handshake"); + closeConnectionDueToWrongHandshake( + new InvalidDataException(CloseFrame.PROTOCOL_ERROR, "wrong http function")); + return false; + } + ClientHandshake handshake = (ClientHandshake) tmphandshake; + handshakestate = d.acceptHandshakeAsServer(handshake); + if (handshakestate == HandshakeState.MATCHED) { + resourceDescriptor = handshake.getResourceDescriptor(); + ServerHandshakeBuilder response; + try { + response = wsl.onWebsocketHandshakeReceivedAsServer(this, d, handshake); + } catch (InvalidDataException e) { + log.trace("Closing due to wrong handshake. Possible handshake rejection", e); + closeConnectionDueToWrongHandshake(e); + return false; + } catch (RuntimeException e) { + log.error("Closing due to internal server error", e); + wsl.onWebsocketError(this, e); + closeConnectionDueToInternalServerError(e); + return false; + } + write(d.createHandshake( + d.postProcessHandshakeResponseAsServer(handshake, response))); + draft = d; + open(handshake); + return true; + } + } catch (InvalidHandshakeException e) { + // go on with an other draft + } + } + if (draft == null) { + log.trace("Closing due to protocol error: no draft matches"); + closeConnectionDueToWrongHandshake( + new InvalidDataException(CloseFrame.PROTOCOL_ERROR, "no draft matches")); + } + return false; + } else { + // special case for multiple step handshakes + Handshakedata tmphandshake = draft.translateHandshake(socketBuffer); + if (!(tmphandshake instanceof ClientHandshake)) { + log.trace("Closing due to protocol error: wrong http function"); + flushAndClose(CloseFrame.PROTOCOL_ERROR, "wrong http function", false); + return false; + } + ClientHandshake handshake = (ClientHandshake) tmphandshake; + handshakestate = draft.acceptHandshakeAsServer(handshake); + + if (handshakestate == HandshakeState.MATCHED) { + open(handshake); + return true; + } else { + log.trace("Closing due to protocol error: the handshake did finally not match"); + close(CloseFrame.PROTOCOL_ERROR, "the handshake did finally not match"); + } + return false; + } + } else if (role == Role.CLIENT) { + draft.setParseMode(role); + Handshakedata tmphandshake = draft.translateHandshake(socketBuffer); + if (!(tmphandshake instanceof ServerHandshake)) { + log.trace("Closing due to protocol error: wrong http function"); + flushAndClose(CloseFrame.PROTOCOL_ERROR, "wrong http function", false); + return false; + } + ServerHandshake handshake = (ServerHandshake) tmphandshake; + handshakestate = draft.acceptHandshakeAsClient(handshakerequest, handshake); + if (handshakestate == HandshakeState.MATCHED) { + try { + wsl.onWebsocketHandshakeReceivedAsClient(this, handshakerequest, handshake); + } catch (InvalidDataException e) { + log.trace("Closing due to invalid data exception. Possible handshake rejection", e); + flushAndClose(e.getCloseCode(), e.getMessage(), false); + return false; + } catch (RuntimeException e) { + log.error("Closing since client was never connected", e); + wsl.onWebsocketError(this, e); + flushAndClose(CloseFrame.NEVER_CONNECTED, e.getMessage(), false); + return false; + } + open(handshake); + return true; + } else { + log.trace("Closing due to protocol error: draft {} refuses handshake", draft); + close(CloseFrame.PROTOCOL_ERROR, "draft " + draft + " refuses handshake"); + } + } + } catch (InvalidHandshakeException e) { + log.trace("Closing due to invalid handshake", e); + close(e); + } + } catch (IncompleteHandshakeException e) { + if (tmpHandshakeBytes.capacity() == 0) { + socketBuffer.reset(); + int newsize = e.getPreferredSize(); + if (newsize == 0) { + newsize = socketBuffer.capacity() + 16; + } else { + assert (e.getPreferredSize() >= socketBuffer.remaining()); + } + tmpHandshakeBytes = ByteBuffer.allocate(newsize); + + tmpHandshakeBytes.put(socketBufferNew); + // tmpHandshakeBytes.flip(); + } else { + tmpHandshakeBytes.position(tmpHandshakeBytes.limit()); + tmpHandshakeBytes.limit(tmpHandshakeBytes.capacity()); + } + } + return false; + } + + private void decodeFrames(ByteBuffer socketBuffer) { + List frames; + try { + frames = draft.translateFrame(socketBuffer); + for (Framedata f : frames) { + log.trace("matched frame: {}", f); + draft.processFrame(this, f); + } + } catch (LimitExceededException e) { + if (e.getLimit() == Integer.MAX_VALUE) { + log.error("Closing due to invalid size of frame", e); + wsl.onWebsocketError(this, e); + } + close(e); + } catch (InvalidDataException e) { + log.error("Closing due to invalid data in frame", e); + wsl.onWebsocketError(this, e); + close(e); + } + } + + /** + * Close the connection if the received handshake was not correct + * + * @param exception the InvalidDataException causing this problem + */ + private void closeConnectionDueToWrongHandshake(InvalidDataException exception) { + write(generateHttpResponseDueToError(404)); + flushAndClose(exception.getCloseCode(), exception.getMessage(), false); + } + + /** + * Close the connection if there was a server error by a RuntimeException + * + * @param exception the RuntimeException causing this problem + */ + private void closeConnectionDueToInternalServerError(RuntimeException exception) { + write(generateHttpResponseDueToError(500)); + flushAndClose(CloseFrame.NEVER_CONNECTED, exception.getMessage(), false); + } + + /** + * Generate a simple response for the corresponding endpoint to indicate some error + * + * @param errorCode the http error code + * @return the complete response as ByteBuffer + */ + private ByteBuffer generateHttpResponseDueToError(int errorCode) { + String errorCodeDescription; + switch (errorCode) { + case 404: + errorCodeDescription = "404 WebSocket Upgrade Failure"; + break; + case 500: + default: + errorCodeDescription = "500 Internal Server Error"; + } + return ByteBuffer.wrap(Charsetfunctions.asciiBytes("HTTP/1.1 " + errorCodeDescription + + "\r\nContent-Type: text/html\r\nServer: TooTallNate Java-WebSocket\r\nContent-Length: " + + (48 + errorCodeDescription.length()) + "\r\n\r\n

    " + + errorCodeDescription + "

    ")); + } + + public synchronized void close(int code, String message, boolean remote) { + if (readyState != ReadyState.CLOSING && readyState != ReadyState.CLOSED) { + if (readyState == ReadyState.OPEN) { + if (code == CloseFrame.ABNORMAL_CLOSE) { + assert (!remote); + readyState = ReadyState.CLOSING; + flushAndClose(code, message, false); + return; + } + if (draft.getCloseHandshakeType() != CloseHandshakeType.NONE) { + try { + if (!remote) { + try { + wsl.onWebsocketCloseInitiated(this, code, message); + } catch (RuntimeException e) { + wsl.onWebsocketError(this, e); + } + } + if (isOpen()) { + CloseFrame closeFrame = new CloseFrame(); + closeFrame.setReason(message); + closeFrame.setCode(code); + closeFrame.isValid(); + sendFrame(closeFrame); + } + } catch (InvalidDataException e) { + log.error("generated frame is invalid", e); + wsl.onWebsocketError(this, e); + flushAndClose(CloseFrame.ABNORMAL_CLOSE, "generated frame is invalid", false); + } + } + flushAndClose(code, message, remote); + } else if (code == CloseFrame.FLASHPOLICY) { + assert (remote); + flushAndClose(CloseFrame.FLASHPOLICY, message, true); + } else if (code == CloseFrame.PROTOCOL_ERROR) { // this endpoint found a PROTOCOL_ERROR + flushAndClose(code, message, remote); + } else { + flushAndClose(CloseFrame.NEVER_CONNECTED, message, false); + } + readyState = ReadyState.CLOSING; + tmpHandshakeBytes = null; + return; + } + } + + @Override + public void close(int code, String message) { + close(code, message, false); + } + + /** + * This will close the connection immediately without a proper close handshake. The code and the + * message therefore won't be transferred over the wire also they will be forwarded to + * onClose/onWebsocketClose. + * + * @param code the closing code + * @param message the closing message + * @param remote Indicates who "generated" code.
    + * true means that this endpoint received the code from + * the other endpoint.
    + * false means this endpoint decided to send the given code,
    + * remote may also be true if this endpoint started the closing + * handshake since the other endpoint may not simply echo the code but + * close the connection the same time this endpoint does do but with an other + * code.
    + **/ + public synchronized void closeConnection(int code, String message, boolean remote) { + if (readyState == ReadyState.CLOSED) { + return; + } + //Methods like eot() call this method without calling onClose(). Due to that reason we have to adjust the ReadyState manually + if (readyState == ReadyState.OPEN) { + if (code == CloseFrame.ABNORMAL_CLOSE) { + readyState = ReadyState.CLOSING; + } + } + if (key != null) { + // key.attach( null ); //see issue #114 + key.cancel(); + } + if (channel != null) { + try { + channel.close(); + } catch (IOException e) { + if (e.getMessage() != null && e.getMessage().equals("Broken pipe")) { + log.trace("Caught IOException: Broken pipe during closeConnection()", e); + } else { + log.error("Exception during channel.close()", e); + wsl.onWebsocketError(this, e); + } + } + } + try { + this.wsl.onWebsocketClose(this, code, message, remote); + } catch (RuntimeException e) { + + wsl.onWebsocketError(this, e); + } + if (draft != null) { + draft.reset(); + } + handshakerequest = null; + readyState = ReadyState.CLOSED; + } + + protected void closeConnection(int code, boolean remote) { + closeConnection(code, "", remote); + } + + public void closeConnection() { + if (closedremotely == null) { + throw new IllegalStateException("this method must be used in conjunction with flushAndClose"); + } + closeConnection(closecode, closemessage, closedremotely); + } + + public void closeConnection(int code, String message) { + closeConnection(code, message, false); + } + + public synchronized void flushAndClose(int code, String message, boolean remote) { + if (flushandclosestate) { + return; + } + closecode = code; + closemessage = message; + closedremotely = remote; + + flushandclosestate = true; + + wsl.onWriteDemand( + this); // ensures that all outgoing frames are flushed before closing the connection + try { + wsl.onWebsocketClosing(this, code, message, remote); + } catch (RuntimeException e) { + log.error("Exception in onWebsocketClosing", e); + wsl.onWebsocketError(this, e); + } + if (draft != null) { + draft.reset(); + } + handshakerequest = null; + } + + public void eot() { + if (readyState == ReadyState.NOT_YET_CONNECTED) { + closeConnection(CloseFrame.NEVER_CONNECTED, true); + } else if (flushandclosestate) { + closeConnection(closecode, closemessage, closedremotely); + } else if (draft.getCloseHandshakeType() == CloseHandshakeType.NONE) { + closeConnection(CloseFrame.NORMAL, true); + } else if (draft.getCloseHandshakeType() == CloseHandshakeType.ONEWAY) { + if (role == Role.SERVER) { + closeConnection(CloseFrame.ABNORMAL_CLOSE, true); + } else { + closeConnection(CloseFrame.NORMAL, true); + } + } else { + closeConnection(CloseFrame.ABNORMAL_CLOSE, true); + } + } + + @Override + public void close(int code) { + close(code, "", false); + } + + public void close(InvalidDataException e) { + close(e.getCloseCode(), e.getMessage(), false); + } + + /** + * Send Text data to the other end. + * + * @throws WebsocketNotConnectedException websocket is not yet connected + */ + @Override + public void send(String text) { + if (text == null) { + throw new IllegalArgumentException("Cannot send 'null' data to a WebSocketImpl."); + } + send(draft.createFrames(text, role == Role.CLIENT)); + } + + /** + * Send Binary data (plain bytes) to the other end. + * + * @throws IllegalArgumentException the data is null + * @throws WebsocketNotConnectedException websocket is not yet connected + */ + @Override + public void send(ByteBuffer bytes) { + if (bytes == null) { + throw new IllegalArgumentException("Cannot send 'null' data to a WebSocketImpl."); + } + send(draft.createFrames(bytes, role == Role.CLIENT)); + } + + @Override + public void send(byte[] bytes) { + send(ByteBuffer.wrap(bytes)); + } + + private void send(Collection frames) { + if (!isOpen()) { + throw new WebsocketNotConnectedException(); + } + if (frames == null) { + throw new IllegalArgumentException(); + } + ArrayList outgoingFrames = new ArrayList(); + for (Framedata f : frames) { + log.trace("send frame: {}", f); + outgoingFrames.add(draft.createBinaryFrame(f)); + } + write(outgoingFrames); + } + + @Override + public void sendFragmentedFrame(Opcode op, ByteBuffer buffer, boolean fin) { + send(draft.continuousFrame(op, buffer, fin)); + } + + @Override + public void sendFrame(Collection frames) { + send(frames); + } + + @Override + public void sendFrame(Framedata framedata) { + send(Collections.singletonList(framedata)); + } + + public void sendPing() throws NullPointerException { + // Gets a PingFrame from WebSocketListener(wsl) and sends it. + PingFrame pingFrame = wsl.onPreparePing(this); + if (pingFrame == null) { + throw new NullPointerException( + "onPreparePing(WebSocket) returned null. PingFrame to sent can't be null."); + } + sendFrame(pingFrame); + } + + @Override + public boolean hasBufferedData() { + return !this.outQueue.isEmpty(); + } + + public void startHandshake(ClientHandshakeBuilder handshakedata) + throws InvalidHandshakeException { + // Store the Handshake Request we are about to send + this.handshakerequest = draft.postProcessHandshakeRequestAsClient(handshakedata); + + resourceDescriptor = handshakedata.getResourceDescriptor(); + assert (resourceDescriptor != null); + + // Notify Listener + try { + wsl.onWebsocketHandshakeSentAsClient(this, this.handshakerequest); + } catch (InvalidDataException e) { + // Stop if the client code throws an exception + throw new InvalidHandshakeException("Handshake data rejected by client."); + } catch (RuntimeException e) { + log.error("Exception in startHandshake", e); + wsl.onWebsocketError(this, e); + throw new InvalidHandshakeException("rejected because of " + e); + } + + // Send + write(draft.createHandshake(this.handshakerequest)); + } + + private void write(ByteBuffer buf) { + log.trace("write({}): {}", buf.remaining(), + buf.remaining() > 1000 ? "too big to display" : new String(buf.array())); + + outQueue.add(buf); + wsl.onWriteDemand(this); + } + + /** + * Write a list of bytebuffer (frames in binary form) into the outgoing queue + * + * @param bufs the list of bytebuffer + */ + private void write(List bufs) { + synchronized (synchronizeWriteObject) { + for (ByteBuffer b : bufs) { + write(b); + } + } + } + + private void open(Handshakedata d) { + log.trace("open using draft: {}", draft); + readyState = ReadyState.OPEN; + try { + wsl.onWebsocketOpen(this, d); + } catch (RuntimeException e) { + wsl.onWebsocketError(this, e); + } + } + + @Override + public boolean isOpen() { + return readyState == ReadyState.OPEN; + } + + @Override + public boolean isClosing() { + return readyState == ReadyState.CLOSING; + } + + @Override + public boolean isFlushAndClose() { + return flushandclosestate; + } + + @Override + public boolean isClosed() { + return readyState == ReadyState.CLOSED; + } + + @Override + public ReadyState getReadyState() { + return readyState; + } + + /** + * @param key the selection key of this implementation + */ + public void setSelectionKey(SelectionKey key) { + this.key = key; + } + + /** + * @return the selection key of this implementation + */ + public SelectionKey getSelectionKey() { + return key; + } + + @Override + public String toString() { + return super.toString(); // its nice to be able to set breakpoints here + } + + @Override + public InetSocketAddress getRemoteSocketAddress() { + return wsl.getRemoteSocketAddress(this); + } + + @Override + public InetSocketAddress getLocalSocketAddress() { + return wsl.getLocalSocketAddress(this); + } + + @Override + public Draft getDraft() { + return draft; + } + + @Override + public void close() { + close(CloseFrame.NORMAL); + } + + @Override + public String getResourceDescriptor() { + return resourceDescriptor; + } + + /** + * Getter for the last pong received + * + * @return the timestamp for the last received pong + */ + long getLastPong() { + return lastPong; + } + + /** + * Update the timestamp when the last pong was received + */ + public void updateLastPong() { + this.lastPong = System.nanoTime(); + } + + /** + * Getter for the websocket listener + * + * @return the websocket listener associated with this instance + */ + public WebSocketListener getWebSocketListener() { + return wsl; + } + + @Override + @SuppressWarnings("unchecked") + public T getAttachment() { + return (T) attachment; + } + + @Override + public boolean hasSSLSupport() { + return channel instanceof ISSLChannel; + } + + @Override + public SSLSession getSSLSession() { + if (!hasSSLSupport()) { + throw new IllegalArgumentException( + "This websocket uses ws instead of wss. No SSLSession available."); + } + return ((ISSLChannel) channel).getSSLEngine().getSession(); + } + + @Override + public IProtocol getProtocol() { + if (draft == null) { + return null; + } + if (!(draft instanceof Draft_6455)) { + throw new IllegalArgumentException("This draft does not support Sec-WebSocket-Protocol"); + } + return ((Draft_6455) draft).getProtocol(); + } + + @Override + public void setAttachment(T attachment) { + this.attachment = attachment; + } + + public ByteChannel getChannel() { + return channel; + } + + public void setChannel(ByteChannel channel) { + this.channel = channel; + } + + public WebSocketWorker getWorkerThread() { + return workerThread; + } + + public void setWorkerThread(WebSocketWorker workerThread) { + this.workerThread = workerThread; + } } diff --git a/src/main/java/org/java_websocket/WebSocketListener.java b/src/main/java/org/java_websocket/WebSocketListener.java index 7271100c4..2150e23ec 100644 --- a/src/main/java/org/java_websocket/WebSocketListener.java +++ b/src/main/java/org/java_websocket/WebSocketListener.java @@ -39,171 +39,163 @@ import org.java_websocket.handshake.ServerHandshakeBuilder; /** - * Implemented by WebSocketClient and WebSocketServer. - * The methods within are called by WebSocket. - * Almost every method takes a first parameter conn which represents the source of the respective event. + * Implemented by WebSocketClient and WebSocketServer. The methods within are + * called by WebSocket. Almost every method takes a first parameter conn which represents + * the source of the respective event. */ public interface WebSocketListener { - /** - * Called on the server side when the socket connection is first established, and the WebSocket - * handshake has been received. This method allows to deny connections based on the received handshake.
    - * By default this method only requires protocol compliance. - * - * @param conn - * The WebSocket related to this event - * @param draft - * The protocol draft the client uses to connect - * @param request - * The opening http message send by the client. Can be used to access additional fields like cookies. - * @return Returns an incomplete handshake containing all optional fields - * @throws InvalidDataException - * Throwing this exception will cause this handshake to be rejected - */ - ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer( WebSocket conn, Draft draft, ClientHandshake request ) throws InvalidDataException; - - /** - * Called on the client side when the socket connection is first established, and the WebSocketImpl - * handshake response has been received. - * - * @param conn - * The WebSocket related to this event - * @param request - * The handshake initially send out to the server by this websocket. - * @param response - * The handshake the server sent in response to the request. - * @throws InvalidDataException - * Allows the client to reject the connection with the server in respect of its handshake response. - */ - void onWebsocketHandshakeReceivedAsClient( WebSocket conn, ClientHandshake request, ServerHandshake response ) throws InvalidDataException; - - /** - * Called on the client side when the socket connection is first established, and the WebSocketImpl - * handshake has just been sent. - * - * @param conn - * The WebSocket related to this event - * @param request - * The handshake sent to the server by this websocket - * @throws InvalidDataException - * Allows the client to stop the connection from progressing - */ - void onWebsocketHandshakeSentAsClient( WebSocket conn, ClientHandshake request ) throws InvalidDataException; - - /** - * Called when an entire text frame has been received. Do whatever you want - * here... - * - * @param conn - * The WebSocket instance this event is occurring on. - * @param message - * The UTF-8 decoded message that was received. - */ - void onWebsocketMessage( WebSocket conn, String message ); - - /** - * Called when an entire binary frame has been received. Do whatever you want - * here... - * - * @param conn - * The WebSocket instance this event is occurring on. - * @param blob - * The binary message that was received. - */ - void onWebsocketMessage( WebSocket conn, ByteBuffer blob ); - - /** - * Called after onHandshakeReceived returns true. - * Indicates that a complete WebSocket connection has been established, - * and we are ready to send/receive data. - * - * @param conn The WebSocket instance this event is occurring on. - * @param d The handshake of the websocket instance - */ - void onWebsocketOpen( WebSocket conn, Handshakedata d ); - - /** - * Called after WebSocket#close is explicity called, or when the - * other end of the WebSocket connection is closed. - * - * @param ws The WebSocket instance this event is occurring on. - * @param code The codes can be looked up here: {@link CloseFrame} - * @param reason Additional information string - * @param remote Returns whether or not the closing of the connection was initiated by the remote host. - */ - void onWebsocketClose( WebSocket ws, int code, String reason, boolean remote ); - - /** Called as soon as no further frames are accepted - * - * @param ws The WebSocket instance this event is occurring on. - * @param code The codes can be looked up here: {@link CloseFrame} - * @param reason Additional information string - * @param remote Returns whether or not the closing of the connection was initiated by the remote host. - */ - void onWebsocketClosing( WebSocket ws, int code, String reason, boolean remote ); - - /** send when this peer sends a close handshake - * - * @param ws The WebSocket instance this event is occurring on. - * @param code The codes can be looked up here: {@link CloseFrame} - * @param reason Additional information string - */ - void onWebsocketCloseInitiated( WebSocket ws, int code, String reason ); - - /** - * Called if an exception worth noting occurred. - * If an error causes the connection to fail onClose will be called additionally afterwards. - * - * @param conn The WebSocket instance this event is occurring on. - * @param ex - * The exception that occurred.
    - * Might be null if the exception is not related to any specific connection. For example if the server port could not be bound. - */ - void onWebsocketError( WebSocket conn, Exception ex ); - - /** - * Called a ping frame has been received. - * This method must send a corresponding pong by itself. - * - * @param conn The WebSocket instance this event is occurring on. - * @param f The ping frame. Control frames may contain payload. - */ - void onWebsocketPing( WebSocket conn, Framedata f ); - - /** - * Called just before a ping frame is sent, in order to allow users to customize their ping frame data. - * - * @param conn The WebSocket connection from which the ping frame will be sent. - * @return PingFrame to be sent. - */ - PingFrame onPreparePing(WebSocket conn ); - - /** - * Called when a pong frame is received. - * - * @param conn The WebSocket instance this event is occurring on. - * @param f The pong frame. Control frames may contain payload. - **/ - void onWebsocketPong( WebSocket conn, Framedata f ); - - /** This method is used to inform the selector thread that there is data queued to be written to the socket. - * @param conn The WebSocket instance this event is occurring on. - */ - void onWriteDemand( WebSocket conn ); - - /** - * @see WebSocket#getLocalSocketAddress() - * - * @param conn The WebSocket instance this event is occurring on. - * @return Returns the address of the endpoint this socket is bound to. - */ - InetSocketAddress getLocalSocketAddress( WebSocket conn ); - - /** - * @see WebSocket#getRemoteSocketAddress() - * - * @param conn The WebSocket instance this event is occurring on. - * @return Returns the address of the endpoint this socket is connected to, or{@code null} if it is unconnected. - */ - InetSocketAddress getRemoteSocketAddress( WebSocket conn ); + /** + * Called on the server side when the socket connection is first established, and the WebSocket + * handshake has been received. This method allows to deny connections based on the received + * handshake.
    By default this method only requires protocol compliance. + * + * @param conn The WebSocket related to this event + * @param draft The protocol draft the client uses to connect + * @param request The opening http message send by the client. Can be used to access additional + * fields like cookies. + * @return Returns an incomplete handshake containing all optional fields + * @throws InvalidDataException Throwing this exception will cause this handshake to be rejected + */ + ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft, + ClientHandshake request) throws InvalidDataException; + + /** + * Called on the client side when the socket connection is first established, and the + * WebSocketImpl handshake response has been received. + * + * @param conn The WebSocket related to this event + * @param request The handshake initially send out to the server by this websocket. + * @param response The handshake the server sent in response to the request. + * @throws InvalidDataException Allows the client to reject the connection with the server in + * respect of its handshake response. + */ + void onWebsocketHandshakeReceivedAsClient(WebSocket conn, ClientHandshake request, + ServerHandshake response) throws InvalidDataException; + + /** + * Called on the client side when the socket connection is first established, and the + * WebSocketImpl handshake has just been sent. + * + * @param conn The WebSocket related to this event + * @param request The handshake sent to the server by this websocket + * @throws InvalidDataException Allows the client to stop the connection from progressing + */ + void onWebsocketHandshakeSentAsClient(WebSocket conn, ClientHandshake request) + throws InvalidDataException; + + /** + * Called when an entire text frame has been received. Do whatever you want here... + * + * @param conn The WebSocket instance this event is occurring on. + * @param message The UTF-8 decoded message that was received. + */ + void onWebsocketMessage(WebSocket conn, String message); + + /** + * Called when an entire binary frame has been received. Do whatever you want here... + * + * @param conn The WebSocket instance this event is occurring on. + * @param blob The binary message that was received. + */ + void onWebsocketMessage(WebSocket conn, ByteBuffer blob); + + /** + * Called after onHandshakeReceived returns true. Indicates that a complete + * WebSocket connection has been established, and we are ready to send/receive data. + * + * @param conn The WebSocket instance this event is occurring on. + * @param d The handshake of the websocket instance + */ + void onWebsocketOpen(WebSocket conn, Handshakedata d); + + /** + * Called after WebSocket#close is explicity called, or when the other end of the + * WebSocket connection is closed. + * + * @param ws The WebSocket instance this event is occurring on. + * @param code The codes can be looked up here: {@link CloseFrame} + * @param reason Additional information string + * @param remote Returns whether or not the closing of the connection was initiated by the remote + * host. + */ + void onWebsocketClose(WebSocket ws, int code, String reason, boolean remote); + + /** + * Called as soon as no further frames are accepted + * + * @param ws The WebSocket instance this event is occurring on. + * @param code The codes can be looked up here: {@link CloseFrame} + * @param reason Additional information string + * @param remote Returns whether or not the closing of the connection was initiated by the remote + * host. + */ + void onWebsocketClosing(WebSocket ws, int code, String reason, boolean remote); + + /** + * send when this peer sends a close handshake + * + * @param ws The WebSocket instance this event is occurring on. + * @param code The codes can be looked up here: {@link CloseFrame} + * @param reason Additional information string + */ + void onWebsocketCloseInitiated(WebSocket ws, int code, String reason); + + /** + * Called if an exception worth noting occurred. If an error causes the connection to fail onClose + * will be called additionally afterwards. + * + * @param conn The WebSocket instance this event is occurring on. + * @param ex The exception that occurred.
    Might be null if the exception is not related to + * any specific connection. For example if the server port could not be bound. + */ + void onWebsocketError(WebSocket conn, Exception ex); + + /** + * Called a ping frame has been received. This method must send a corresponding pong by itself. + * + * @param conn The WebSocket instance this event is occurring on. + * @param f The ping frame. Control frames may contain payload. + */ + void onWebsocketPing(WebSocket conn, Framedata f); + + /** + * Called just before a ping frame is sent, in order to allow users to customize their ping frame + * data. + * + * @param conn The WebSocket connection from which the ping frame will be sent. + * @return PingFrame to be sent. + */ + PingFrame onPreparePing(WebSocket conn); + + /** + * Called when a pong frame is received. + * + * @param conn The WebSocket instance this event is occurring on. + * @param f The pong frame. Control frames may contain payload. + **/ + void onWebsocketPong(WebSocket conn, Framedata f); + + /** + * This method is used to inform the selector thread that there is data queued to be written to + * the socket. + * + * @param conn The WebSocket instance this event is occurring on. + */ + void onWriteDemand(WebSocket conn); + + /** + * @param conn The WebSocket instance this event is occurring on. + * @return Returns the address of the endpoint this socket is bound to. + * @see WebSocket#getLocalSocketAddress() + */ + InetSocketAddress getLocalSocketAddress(WebSocket conn); + + /** + * @param conn The WebSocket instance this event is occurring on. + * @return Returns the address of the endpoint this socket is connected to, or{@code null} if it + * is unconnected. + * @see WebSocket#getRemoteSocketAddress() + */ + InetSocketAddress getRemoteSocketAddress(WebSocket conn); } diff --git a/src/main/java/org/java_websocket/WebSocketServerFactory.java b/src/main/java/org/java_websocket/WebSocketServerFactory.java index 2a6c2347f..d6d5cce82 100644 --- a/src/main/java/org/java_websocket/WebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/WebSocketServerFactory.java @@ -37,24 +37,26 @@ * Interface to encapsulate the required methods for a websocket factory */ public interface WebSocketServerFactory extends WebSocketFactory { - @Override - WebSocketImpl createWebSocket( WebSocketAdapter a, Draft d); - - @Override - WebSocketImpl createWebSocket( WebSocketAdapter a, List drafts ); - - /** - * Allows to wrap the SocketChannel( key.channel() ) to insert a protocol layer( like ssl or proxy authentication) beyond the ws layer. - * - * @param channel The SocketChannel to wrap - * @param key a SelectionKey of an open SocketChannel. - * @return The channel on which the read and write operations will be performed.
    - * @throws IOException may be thrown while writing on the channel - */ - ByteChannel wrapChannel(SocketChannel channel, SelectionKey key ) throws IOException; - - /** - * Allows to shutdown the websocket factory for a clean shutdown - */ - void close(); + + @Override + WebSocketImpl createWebSocket(WebSocketAdapter a, Draft d); + + @Override + WebSocketImpl createWebSocket(WebSocketAdapter a, List drafts); + + /** + * Allows to wrap the SocketChannel( key.channel() ) to insert a protocol layer( like ssl or proxy + * authentication) beyond the ws layer. + * + * @param channel The SocketChannel to wrap + * @param key a SelectionKey of an open SocketChannel. + * @return The channel on which the read and write operations will be performed.
    + * @throws IOException may be thrown while writing on the channel + */ + ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException; + + /** + * Allows to shutdown the websocket factory for a clean shutdown + */ + void close(); } diff --git a/src/main/java/org/java_websocket/WrappedByteChannel.java b/src/main/java/org/java_websocket/WrappedByteChannel.java index 06c2f0b4f..8dee57db0 100644 --- a/src/main/java/org/java_websocket/WrappedByteChannel.java +++ b/src/main/java/org/java_websocket/WrappedByteChannel.java @@ -30,39 +30,47 @@ import java.nio.channels.ByteChannel; public interface WrappedByteChannel extends ByteChannel { - /** - * returns whether writeMore should be called write additional data. - * @return is a additional write needed - */ - boolean isNeedWrite(); + /** + * returns whether writeMore should be called write additional data. + * + * @return is a additional write needed + */ + boolean isNeedWrite(); - /** - * Gets called when {@link #isNeedWrite()} ()} requires a additional rite - * @throws IOException may be thrown due to an error while writing - */ - void writeMore() throws IOException; + /** + * Gets called when {@link #isNeedWrite()} ()} requires a additional rite + * + * @throws IOException may be thrown due to an error while writing + */ + void writeMore() throws IOException; - /** - * returns whether readMore should be called to fetch data which has been decoded but not yet been returned. - * - * @see #read(ByteBuffer) - * @see #readMore(ByteBuffer) - * @return is a additional read needed - **/ - boolean isNeedRead(); - /** - * This function does not read data from the underlying channel at all. It is just a way to fetch data which has already be received or decoded but was but was not yet returned to the user. - * This could be the case when the decoded data did not fit into the buffer the user passed to {@link #read(ByteBuffer)}. - * @param dst the destiny of the read - * @return the amount of remaining data - * @throws IOException when a error occurred during unwrapping - **/ - int readMore( ByteBuffer dst ) throws IOException; + /** + * returns whether readMore should be called to fetch data which has been decoded but not yet been + * returned. + * + * @return is a additional read needed + * @see #read(ByteBuffer) + * @see #readMore(ByteBuffer) + **/ + boolean isNeedRead(); - /** - * This function returns the blocking state of the channel - * @return is the channel blocking - */ - boolean isBlocking(); + /** + * This function does not read data from the underlying channel at all. It is just a way to fetch + * data which has already be received or decoded but was but was not yet returned to the user. + * This could be the case when the decoded data did not fit into the buffer the user passed to + * {@link #read(ByteBuffer)}. + * + * @param dst the destiny of the read + * @return the amount of remaining data + * @throws IOException when a error occurred during unwrapping + **/ + int readMore(ByteBuffer dst) throws IOException; + + /** + * This function returns the blocking state of the channel + * + * @return is the channel blocking + */ + boolean isBlocking(); } diff --git a/src/main/java/org/java_websocket/client/DnsResolver.java b/src/main/java/org/java_websocket/client/DnsResolver.java index 77b1823d8..ec9f17f06 100644 --- a/src/main/java/org/java_websocket/client/DnsResolver.java +++ b/src/main/java/org/java_websocket/client/DnsResolver.java @@ -30,25 +30,22 @@ import java.net.UnknownHostException; /** - * Users may implement this interface to override the default DNS lookup offered - * by the OS. + * Users may implement this interface to override the default DNS lookup offered by the OS. * * @since 1.4.1 */ public interface DnsResolver { - /** - * Resolves the IP address for the given URI. - * - * This method should never return null. If it's not able to resolve the IP - * address then it should throw an UnknownHostException - * - * @param uri The URI to be resolved - * - * @return The resolved IP address - * - * @throws UnknownHostException if no IP address for the uri could be found. - */ - InetAddress resolve(URI uri) throws UnknownHostException; + /** + * Resolves the IP address for the given URI. + *

    + * This method should never return null. If it's not able to resolve the IP address then it should + * throw an UnknownHostException + * + * @param uri The URI to be resolved + * @return The resolved IP address + * @throws UnknownHostException if no IP address for the uri could be found. + */ + InetAddress resolve(URI uri) throws UnknownHostException; } diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index e75d33886..91288f080 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -62,866 +62,895 @@ import org.java_websocket.protocols.IProtocol; /** - * A subclass must implement at least onOpen, onClose, and onMessage to be - * useful. At runtime the user is expected to establish a connection via {@link #connect()}, then receive events like {@link #onMessage(String)} via the overloaded methods and to {@link #send(String)} data to the server. + * A subclass must implement at least onOpen, onClose, and + * onMessage to be useful. At runtime the user is expected to establish a connection via + * {@link #connect()}, then receive events like {@link #onMessage(String)} via the overloaded + * methods and to {@link #send(String)} data to the server. */ public abstract class WebSocketClient extends AbstractWebSocket implements Runnable, WebSocket { - /** - * The URI this channel is supposed to connect to. - */ - protected URI uri = null; - - /** - * The underlying engine - */ - private WebSocketImpl engine = null; - - /** - * The socket for this WebSocketClient - */ - private Socket socket = null; - - /** - * The SocketFactory for this WebSocketClient - * @since 1.4.0 - */ - private SocketFactory socketFactory = null; - - /** - * The used OutputStream - */ - private OutputStream ostream; - - /** - * The used proxy, if any - */ - private Proxy proxy = Proxy.NO_PROXY; - - /** - * The thread to write outgoing message - */ - private Thread writeThread; - - /** - * The thread to connect and read message - */ - private Thread connectReadThread; - - /** - * The draft to use - */ - private Draft draft; - - /** - * The additional headers to use - */ - private Map headers; - - /** - * The latch for connectBlocking() - */ - private CountDownLatch connectLatch = new CountDownLatch( 1 ); - - /** - * The latch for closeBlocking() - */ - private CountDownLatch closeLatch = new CountDownLatch( 1 ); - - /** - * The socket timeout value to be used in milliseconds. - */ - private int connectTimeout = 0; - - /** - * DNS resolver that translates a URI to an InetAddress - * - * @see InetAddress - * @since 1.4.1 - */ - private DnsResolver dnsResolver = null; - - /** - * Constructs a WebSocketClient instance and sets it to the connect to the - * specified URI. The channel does not attampt to connect automatically. The connection - * will be established once you call connect. - * - * @param serverUri the server URI to connect to - */ - public WebSocketClient( URI serverUri ) { - this( serverUri, new Draft_6455()); - } - - /** - * Constructs a WebSocketClient instance and sets it to the connect to the - * specified URI. The channel does not attampt to connect automatically. The connection - * will be established once you call connect. - * @param serverUri the server URI to connect to - * @param protocolDraft The draft which should be used for this connection - */ - public WebSocketClient( URI serverUri , Draft protocolDraft ) { - this( serverUri, protocolDraft, null, 0 ); - } - - /** - * Constructs a WebSocketClient instance and sets it to the connect to the - * specified URI. The channel does not attampt to connect automatically. The connection - * will be established once you call connect. - * @param serverUri the server URI to connect to - * @param httpHeaders Additional HTTP-Headers - * @since 1.3.8 - */ - public WebSocketClient( URI serverUri, Map httpHeaders) { - this(serverUri, new Draft_6455(), httpHeaders); - } - - /** - * Constructs a WebSocketClient instance and sets it to the connect to the - * specified URI. The channel does not attampt to connect automatically. The connection - * will be established once you call connect. - * @param serverUri the server URI to connect to - * @param protocolDraft The draft which should be used for this connection - * @param httpHeaders Additional HTTP-Headers - * @since 1.3.8 - */ - public WebSocketClient( URI serverUri , Draft protocolDraft , Map httpHeaders) { - this(serverUri, protocolDraft, httpHeaders, 0); - } - - /** - * Constructs a WebSocketClient instance and sets it to the connect to the - * specified URI. The channel does not attampt to connect automatically. The connection - * will be established once you call connect. - * @param serverUri the server URI to connect to - * @param protocolDraft The draft which should be used for this connection - * @param httpHeaders Additional HTTP-Headers - * @param connectTimeout The Timeout for the connection - */ - public WebSocketClient( URI serverUri , Draft protocolDraft , Map httpHeaders , int connectTimeout ) { - if( serverUri == null ) { - throw new IllegalArgumentException(); - } else if( protocolDraft == null ) { - throw new IllegalArgumentException( "null as draft is permitted for `WebSocketServer` only!" ); - } - this.uri = serverUri; - this.draft = protocolDraft; - this.dnsResolver = new DnsResolver() { - @Override - public InetAddress resolve(URI uri) throws UnknownHostException { - return InetAddress.getByName(uri.getHost()); - } - }; - if(httpHeaders != null) { - headers = new TreeMap(String.CASE_INSENSITIVE_ORDER); - headers.putAll(httpHeaders); - } - this.connectTimeout = connectTimeout; - setTcpNoDelay( false ); - setReuseAddr( false ); - this.engine = new WebSocketImpl( this, protocolDraft ); - } - - /** - * Returns the URI that this WebSocketClient is connected to. - * @return the URI connected to - */ - public URI getURI() { - return uri; - } - - /** - * Returns the protocol version this channel uses.
    - * For more infos see https://github.com/TooTallNate/Java-WebSocket/wiki/Drafts - * @return The draft used for this client - */ - public Draft getDraft() { - return draft; - } - - /** - * Returns the socket to allow Hostname Verification - * @return the socket used for this connection - */ - public Socket getSocket() { - return socket; - } - - /** - * @since 1.4.1 - * Adds an additional header to be sent in the handshake.
    - * If the connection is already made, adding headers has no effect, - * unless reconnect is called, which then a new handshake is sent.
    - * If a header with the same key already exists, it is overridden. - * @param key Name of the header to add. - * @param value Value of the header to add. - */ - public void addHeader(String key, String value){ - if(headers == null) - headers = new TreeMap(String.CASE_INSENSITIVE_ORDER); - headers.put(key, value); - } - - /** - * @since 1.4.1 - * Removes a header from the handshake to be sent, if header key exists.
    - * @param key Name of the header to remove. - * @return the previous value associated with key, or - * null if there was no mapping for key. - */ - public String removeHeader(String key) { - if(headers == null) - return null; - return headers.remove(key); - } - - /** - * @since 1.4.1 - * Clears all previously put headers. - */ - public void clearHeaders() { - headers = null; - } - - /** - * Sets a custom DNS resolver. - * - * @param dnsResolver The DnsResolver to use. - * - * @since 1.4.1 - */ - public void setDnsResolver(DnsResolver dnsResolver) { - this.dnsResolver = dnsResolver; - } - - /** - * Reinitiates the websocket connection. This method does not block. - * @since 1.3.8 - */ - public void reconnect() { - reset(); - connect(); - } - - /** - * Same as reconnect but blocks until the websocket reconnected or failed to do so.
    - * @return Returns whether it succeeded or not. - * @throws InterruptedException Thrown when the threads get interrupted - * @since 1.3.8 - */ - public boolean reconnectBlocking() throws InterruptedException { - reset(); - return connectBlocking(); - } - - /** - * Reset everything relevant to allow a reconnect - * @since 1.3.8 - */ - private void reset() { - Thread current = Thread.currentThread(); - if (current == writeThread || current == connectReadThread) { - throw new IllegalStateException("You cannot initialize a reconnect out of the websocket thread. Use reconnect in another thread to ensure a successful cleanup."); - } - try { - closeBlocking(); - if( writeThread != null ) { - this.writeThread.interrupt(); - this.writeThread = null; - } - if( connectReadThread != null ) { - this.connectReadThread.interrupt(); - this.connectReadThread = null; - } - this.draft.reset(); - if( this.socket != null ) { - this.socket.close(); - this.socket = null; - } - } catch ( Exception e ) { - onError( e ); - engine.closeConnection( CloseFrame.ABNORMAL_CLOSE, e.getMessage() ); - return; - } - connectLatch = new CountDownLatch( 1 ); - closeLatch = new CountDownLatch( 1 ); - this.engine = new WebSocketImpl( this, this.draft ); - } - - /** - * Initiates the websocket connection. This method does not block. - */ - public void connect() { - if( connectReadThread != null ) - throw new IllegalStateException( "WebSocketClient objects are not reuseable" ); - connectReadThread = new Thread( this ); - connectReadThread.setName( "WebSocketConnectReadThread-" + connectReadThread.getId() ); - connectReadThread.start(); - } - - /** - * Same as connect but blocks until the websocket connected or failed to do so.
    - * @return Returns whether it succeeded or not. - * @throws InterruptedException Thrown when the threads get interrupted - */ - public boolean connectBlocking() throws InterruptedException { - connect(); - connectLatch.await(); - return engine.isOpen(); - } - - /** - * Same as connect but blocks with a timeout until the websocket connected or failed to do so.
    - * @param timeout - * The connect timeout - * @param timeUnit - * The timeout time unit - * @return Returns whether it succeeded or not. - * @throws InterruptedException Thrown when the threads get interrupted - */ - public boolean connectBlocking(long timeout, TimeUnit timeUnit) throws InterruptedException { - connect(); - return connectLatch.await(timeout, timeUnit) && engine.isOpen(); - } - - /** - * Initiates the websocket close handshake. This method does not block
    - * In oder to make sure the connection is closed use closeBlocking - */ - public void close() { - if( writeThread != null ) { - engine.close( CloseFrame.NORMAL ); - } - } - /** - * Same as close but blocks until the websocket closed or failed to do so.
    - * @throws InterruptedException Thrown when the threads get interrupted - */ - public void closeBlocking() throws InterruptedException { - close(); - closeLatch.await(); - } - - /** - * Sends text to the connected websocket server. - * - * @param text - * The string which will be transmitted. - */ - public void send( String text ) { - engine.send( text ); - } - - /** - * Sends binary data to the connected webSocket server. - * - * @param data - * The byte-Array of data to send to the WebSocket server. - */ - public void send( byte[] data ) { - engine.send( data ); - } - - @Override - public T getAttachment() { - return engine.getAttachment(); - } - - @Override - public void setAttachment(T attachment) { - engine.setAttachment( attachment ); - } - - @Override - protected Collection getConnections() { - return Collections.singletonList((WebSocket ) engine ); - } - - @Override - public void sendPing() { - engine.sendPing( ); - } - - public void run() { - InputStream istream; - try { - boolean isNewSocket = false; - if (socketFactory != null) { - socket = socketFactory.createSocket(); - } else if( socket == null ) { - socket = new Socket( proxy ); - isNewSocket = true; - } else if( socket.isClosed() ) { - throw new IOException(); - } - - socket.setTcpNoDelay( isTcpNoDelay() ); - socket.setReuseAddress( isReuseAddr() ); - - if (!socket.isConnected()) { - InetSocketAddress addr = new InetSocketAddress(dnsResolver.resolve(uri), this.getPort()); - socket.connect(addr, connectTimeout); - } - - // if the socket is set by others we don't apply any TLS wrapper - if (isNewSocket && "wss".equals( uri.getScheme())) { - SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); - sslContext.init(null, null, null); - SSLSocketFactory factory = sslContext.getSocketFactory(); - socket = factory.createSocket(socket, uri.getHost(), getPort(), true); - } - - if (socket instanceof SSLSocket) { - SSLSocket sslSocket = (SSLSocket)socket; - SSLParameters sslParameters = sslSocket.getSSLParameters(); - onSetSSLParameters(sslParameters); - sslSocket.setSSLParameters(sslParameters); - } - - istream = socket.getInputStream(); - ostream = socket.getOutputStream(); - - sendHandshake(); - } catch ( /*IOException | SecurityException | UnresolvedAddressException | InvalidHandshakeException | ClosedByInterruptException | SocketTimeoutException */Exception e ) { - onWebsocketError( engine, e ); - engine.closeConnection( CloseFrame.NEVER_CONNECTED, e.getMessage() ); - return; - } catch (InternalError e) { - // https://bugs.openjdk.java.net/browse/JDK-8173620 - if (e.getCause() instanceof InvocationTargetException && e.getCause().getCause() instanceof IOException) { - IOException cause = (IOException) e.getCause().getCause(); - onWebsocketError(engine, cause); - engine.closeConnection(CloseFrame.NEVER_CONNECTED, cause.getMessage()); - return; - } - throw e; - } - - writeThread = new Thread( new WebsocketWriteThread(this) ); - writeThread.start(); - - byte[] rawbuffer = new byte[ WebSocketImpl.RCVBUF ]; - int readBytes; - - try { - while ( !isClosing() && !isClosed() && ( readBytes = istream.read( rawbuffer ) ) != -1 ) { - engine.decode( ByteBuffer.wrap( rawbuffer, 0, readBytes ) ); - } - engine.eot(); - } catch ( IOException e ) { - handleIOException(e); - } catch ( RuntimeException e ) { - // this catch case covers internal errors only and indicates a bug in this websocket implementation - onError( e ); - engine.closeConnection( CloseFrame.ABNORMAL_CLOSE, e.getMessage() ); - } - connectReadThread = null; - } - - /** - * Apply specific SSLParameters - * If you override this method make sure to always call super.onSetSSLParameters() to ensure the hostname validation is active - * - * @param sslParameters the SSLParameters which will be used for the SSLSocket - */ - protected void onSetSSLParameters(SSLParameters sslParameters) { - // If you run into problem on Android (NoSuchMethodException), check out the wiki https://github.com/TooTallNate/Java-WebSocket/wiki/No-such-method-error-setEndpointIdentificationAlgorithm - // Perform hostname validation - sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); - } - - /** - * Extract the specified port - * @return the specified port or the default port for the specific scheme - */ - private int getPort() { - int port = uri.getPort(); - String scheme = uri.getScheme(); - if( "wss".equals( scheme ) ) { - return port == -1 ? WebSocketImpl.DEFAULT_WSS_PORT : port; - } else if( "ws".equals( scheme ) ) { - return port == -1 ? WebSocketImpl.DEFAULT_PORT : port; - } else { - throw new IllegalArgumentException( "unknown scheme: " + scheme ); - } - } - - /** - * Create and send the handshake to the other endpoint - * @throws InvalidHandshakeException a invalid handshake was created - */ - private void sendHandshake() throws InvalidHandshakeException { - String path; - String part1 = uri.getRawPath(); - String part2 = uri.getRawQuery(); - if( part1 == null || part1.length() == 0 ) - path = "/"; - else - path = part1; - if( part2 != null ) - path += '?' + part2; - int port = getPort(); - String host = uri.getHost() + ( - (port != WebSocketImpl.DEFAULT_PORT && port != WebSocketImpl.DEFAULT_WSS_PORT) - ? ":" + port - : "" ); - - HandshakeImpl1Client handshake = new HandshakeImpl1Client(); - handshake.setResourceDescriptor( path ); - handshake.put( "Host", host ); - if( headers != null ) { - for( Map.Entry kv : headers.entrySet() ) { - handshake.put( kv.getKey(), kv.getValue() ); - } - } - engine.startHandshake( handshake ); - } - - /** - * This represents the state of the connection. - */ - public ReadyState getReadyState() { - return engine.getReadyState(); - } - - /** - * Calls subclass' implementation of onMessage. - */ - @Override - public final void onWebsocketMessage( WebSocket conn, String message ) { - onMessage( message ); - } - - @Override - public final void onWebsocketMessage( WebSocket conn, ByteBuffer blob ) { - onMessage( blob ); - } - - /** - * Calls subclass' implementation of onOpen. - */ - @Override - public final void onWebsocketOpen( WebSocket conn, Handshakedata handshake ) { - startConnectionLostTimer(); - onOpen( (ServerHandshake) handshake ); - connectLatch.countDown(); - } - - /** - * Calls subclass' implementation of onClose. - */ - @Override - public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) { - stopConnectionLostTimer(); - if( writeThread != null ) - writeThread.interrupt(); - onClose( code, reason, remote ); - connectLatch.countDown(); - closeLatch.countDown(); - } - - /** - * Calls subclass' implementation of onIOError. - */ - @Override - public final void onWebsocketError( WebSocket conn, Exception ex ) { - onError( ex ); - } - - @Override - public final void onWriteDemand( WebSocket conn ) { - // nothing to do - } - - @Override - public void onWebsocketCloseInitiated( WebSocket conn, int code, String reason ) { - onCloseInitiated( code, reason ); - } - - @Override - public void onWebsocketClosing( WebSocket conn, int code, String reason, boolean remote ) { - onClosing( code, reason, remote ); - } - - /** - * Send when this peer sends a close handshake - * - * @param code The codes can be looked up here: {@link CloseFrame} - * @param reason Additional information string - */ - public void onCloseInitiated( int code, String reason ) { - //To overwrite - } - - /** Called as soon as no further frames are accepted - * - * @param code The codes can be looked up here: {@link CloseFrame} - * @param reason Additional information string - * @param remote Returns whether or not the closing of the connection was initiated by the remote host. - */ - public void onClosing( int code, String reason, boolean remote ) { - //To overwrite - } - - /** - * Getter for the engine - * @return the engine - */ - public WebSocket getConnection() { - return engine; - } - - @Override - public InetSocketAddress getLocalSocketAddress( WebSocket conn ) { - if( socket != null ) - return (InetSocketAddress) socket.getLocalSocketAddress(); - return null; - } - - @Override - public InetSocketAddress getRemoteSocketAddress( WebSocket conn ) { - if( socket != null ) - return (InetSocketAddress) socket.getRemoteSocketAddress(); - return null; - } - - // ABSTRACT METHODS ///////////////////////////////////////////////////////// - - /** - * Called after an opening handshake has been performed and the given websocket is ready to be written on. - * @param handshakedata The handshake of the websocket instance - */ - public abstract void onOpen( ServerHandshake handshakedata ); - - /** - * Callback for string messages received from the remote host - * - * @see #onMessage(ByteBuffer) - * @param message The UTF-8 decoded message that was received. - **/ - public abstract void onMessage( String message ); - - /** - * Called after the websocket connection has been closed. - * - * @param code - * The codes can be looked up here: {@link CloseFrame} - * @param reason - * Additional information string - * @param remote - * Returns whether or not the closing of the connection was initiated by the remote host. - **/ - public abstract void onClose( int code, String reason, boolean remote ); - - /** - * Called when errors occurs. If an error causes the websocket connection to fail {@link #onClose(int, String, boolean)} will be called additionally.
    - * This method will be called primarily because of IO or protocol errors.
    - * If the given exception is an RuntimeException that probably means that you encountered a bug.
    - * - * @param ex The exception causing this error - **/ - public abstract void onError( Exception ex ); - - /** - * Callback for binary messages received from the remote host - * - * @see #onMessage(String) - * - * @param bytes - * The binary message that was received. - **/ - public void onMessage( ByteBuffer bytes ) { - //To overwrite - } - - - private class WebsocketWriteThread implements Runnable { - - private final WebSocketClient webSocketClient; - - WebsocketWriteThread(WebSocketClient webSocketClient) { - this.webSocketClient = webSocketClient; - } - - @Override - public void run() { - Thread.currentThread().setName( "WebSocketWriteThread-" + Thread.currentThread().getId() ); - try { - runWriteData(); - } catch ( IOException e ) { - handleIOException( e ); - } finally { - closeSocket(); - writeThread = null; - } - } - - /** - * Write the data into the outstream - * @throws IOException if write or flush did not work - */ - private void runWriteData() throws IOException { - try { - while( !Thread.interrupted() ) { - ByteBuffer buffer = engine.outQueue.take(); - ostream.write( buffer.array(), 0, buffer.limit() ); - ostream.flush(); - } - } catch ( InterruptedException e ) { - for (ByteBuffer buffer : engine.outQueue) { - ostream.write( buffer.array(), 0, buffer.limit() ); - ostream.flush(); - } - Thread.currentThread().interrupt(); - } - } - - /** - * Closing the socket - */ - private void closeSocket() { - try { - if( socket != null ) { - socket.close(); - } - } catch ( IOException ex ) { - onWebsocketError( webSocketClient, ex ); - } - } - } - - - - - /** - * Method to set a proxy for this connection - * @param proxy the proxy to use for this websocket client - */ - public void setProxy( Proxy proxy ) { - if( proxy == null ) - throw new IllegalArgumentException(); - this.proxy = proxy; - } - - /** - * Accepts bound and unbound sockets.
    - * This method must be called before connect. - * If the given socket is not yet bound it will be bound to the uri specified in the constructor. - * @param socket The socket which should be used for the connection - * @deprecated use setSocketFactory - */ - @Deprecated - public void setSocket( Socket socket ) { - if( this.socket != null ) { - throw new IllegalStateException( "socket has already been set" ); - } - this.socket = socket; - } - - /** - * Accepts a SocketFactory.
    - * This method must be called before connect. - * The socket will be bound to the uri specified in the constructor. - * @param socketFactory The socket factory which should be used for the connection. - */ - public void setSocketFactory(SocketFactory socketFactory) { - this.socketFactory = socketFactory; - } - - @Override - public void sendFragmentedFrame(Opcode op, ByteBuffer buffer, boolean fin ) { - engine.sendFragmentedFrame( op, buffer, fin ); - } - - @Override - public boolean isOpen() { - return engine.isOpen(); - } - - @Override - public boolean isFlushAndClose() { - return engine.isFlushAndClose(); - } - - @Override - public boolean isClosed() { - return engine.isClosed(); - } - - @Override - public boolean isClosing() { - return engine.isClosing(); - } - - @Override - public boolean hasBufferedData() { - return engine.hasBufferedData(); - } - - @Override - public void close( int code ) { - engine.close( code ); - } - - @Override - public void close( int code, String message ) { - engine.close( code, message ); - } - - @Override - public void closeConnection( int code, String message ) { - engine.closeConnection( code, message ); - } - - @Override - public void send( ByteBuffer bytes ) { - engine.send( bytes ); - } - - @Override - public void sendFrame( Framedata framedata ) { - engine.sendFrame( framedata ); - } - - @Override - public void sendFrame( Collection frames ) { - engine.sendFrame( frames ); - } - - @Override - public InetSocketAddress getLocalSocketAddress() { - return engine.getLocalSocketAddress(); - } - @Override - public InetSocketAddress getRemoteSocketAddress() { - return engine.getRemoteSocketAddress(); - } - - @Override - public String getResourceDescriptor() { - return uri.getPath(); - } - - @Override - public boolean hasSSLSupport() { - return engine.hasSSLSupport(); - } - - @Override - public SSLSession getSSLSession() { - return engine.getSSLSession(); - } - - @Override - public IProtocol getProtocol() { return engine.getProtocol();} - - /** - * Method to give some additional info for specific IOExceptions - * @param e the IOException causing a eot. - */ - private void handleIOException( IOException e ) { - if (e instanceof SSLException) { - onError( e ); - } - engine.eot(); - } + /** + * The URI this channel is supposed to connect to. + */ + protected URI uri = null; + + /** + * The underlying engine + */ + private WebSocketImpl engine = null; + + /** + * The socket for this WebSocketClient + */ + private Socket socket = null; + + /** + * The SocketFactory for this WebSocketClient + * + * @since 1.4.0 + */ + private SocketFactory socketFactory = null; + + /** + * The used OutputStream + */ + private OutputStream ostream; + + /** + * The used proxy, if any + */ + private Proxy proxy = Proxy.NO_PROXY; + + /** + * The thread to write outgoing message + */ + private Thread writeThread; + + /** + * The thread to connect and read message + */ + private Thread connectReadThread; + + /** + * The draft to use + */ + private Draft draft; + + /** + * The additional headers to use + */ + private Map headers; + + /** + * The latch for connectBlocking() + */ + private CountDownLatch connectLatch = new CountDownLatch(1); + + /** + * The latch for closeBlocking() + */ + private CountDownLatch closeLatch = new CountDownLatch(1); + + /** + * The socket timeout value to be used in milliseconds. + */ + private int connectTimeout = 0; + + /** + * DNS resolver that translates a URI to an InetAddress + * + * @see InetAddress + * @since 1.4.1 + */ + private DnsResolver dnsResolver = null; + + /** + * Constructs a WebSocketClient instance and sets it to the connect to the specified URI. The + * channel does not attampt to connect automatically. The connection will be established once you + * call connect. + * + * @param serverUri the server URI to connect to + */ + public WebSocketClient(URI serverUri) { + this(serverUri, new Draft_6455()); + } + + /** + * Constructs a WebSocketClient instance and sets it to the connect to the specified URI. The + * channel does not attampt to connect automatically. The connection will be established once you + * call connect. + * + * @param serverUri the server URI to connect to + * @param protocolDraft The draft which should be used for this connection + */ + public WebSocketClient(URI serverUri, Draft protocolDraft) { + this(serverUri, protocolDraft, null, 0); + } + + /** + * Constructs a WebSocketClient instance and sets it to the connect to the specified URI. The + * channel does not attampt to connect automatically. The connection will be established once you + * call connect. + * + * @param serverUri the server URI to connect to + * @param httpHeaders Additional HTTP-Headers + * @since 1.3.8 + */ + public WebSocketClient(URI serverUri, Map httpHeaders) { + this(serverUri, new Draft_6455(), httpHeaders); + } + + /** + * Constructs a WebSocketClient instance and sets it to the connect to the specified URI. The + * channel does not attampt to connect automatically. The connection will be established once you + * call connect. + * + * @param serverUri the server URI to connect to + * @param protocolDraft The draft which should be used for this connection + * @param httpHeaders Additional HTTP-Headers + * @since 1.3.8 + */ + public WebSocketClient(URI serverUri, Draft protocolDraft, Map httpHeaders) { + this(serverUri, protocolDraft, httpHeaders, 0); + } + + /** + * Constructs a WebSocketClient instance and sets it to the connect to the specified URI. The + * channel does not attampt to connect automatically. The connection will be established once you + * call connect. + * + * @param serverUri the server URI to connect to + * @param protocolDraft The draft which should be used for this connection + * @param httpHeaders Additional HTTP-Headers + * @param connectTimeout The Timeout for the connection + */ + public WebSocketClient(URI serverUri, Draft protocolDraft, Map httpHeaders, + int connectTimeout) { + if (serverUri == null) { + throw new IllegalArgumentException(); + } else if (protocolDraft == null) { + throw new IllegalArgumentException("null as draft is permitted for `WebSocketServer` only!"); + } + this.uri = serverUri; + this.draft = protocolDraft; + this.dnsResolver = new DnsResolver() { + @Override + public InetAddress resolve(URI uri) throws UnknownHostException { + return InetAddress.getByName(uri.getHost()); + } + }; + if (httpHeaders != null) { + headers = new TreeMap(String.CASE_INSENSITIVE_ORDER); + headers.putAll(httpHeaders); + } + this.connectTimeout = connectTimeout; + setTcpNoDelay(false); + setReuseAddr(false); + this.engine = new WebSocketImpl(this, protocolDraft); + } + + /** + * Returns the URI that this WebSocketClient is connected to. + * + * @return the URI connected to + */ + public URI getURI() { + return uri; + } + + /** + * Returns the protocol version this channel uses.
    For more infos see + * https://github.com/TooTallNate/Java-WebSocket/wiki/Drafts + * + * @return The draft used for this client + */ + public Draft getDraft() { + return draft; + } + + /** + * Returns the socket to allow Hostname Verification + * + * @return the socket used for this connection + */ + public Socket getSocket() { + return socket; + } + + /** + * @param key Name of the header to add. + * @param value Value of the header to add. + * @since 1.4.1 Adds an additional header to be sent in the handshake.
    If the connection is + * already made, adding headers has no effect, unless reconnect is called, which then a new + * handshake is sent.
    If a header with the same key already exists, it is overridden. + */ + public void addHeader(String key, String value) { + if (headers == null) { + headers = new TreeMap(String.CASE_INSENSITIVE_ORDER); + } + headers.put(key, value); + } + + /** + * @param key Name of the header to remove. + * @return the previous value associated with key, or null if there was no mapping for key. + * @since 1.4.1 Removes a header from the handshake to be sent, if header key exists.
    + */ + public String removeHeader(String key) { + if (headers == null) { + return null; + } + return headers.remove(key); + } + + /** + * @since 1.4.1 Clears all previously put headers. + */ + public void clearHeaders() { + headers = null; + } + + /** + * Sets a custom DNS resolver. + * + * @param dnsResolver The DnsResolver to use. + * @since 1.4.1 + */ + public void setDnsResolver(DnsResolver dnsResolver) { + this.dnsResolver = dnsResolver; + } + + /** + * Reinitiates the websocket connection. This method does not block. + * + * @since 1.3.8 + */ + public void reconnect() { + reset(); + connect(); + } + + /** + * Same as reconnect but blocks until the websocket reconnected or failed to do + * so.
    + * + * @return Returns whether it succeeded or not. + * @throws InterruptedException Thrown when the threads get interrupted + * @since 1.3.8 + */ + public boolean reconnectBlocking() throws InterruptedException { + reset(); + return connectBlocking(); + } + + /** + * Reset everything relevant to allow a reconnect + * + * @since 1.3.8 + */ + private void reset() { + Thread current = Thread.currentThread(); + if (current == writeThread || current == connectReadThread) { + throw new IllegalStateException( + "You cannot initialize a reconnect out of the websocket thread. Use reconnect in another thread to ensure a successful cleanup."); + } + try { + closeBlocking(); + if (writeThread != null) { + this.writeThread.interrupt(); + this.writeThread = null; + } + if (connectReadThread != null) { + this.connectReadThread.interrupt(); + this.connectReadThread = null; + } + this.draft.reset(); + if (this.socket != null) { + this.socket.close(); + this.socket = null; + } + } catch (Exception e) { + onError(e); + engine.closeConnection(CloseFrame.ABNORMAL_CLOSE, e.getMessage()); + return; + } + connectLatch = new CountDownLatch(1); + closeLatch = new CountDownLatch(1); + this.engine = new WebSocketImpl(this, this.draft); + } + + /** + * Initiates the websocket connection. This method does not block. + */ + public void connect() { + if (connectReadThread != null) { + throw new IllegalStateException("WebSocketClient objects are not reuseable"); + } + connectReadThread = new Thread(this); + connectReadThread.setName("WebSocketConnectReadThread-" + connectReadThread.getId()); + connectReadThread.start(); + } + + /** + * Same as connect but blocks until the websocket connected or failed to do so.
    + * + * @return Returns whether it succeeded or not. + * @throws InterruptedException Thrown when the threads get interrupted + */ + public boolean connectBlocking() throws InterruptedException { + connect(); + connectLatch.await(); + return engine.isOpen(); + } + + /** + * Same as connect but blocks with a timeout until the websocket connected or failed + * to do so.
    + * + * @param timeout The connect timeout + * @param timeUnit The timeout time unit + * @return Returns whether it succeeded or not. + * @throws InterruptedException Thrown when the threads get interrupted + */ + public boolean connectBlocking(long timeout, TimeUnit timeUnit) throws InterruptedException { + connect(); + return connectLatch.await(timeout, timeUnit) && engine.isOpen(); + } + + /** + * Initiates the websocket close handshake. This method does not block
    In oder to make sure + * the connection is closed use closeBlocking + */ + public void close() { + if (writeThread != null) { + engine.close(CloseFrame.NORMAL); + } + } + + /** + * Same as close but blocks until the websocket closed or failed to do so.
    + * + * @throws InterruptedException Thrown when the threads get interrupted + */ + public void closeBlocking() throws InterruptedException { + close(); + closeLatch.await(); + } + + /** + * Sends text to the connected websocket server. + * + * @param text The string which will be transmitted. + */ + public void send(String text) { + engine.send(text); + } + + /** + * Sends binary data to the connected webSocket server. + * + * @param data The byte-Array of data to send to the WebSocket server. + */ + public void send(byte[] data) { + engine.send(data); + } + + @Override + public T getAttachment() { + return engine.getAttachment(); + } + + @Override + public void setAttachment(T attachment) { + engine.setAttachment(attachment); + } + + @Override + protected Collection getConnections() { + return Collections.singletonList((WebSocket) engine); + } + + @Override + public void sendPing() { + engine.sendPing(); + } + + public void run() { + InputStream istream; + try { + boolean isNewSocket = false; + if (socketFactory != null) { + socket = socketFactory.createSocket(); + } else if (socket == null) { + socket = new Socket(proxy); + isNewSocket = true; + } else if (socket.isClosed()) { + throw new IOException(); + } + + socket.setTcpNoDelay(isTcpNoDelay()); + socket.setReuseAddress(isReuseAddr()); + + if (!socket.isConnected()) { + InetSocketAddress addr = new InetSocketAddress(dnsResolver.resolve(uri), this.getPort()); + socket.connect(addr, connectTimeout); + } + + // if the socket is set by others we don't apply any TLS wrapper + if (isNewSocket && "wss".equals(uri.getScheme())) { + SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); + sslContext.init(null, null, null); + SSLSocketFactory factory = sslContext.getSocketFactory(); + socket = factory.createSocket(socket, uri.getHost(), getPort(), true); + } + + if (socket instanceof SSLSocket) { + SSLSocket sslSocket = (SSLSocket) socket; + SSLParameters sslParameters = sslSocket.getSSLParameters(); + onSetSSLParameters(sslParameters); + sslSocket.setSSLParameters(sslParameters); + } + + istream = socket.getInputStream(); + ostream = socket.getOutputStream(); + + sendHandshake(); + } catch ( /*IOException | SecurityException | UnresolvedAddressException | InvalidHandshakeException | ClosedByInterruptException | SocketTimeoutException */Exception e) { + onWebsocketError(engine, e); + engine.closeConnection(CloseFrame.NEVER_CONNECTED, e.getMessage()); + return; + } catch (InternalError e) { + // https://bugs.openjdk.java.net/browse/JDK-8173620 + if (e.getCause() instanceof InvocationTargetException && e.getCause() + .getCause() instanceof IOException) { + IOException cause = (IOException) e.getCause().getCause(); + onWebsocketError(engine, cause); + engine.closeConnection(CloseFrame.NEVER_CONNECTED, cause.getMessage()); + return; + } + throw e; + } + + writeThread = new Thread(new WebsocketWriteThread(this)); + writeThread.start(); + + byte[] rawbuffer = new byte[WebSocketImpl.RCVBUF]; + int readBytes; + + try { + while (!isClosing() && !isClosed() && (readBytes = istream.read(rawbuffer)) != -1) { + engine.decode(ByteBuffer.wrap(rawbuffer, 0, readBytes)); + } + engine.eot(); + } catch (IOException e) { + handleIOException(e); + } catch (RuntimeException e) { + // this catch case covers internal errors only and indicates a bug in this websocket implementation + onError(e); + engine.closeConnection(CloseFrame.ABNORMAL_CLOSE, e.getMessage()); + } + connectReadThread = null; + } + + /** + * Apply specific SSLParameters If you override this method make sure to always call + * super.onSetSSLParameters() to ensure the hostname validation is active + * + * @param sslParameters the SSLParameters which will be used for the SSLSocket + */ + protected void onSetSSLParameters(SSLParameters sslParameters) { + // If you run into problem on Android (NoSuchMethodException), check out the wiki https://github.com/TooTallNate/Java-WebSocket/wiki/No-such-method-error-setEndpointIdentificationAlgorithm + // Perform hostname validation + sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); + } + + /** + * Extract the specified port + * + * @return the specified port or the default port for the specific scheme + */ + private int getPort() { + int port = uri.getPort(); + String scheme = uri.getScheme(); + if ("wss".equals(scheme)) { + return port == -1 ? WebSocketImpl.DEFAULT_WSS_PORT : port; + } else if ("ws".equals(scheme)) { + return port == -1 ? WebSocketImpl.DEFAULT_PORT : port; + } else { + throw new IllegalArgumentException("unknown scheme: " + scheme); + } + } + + /** + * Create and send the handshake to the other endpoint + * + * @throws InvalidHandshakeException a invalid handshake was created + */ + private void sendHandshake() throws InvalidHandshakeException { + String path; + String part1 = uri.getRawPath(); + String part2 = uri.getRawQuery(); + if (part1 == null || part1.length() == 0) { + path = "/"; + } else { + path = part1; + } + if (part2 != null) { + path += '?' + part2; + } + int port = getPort(); + String host = uri.getHost() + ( + (port != WebSocketImpl.DEFAULT_PORT && port != WebSocketImpl.DEFAULT_WSS_PORT) + ? ":" + port + : ""); + + HandshakeImpl1Client handshake = new HandshakeImpl1Client(); + handshake.setResourceDescriptor(path); + handshake.put("Host", host); + if (headers != null) { + for (Map.Entry kv : headers.entrySet()) { + handshake.put(kv.getKey(), kv.getValue()); + } + } + engine.startHandshake(handshake); + } + + /** + * This represents the state of the connection. + */ + public ReadyState getReadyState() { + return engine.getReadyState(); + } + + /** + * Calls subclass' implementation of onMessage. + */ + @Override + public final void onWebsocketMessage(WebSocket conn, String message) { + onMessage(message); + } + + @Override + public final void onWebsocketMessage(WebSocket conn, ByteBuffer blob) { + onMessage(blob); + } + + /** + * Calls subclass' implementation of onOpen. + */ + @Override + public final void onWebsocketOpen(WebSocket conn, Handshakedata handshake) { + startConnectionLostTimer(); + onOpen((ServerHandshake) handshake); + connectLatch.countDown(); + } + + /** + * Calls subclass' implementation of onClose. + */ + @Override + public final void onWebsocketClose(WebSocket conn, int code, String reason, boolean remote) { + stopConnectionLostTimer(); + if (writeThread != null) { + writeThread.interrupt(); + } + onClose(code, reason, remote); + connectLatch.countDown(); + closeLatch.countDown(); + } + + /** + * Calls subclass' implementation of onIOError. + */ + @Override + public final void onWebsocketError(WebSocket conn, Exception ex) { + onError(ex); + } + + @Override + public final void onWriteDemand(WebSocket conn) { + // nothing to do + } + + @Override + public void onWebsocketCloseInitiated(WebSocket conn, int code, String reason) { + onCloseInitiated(code, reason); + } + + @Override + public void onWebsocketClosing(WebSocket conn, int code, String reason, boolean remote) { + onClosing(code, reason, remote); + } + + /** + * Send when this peer sends a close handshake + * + * @param code The codes can be looked up here: {@link CloseFrame} + * @param reason Additional information string + */ + public void onCloseInitiated(int code, String reason) { + //To overwrite + } + + /** + * Called as soon as no further frames are accepted + * + * @param code The codes can be looked up here: {@link CloseFrame} + * @param reason Additional information string + * @param remote Returns whether or not the closing of the connection was initiated by the remote + * host. + */ + public void onClosing(int code, String reason, boolean remote) { + //To overwrite + } + + /** + * Getter for the engine + * + * @return the engine + */ + public WebSocket getConnection() { + return engine; + } + + @Override + public InetSocketAddress getLocalSocketAddress(WebSocket conn) { + if (socket != null) { + return (InetSocketAddress) socket.getLocalSocketAddress(); + } + return null; + } + + @Override + public InetSocketAddress getRemoteSocketAddress(WebSocket conn) { + if (socket != null) { + return (InetSocketAddress) socket.getRemoteSocketAddress(); + } + return null; + } + + // ABSTRACT METHODS ///////////////////////////////////////////////////////// + + /** + * Called after an opening handshake has been performed and the given websocket is ready to be + * written on. + * + * @param handshakedata The handshake of the websocket instance + */ + public abstract void onOpen(ServerHandshake handshakedata); + + /** + * Callback for string messages received from the remote host + * + * @param message The UTF-8 decoded message that was received. + * @see #onMessage(ByteBuffer) + **/ + public abstract void onMessage(String message); + + /** + * Called after the websocket connection has been closed. + * + * @param code The codes can be looked up here: {@link CloseFrame} + * @param reason Additional information string + * @param remote Returns whether or not the closing of the connection was initiated by the remote + * host. + **/ + public abstract void onClose(int code, String reason, boolean remote); + + /** + * Called when errors occurs. If an error causes the websocket connection to fail {@link + * #onClose(int, String, boolean)} will be called additionally.
    This method will be called + * primarily because of IO or protocol errors.
    If the given exception is an RuntimeException + * that probably means that you encountered a bug.
    + * + * @param ex The exception causing this error + **/ + public abstract void onError(Exception ex); + + /** + * Callback for binary messages received from the remote host + * + * @param bytes The binary message that was received. + * @see #onMessage(String) + **/ + public void onMessage(ByteBuffer bytes) { + //To overwrite + } + + + private class WebsocketWriteThread implements Runnable { + + private final WebSocketClient webSocketClient; + + WebsocketWriteThread(WebSocketClient webSocketClient) { + this.webSocketClient = webSocketClient; + } + + @Override + public void run() { + Thread.currentThread().setName("WebSocketWriteThread-" + Thread.currentThread().getId()); + try { + runWriteData(); + } catch (IOException e) { + handleIOException(e); + } finally { + closeSocket(); + writeThread = null; + } + } + + /** + * Write the data into the outstream + * + * @throws IOException if write or flush did not work + */ + private void runWriteData() throws IOException { + try { + while (!Thread.interrupted()) { + ByteBuffer buffer = engine.outQueue.take(); + ostream.write(buffer.array(), 0, buffer.limit()); + ostream.flush(); + } + } catch (InterruptedException e) { + for (ByteBuffer buffer : engine.outQueue) { + ostream.write(buffer.array(), 0, buffer.limit()); + ostream.flush(); + } + Thread.currentThread().interrupt(); + } + } + + /** + * Closing the socket + */ + private void closeSocket() { + try { + if (socket != null) { + socket.close(); + } + } catch (IOException ex) { + onWebsocketError(webSocketClient, ex); + } + } + } + + + /** + * Method to set a proxy for this connection + * + * @param proxy the proxy to use for this websocket client + */ + public void setProxy(Proxy proxy) { + if (proxy == null) { + throw new IllegalArgumentException(); + } + this.proxy = proxy; + } + + /** + * Accepts bound and unbound sockets.
    This method must be called before connect. + * If the given socket is not yet bound it will be bound to the uri specified in the constructor. + * + * @param socket The socket which should be used for the connection + * @deprecated use setSocketFactory + */ + @Deprecated + public void setSocket(Socket socket) { + if (this.socket != null) { + throw new IllegalStateException("socket has already been set"); + } + this.socket = socket; + } + + /** + * Accepts a SocketFactory.
    This method must be called before connect. The socket + * will be bound to the uri specified in the constructor. + * + * @param socketFactory The socket factory which should be used for the connection. + */ + public void setSocketFactory(SocketFactory socketFactory) { + this.socketFactory = socketFactory; + } + + @Override + public void sendFragmentedFrame(Opcode op, ByteBuffer buffer, boolean fin) { + engine.sendFragmentedFrame(op, buffer, fin); + } + + @Override + public boolean isOpen() { + return engine.isOpen(); + } + + @Override + public boolean isFlushAndClose() { + return engine.isFlushAndClose(); + } + + @Override + public boolean isClosed() { + return engine.isClosed(); + } + + @Override + public boolean isClosing() { + return engine.isClosing(); + } + + @Override + public boolean hasBufferedData() { + return engine.hasBufferedData(); + } + + @Override + public void close(int code) { + engine.close(code); + } + + @Override + public void close(int code, String message) { + engine.close(code, message); + } + + @Override + public void closeConnection(int code, String message) { + engine.closeConnection(code, message); + } + + @Override + public void send(ByteBuffer bytes) { + engine.send(bytes); + } + + @Override + public void sendFrame(Framedata framedata) { + engine.sendFrame(framedata); + } + + @Override + public void sendFrame(Collection frames) { + engine.sendFrame(frames); + } + + @Override + public InetSocketAddress getLocalSocketAddress() { + return engine.getLocalSocketAddress(); + } + + @Override + public InetSocketAddress getRemoteSocketAddress() { + return engine.getRemoteSocketAddress(); + } + + @Override + public String getResourceDescriptor() { + return uri.getPath(); + } + + @Override + public boolean hasSSLSupport() { + return engine.hasSSLSupport(); + } + + @Override + public SSLSession getSSLSession() { + return engine.getSSLSession(); + } + + @Override + public IProtocol getProtocol() { + return engine.getProtocol(); + } + + /** + * Method to give some additional info for specific IOExceptions + * + * @param e the IOException causing a eot. + */ + private void handleIOException(IOException e) { + if (e instanceof SSLException) { + onError(e); + } + engine.eot(); + } } diff --git a/src/main/java/org/java_websocket/drafts/Draft.java b/src/main/java/org/java_websocket/drafts/Draft.java index 3fb040c9b..68cc49c69 100644 --- a/src/main/java/org/java_websocket/drafts/Draft.java +++ b/src/main/java/org/java_websocket/drafts/Draft.java @@ -51,270 +51,301 @@ import org.java_websocket.util.Charsetfunctions; /** - * Base class for everything of a websocket specification which is not common such as the way the handshake is read or frames are transferred. + * Base class for everything of a websocket specification which is not common such as the way the + * handshake is read or frames are transferred. **/ public abstract class Draft { - /** In some cases the handshake will be parsed different depending on whether */ - protected Role role = null; - - protected Opcode continuousFrameType = null; - - public static ByteBuffer readLine( ByteBuffer buf ) { - ByteBuffer sbuf = ByteBuffer.allocate( buf.remaining() ); - byte prev; - byte cur = '0'; - while ( buf.hasRemaining() ) { - prev = cur; - cur = buf.get(); - sbuf.put( cur ); - if( prev == (byte) '\r' && cur == (byte) '\n' ) { - sbuf.limit( sbuf.position() - 2 ); - sbuf.position( 0 ); - return sbuf; - - } - } - // ensure that there wont be any bytes skipped - buf.position( buf.position() - sbuf.position() ); - return null; - } - - public static String readStringLine( ByteBuffer buf ) { - ByteBuffer b = readLine( buf ); - return b == null ? null : Charsetfunctions.stringAscii( b.array(), 0, b.limit() ); - } - - public static HandshakeBuilder translateHandshakeHttp( ByteBuffer buf, Role role ) throws InvalidHandshakeException { - HandshakeBuilder handshake; - - String line = readStringLine( buf ); - if( line == null ) - throw new IncompleteHandshakeException( buf.capacity() + 128 ); - - String[] firstLineTokens = line.split( " ", 3 );// eg. HTTP/1.1 101 Switching the Protocols - if( firstLineTokens.length != 3 ) { - throw new InvalidHandshakeException(); - } - if( role == Role.CLIENT ) { - handshake = translateHandshakeHttpClient(firstLineTokens, line); - } else { - handshake = translateHandshakeHttpServer(firstLineTokens, line); - } - line = readStringLine( buf ); - while ( line != null && line.length() > 0 ) { - String[] pair = line.split( ":", 2 ); - if( pair.length != 2 ) - throw new InvalidHandshakeException( "not an http header" ); - // If the handshake contains already a specific key, append the new value - if ( handshake.hasFieldValue( pair[ 0 ] ) ) { - handshake.put( pair[0], handshake.getFieldValue( pair[ 0 ] ) + "; " + pair[1].replaceFirst( "^ +", "" ) ); - } else { - handshake.put( pair[0], pair[1].replaceFirst( "^ +", "" ) ); - } - line = readStringLine( buf ); - } - if( line == null ) - throw new IncompleteHandshakeException(); - return handshake; - } - - /** - * Checking the handshake for the role as server - * @return a handshake - * @param firstLineTokens the token of the first line split as as an string array - * @param line the whole line - */ - private static HandshakeBuilder translateHandshakeHttpServer(String[] firstLineTokens, String line) throws InvalidHandshakeException { - // translating/parsing the request from the CLIENT - if (!"GET".equalsIgnoreCase(firstLineTokens[0])) { - throw new InvalidHandshakeException( String.format("Invalid request method received: %s Status line: %s", firstLineTokens[0],line)); - } - if (!"HTTP/1.1".equalsIgnoreCase(firstLineTokens[2])) { - throw new InvalidHandshakeException( String.format("Invalid status line received: %s Status line: %s", firstLineTokens[2], line)); - } - ClientHandshakeBuilder clienthandshake = new HandshakeImpl1Client(); - clienthandshake.setResourceDescriptor( firstLineTokens[ 1 ] ); - return clienthandshake; - } - - /** - * Checking the handshake for the role as client - * @return a handshake - * @param firstLineTokens the token of the first line split as as an string array - * @param line the whole line - */ - private static HandshakeBuilder translateHandshakeHttpClient(String[] firstLineTokens, String line) throws InvalidHandshakeException { - // translating/parsing the response from the SERVER - if (!"101".equals(firstLineTokens[1])) { - throw new InvalidHandshakeException( String.format("Invalid status code received: %s Status line: %s", firstLineTokens[1], line)); - } - if (!"HTTP/1.1".equalsIgnoreCase(firstLineTokens[0])) { - throw new InvalidHandshakeException( String.format("Invalid status line received: %s Status line: %s", firstLineTokens[0], line)); - } - HandshakeBuilder handshake = new HandshakeImpl1Server(); - ServerHandshakeBuilder serverhandshake = (ServerHandshakeBuilder) handshake; - serverhandshake.setHttpStatus( Short.parseShort( firstLineTokens[ 1 ] ) ); - serverhandshake.setHttpStatusMessage( firstLineTokens[ 2 ] ); - return handshake; - } - - public abstract HandshakeState acceptHandshakeAsClient( ClientHandshake request, ServerHandshake response ) throws InvalidHandshakeException; - - public abstract HandshakeState acceptHandshakeAsServer(ClientHandshake handshakedata ) throws InvalidHandshakeException; - - protected boolean basicAccept( Handshakedata handshakedata ) { - return handshakedata.getFieldValue( "Upgrade" ).equalsIgnoreCase( "websocket" ) && handshakedata.getFieldValue( "Connection" ).toLowerCase( Locale.ENGLISH ).contains( "upgrade" ); - } - - public abstract ByteBuffer createBinaryFrame( Framedata framedata ); - - public abstract List createFrames( ByteBuffer binary, boolean mask ); - - public abstract List createFrames( String text, boolean mask ); - - - /** - * Handle the frame specific to the draft - * @param webSocketImpl the websocketimpl used for this draft - * @param frame the frame which is supposed to be handled - * @throws InvalidDataException will be thrown on invalid data - */ - public abstract void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws InvalidDataException; - - public List continuousFrame(Opcode op, ByteBuffer buffer, boolean fin ) { - if(op != Opcode.BINARY && op != Opcode.TEXT) { - throw new IllegalArgumentException( "Only Opcode.BINARY or Opcode.TEXT are allowed" ); - } - DataFrame bui = null; - if( continuousFrameType != null ) { - bui = new ContinuousFrame(); - } else { - continuousFrameType = op; - if (op == Opcode.BINARY) { - bui = new BinaryFrame(); - } else if (op == Opcode.TEXT) { - bui = new TextFrame(); - } - } - bui.setPayload( buffer ); - bui.setFin( fin ); - try { - bui.isValid(); - } catch ( InvalidDataException e ) { - throw new IllegalArgumentException( e ); // can only happen when one builds close frames(Opcode.Close) - } - if( fin ) { - continuousFrameType = null; - } else { - continuousFrameType = op; - } - return Collections.singletonList( (Framedata) bui ); - } - - public abstract void reset(); - - /** - * @deprecated use createHandshake without the role - */ - @Deprecated - public List createHandshake( Handshakedata handshakedata, Role ownrole ) { - return createHandshake(handshakedata); - } - - public List createHandshake( Handshakedata handshakedata) { - return createHandshake( handshakedata, true ); - } - - /** - * @deprecated use createHandshake without the role since it does not have any effect - */ - @Deprecated - public List createHandshake( Handshakedata handshakedata, Role ownrole, boolean withcontent ) { - return createHandshake(handshakedata, withcontent); - } - - public List createHandshake( Handshakedata handshakedata, boolean withcontent ) { - StringBuilder bui = new StringBuilder( 100 ); - if( handshakedata instanceof ClientHandshake ) { - bui.append( "GET " ).append( ( (ClientHandshake) handshakedata ).getResourceDescriptor() ).append( " HTTP/1.1" ); - } else if( handshakedata instanceof ServerHandshake ) { - bui.append("HTTP/1.1 101 ").append(((ServerHandshake) handshakedata).getHttpStatusMessage()); - } else { - throw new IllegalArgumentException( "unknown role" ); - } - bui.append( "\r\n" ); - Iterator it = handshakedata.iterateHttpFields(); - while ( it.hasNext() ) { - String fieldname = it.next(); - String fieldvalue = handshakedata.getFieldValue( fieldname ); - bui.append( fieldname ); - bui.append( ": " ); - bui.append( fieldvalue ); - bui.append( "\r\n" ); - } - bui.append( "\r\n" ); - byte[] httpheader = Charsetfunctions.asciiBytes( bui.toString() ); - - byte[] content = withcontent ? handshakedata.getContent() : null; - ByteBuffer bytebuffer = ByteBuffer.allocate( ( content == null ? 0 : content.length ) + httpheader.length ); - bytebuffer.put( httpheader ); - if( content != null ) { - bytebuffer.put(content); - } - bytebuffer.flip(); - return Collections.singletonList( bytebuffer ); - } - - public abstract ClientHandshakeBuilder postProcessHandshakeRequestAsClient( ClientHandshakeBuilder request ) throws InvalidHandshakeException; - - public abstract HandshakeBuilder postProcessHandshakeResponseAsServer( ClientHandshake request, ServerHandshakeBuilder response ) throws InvalidHandshakeException; - - public abstract List translateFrame( ByteBuffer buffer ) throws InvalidDataException; - - public abstract CloseHandshakeType getCloseHandshakeType(); - - /** - * Drafts must only be by one websocket at all. To prevent drafts to be used more than once the Websocket implementation should call this method in order to create a new usable version of a given draft instance.
    - * The copy can be safely used in conjunction with a new websocket connection. - * @return a copy of the draft - */ - public abstract Draft copyInstance(); - - public Handshakedata translateHandshake( ByteBuffer buf ) throws InvalidHandshakeException { - return translateHandshakeHttp( buf, role ); - } - - public int checkAlloc( int bytecount ) throws InvalidDataException { - if( bytecount < 0 ) - throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Negative count" ); - return bytecount; - } - - int readVersion( Handshakedata handshakedata ) { - String vers = handshakedata.getFieldValue( "Sec-WebSocket-Version" ); - if( vers.length() > 0 ) { - int v; - try { - v = new Integer( vers.trim() ); - return v; - } catch ( NumberFormatException e ) { - return -1; - } - } - return -1; - } - - public void setParseMode( Role role ) { - this.role = role; - } - - public Role getRole() { - return role; - } - - public String toString() { - return getClass().getSimpleName(); - } + /** + * In some cases the handshake will be parsed different depending on whether + */ + protected Role role = null; + + protected Opcode continuousFrameType = null; + + public static ByteBuffer readLine(ByteBuffer buf) { + ByteBuffer sbuf = ByteBuffer.allocate(buf.remaining()); + byte prev; + byte cur = '0'; + while (buf.hasRemaining()) { + prev = cur; + cur = buf.get(); + sbuf.put(cur); + if (prev == (byte) '\r' && cur == (byte) '\n') { + sbuf.limit(sbuf.position() - 2); + sbuf.position(0); + return sbuf; + + } + } + // ensure that there wont be any bytes skipped + buf.position(buf.position() - sbuf.position()); + return null; + } + + public static String readStringLine(ByteBuffer buf) { + ByteBuffer b = readLine(buf); + return b == null ? null : Charsetfunctions.stringAscii(b.array(), 0, b.limit()); + } + + public static HandshakeBuilder translateHandshakeHttp(ByteBuffer buf, Role role) + throws InvalidHandshakeException { + HandshakeBuilder handshake; + + String line = readStringLine(buf); + if (line == null) { + throw new IncompleteHandshakeException(buf.capacity() + 128); + } + + String[] firstLineTokens = line.split(" ", 3);// eg. HTTP/1.1 101 Switching the Protocols + if (firstLineTokens.length != 3) { + throw new InvalidHandshakeException(); + } + if (role == Role.CLIENT) { + handshake = translateHandshakeHttpClient(firstLineTokens, line); + } else { + handshake = translateHandshakeHttpServer(firstLineTokens, line); + } + line = readStringLine(buf); + while (line != null && line.length() > 0) { + String[] pair = line.split(":", 2); + if (pair.length != 2) { + throw new InvalidHandshakeException("not an http header"); + } + // If the handshake contains already a specific key, append the new value + if (handshake.hasFieldValue(pair[0])) { + handshake.put(pair[0], + handshake.getFieldValue(pair[0]) + "; " + pair[1].replaceFirst("^ +", "")); + } else { + handshake.put(pair[0], pair[1].replaceFirst("^ +", "")); + } + line = readStringLine(buf); + } + if (line == null) { + throw new IncompleteHandshakeException(); + } + return handshake; + } + + /** + * Checking the handshake for the role as server + * + * @param firstLineTokens the token of the first line split as as an string array + * @param line the whole line + * @return a handshake + */ + private static HandshakeBuilder translateHandshakeHttpServer(String[] firstLineTokens, + String line) throws InvalidHandshakeException { + // translating/parsing the request from the CLIENT + if (!"GET".equalsIgnoreCase(firstLineTokens[0])) { + throw new InvalidHandshakeException(String + .format("Invalid request method received: %s Status line: %s", firstLineTokens[0], line)); + } + if (!"HTTP/1.1".equalsIgnoreCase(firstLineTokens[2])) { + throw new InvalidHandshakeException(String + .format("Invalid status line received: %s Status line: %s", firstLineTokens[2], line)); + } + ClientHandshakeBuilder clienthandshake = new HandshakeImpl1Client(); + clienthandshake.setResourceDescriptor(firstLineTokens[1]); + return clienthandshake; + } + + /** + * Checking the handshake for the role as client + * + * @param firstLineTokens the token of the first line split as as an string array + * @param line the whole line + * @return a handshake + */ + private static HandshakeBuilder translateHandshakeHttpClient(String[] firstLineTokens, + String line) throws InvalidHandshakeException { + // translating/parsing the response from the SERVER + if (!"101".equals(firstLineTokens[1])) { + throw new InvalidHandshakeException(String + .format("Invalid status code received: %s Status line: %s", firstLineTokens[1], line)); + } + if (!"HTTP/1.1".equalsIgnoreCase(firstLineTokens[0])) { + throw new InvalidHandshakeException(String + .format("Invalid status line received: %s Status line: %s", firstLineTokens[0], line)); + } + HandshakeBuilder handshake = new HandshakeImpl1Server(); + ServerHandshakeBuilder serverhandshake = (ServerHandshakeBuilder) handshake; + serverhandshake.setHttpStatus(Short.parseShort(firstLineTokens[1])); + serverhandshake.setHttpStatusMessage(firstLineTokens[2]); + return handshake; + } + + public abstract HandshakeState acceptHandshakeAsClient(ClientHandshake request, + ServerHandshake response) throws InvalidHandshakeException; + + public abstract HandshakeState acceptHandshakeAsServer(ClientHandshake handshakedata) + throws InvalidHandshakeException; + + protected boolean basicAccept(Handshakedata handshakedata) { + return handshakedata.getFieldValue("Upgrade").equalsIgnoreCase("websocket") && handshakedata + .getFieldValue("Connection").toLowerCase(Locale.ENGLISH).contains("upgrade"); + } + + public abstract ByteBuffer createBinaryFrame(Framedata framedata); + + public abstract List createFrames(ByteBuffer binary, boolean mask); + + public abstract List createFrames(String text, boolean mask); + + + /** + * Handle the frame specific to the draft + * + * @param webSocketImpl the websocketimpl used for this draft + * @param frame the frame which is supposed to be handled + * @throws InvalidDataException will be thrown on invalid data + */ + public abstract void processFrame(WebSocketImpl webSocketImpl, Framedata frame) + throws InvalidDataException; + + public List continuousFrame(Opcode op, ByteBuffer buffer, boolean fin) { + if (op != Opcode.BINARY && op != Opcode.TEXT) { + throw new IllegalArgumentException("Only Opcode.BINARY or Opcode.TEXT are allowed"); + } + DataFrame bui = null; + if (continuousFrameType != null) { + bui = new ContinuousFrame(); + } else { + continuousFrameType = op; + if (op == Opcode.BINARY) { + bui = new BinaryFrame(); + } else if (op == Opcode.TEXT) { + bui = new TextFrame(); + } + } + bui.setPayload(buffer); + bui.setFin(fin); + try { + bui.isValid(); + } catch (InvalidDataException e) { + throw new IllegalArgumentException( + e); // can only happen when one builds close frames(Opcode.Close) + } + if (fin) { + continuousFrameType = null; + } else { + continuousFrameType = op; + } + return Collections.singletonList((Framedata) bui); + } + + public abstract void reset(); + + /** + * @deprecated use createHandshake without the role + */ + @Deprecated + public List createHandshake(Handshakedata handshakedata, Role ownrole) { + return createHandshake(handshakedata); + } + + public List createHandshake(Handshakedata handshakedata) { + return createHandshake(handshakedata, true); + } + + /** + * @deprecated use createHandshake without the role since it does not have any effect + */ + @Deprecated + public List createHandshake(Handshakedata handshakedata, Role ownrole, + boolean withcontent) { + return createHandshake(handshakedata, withcontent); + } + + public List createHandshake(Handshakedata handshakedata, boolean withcontent) { + StringBuilder bui = new StringBuilder(100); + if (handshakedata instanceof ClientHandshake) { + bui.append("GET ").append(((ClientHandshake) handshakedata).getResourceDescriptor()) + .append(" HTTP/1.1"); + } else if (handshakedata instanceof ServerHandshake) { + bui.append("HTTP/1.1 101 ").append(((ServerHandshake) handshakedata).getHttpStatusMessage()); + } else { + throw new IllegalArgumentException("unknown role"); + } + bui.append("\r\n"); + Iterator it = handshakedata.iterateHttpFields(); + while (it.hasNext()) { + String fieldname = it.next(); + String fieldvalue = handshakedata.getFieldValue(fieldname); + bui.append(fieldname); + bui.append(": "); + bui.append(fieldvalue); + bui.append("\r\n"); + } + bui.append("\r\n"); + byte[] httpheader = Charsetfunctions.asciiBytes(bui.toString()); + + byte[] content = withcontent ? handshakedata.getContent() : null; + ByteBuffer bytebuffer = ByteBuffer + .allocate((content == null ? 0 : content.length) + httpheader.length); + bytebuffer.put(httpheader); + if (content != null) { + bytebuffer.put(content); + } + bytebuffer.flip(); + return Collections.singletonList(bytebuffer); + } + + public abstract ClientHandshakeBuilder postProcessHandshakeRequestAsClient( + ClientHandshakeBuilder request) throws InvalidHandshakeException; + + public abstract HandshakeBuilder postProcessHandshakeResponseAsServer(ClientHandshake request, + ServerHandshakeBuilder response) throws InvalidHandshakeException; + + public abstract List translateFrame(ByteBuffer buffer) throws InvalidDataException; + + public abstract CloseHandshakeType getCloseHandshakeType(); + + /** + * Drafts must only be by one websocket at all. To prevent drafts to be used more than once the + * Websocket implementation should call this method in order to create a new usable version of a + * given draft instance.
    The copy can be safely used in conjunction with a new websocket + * connection. + * + * @return a copy of the draft + */ + public abstract Draft copyInstance(); + + public Handshakedata translateHandshake(ByteBuffer buf) throws InvalidHandshakeException { + return translateHandshakeHttp(buf, role); + } + + public int checkAlloc(int bytecount) throws InvalidDataException { + if (bytecount < 0) { + throw new InvalidDataException(CloseFrame.PROTOCOL_ERROR, "Negative count"); + } + return bytecount; + } + + int readVersion(Handshakedata handshakedata) { + String vers = handshakedata.getFieldValue("Sec-WebSocket-Version"); + if (vers.length() > 0) { + int v; + try { + v = new Integer(vers.trim()); + return v; + } catch (NumberFormatException e) { + return -1; + } + } + return -1; + } + + public void setParseMode(Role role) { + this.role = role; + } + + public Role getRole() { + return role; + } + + public String toString() { + return getClass().getSimpleName(); + } } diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index b6259c957..8898babb0 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -46,1041 +46,1123 @@ import java.util.*; /** - * Implementation for the RFC 6455 websocket protocol - * This is the recommended class for your websocket connection + * Implementation for the RFC 6455 websocket protocol This is the recommended class for your + * websocket connection */ public class Draft_6455 extends Draft { - /** - * Handshake specific field for the key - */ - private static final String SEC_WEB_SOCKET_KEY = "Sec-WebSocket-Key"; - - /** - * Handshake specific field for the protocol - */ - private static final String SEC_WEB_SOCKET_PROTOCOL = "Sec-WebSocket-Protocol"; - - /** - * Handshake specific field for the extension - */ - private static final String SEC_WEB_SOCKET_EXTENSIONS = "Sec-WebSocket-Extensions"; - - /** - * Handshake specific field for the accept - */ - private static final String SEC_WEB_SOCKET_ACCEPT = "Sec-WebSocket-Accept"; - - /** - * Handshake specific field for the upgrade - */ - private static final String UPGRADE = "Upgrade" ; - - /** - * Handshake specific field for the connection - */ - private static final String CONNECTION = "Connection"; - - /** - * Logger instance - * - * @since 1.4.0 - */ - private final Logger log = LoggerFactory.getLogger(Draft_6455.class); - - /** - * Attribute for the used extension in this draft - */ - private IExtension extension = new DefaultExtension(); - - /** - * Attribute for all available extension in this draft - */ - private List knownExtensions; - - /** - * Attribute for the used protocol in this draft - */ - private IProtocol protocol; - - /** - * Attribute for all available protocols in this draft - */ - private List knownProtocols; - - /** - * Attribute for the current continuous frame - */ - private Framedata currentContinuousFrame; - - /** - * Attribute for the payload of the current continuous frame - */ - private final List byteBufferList; - - /** - * Attribute for the current incomplete frame - */ - private ByteBuffer incompleteframe; - - /** - * Attribute for the reusable random instance - */ - private final Random reuseableRandom = new Random(); - - /** - * Attribute for the maximum allowed size of a frame - * - * @since 1.4.0 - */ - private int maxFrameSize; - - /** - * Constructor for the websocket protocol specified by RFC 6455 with default extensions - * @since 1.3.5 - */ - public Draft_6455() { - this( Collections.emptyList() ); - } - - /** - * Constructor for the websocket protocol specified by RFC 6455 with custom extensions - * - * @param inputExtension the extension which should be used for this draft - * @since 1.3.5 - */ - public Draft_6455( IExtension inputExtension ) { - this( Collections.singletonList( inputExtension ) ); - } - - /** - * Constructor for the websocket protocol specified by RFC 6455 with custom extensions - * - * @param inputExtensions the extensions which should be used for this draft - * @since 1.3.5 - */ - public Draft_6455( List inputExtensions ) { - this( inputExtensions, Collections.singletonList( new Protocol( "" ) )); - } - - /** - * Constructor for the websocket protocol specified by RFC 6455 with custom extensions and protocols - * - * @param inputExtensions the extensions which should be used for this draft - * @param inputProtocols the protocols which should be used for this draft - * - * @since 1.3.7 - */ - public Draft_6455( List inputExtensions , List inputProtocols ) { - this(inputExtensions, inputProtocols, Integer.MAX_VALUE); - } - - /** - * Constructor for the websocket protocol specified by RFC 6455 with custom extensions and protocols - * - * @param inputExtensions the extensions which should be used for this draft - * @param inputMaxFrameSize the maximum allowed size of a frame (the real payload size, decoded frames can be bigger) - * - * @since 1.4.0 - */ - public Draft_6455( List inputExtensions , int inputMaxFrameSize) { - this(inputExtensions, Collections.singletonList( new Protocol( "" )), inputMaxFrameSize); - } - - /** - * Constructor for the websocket protocol specified by RFC 6455 with custom extensions and protocols - * - * @param inputExtensions the extensions which should be used for this draft - * @param inputProtocols the protocols which should be used for this draft - * @param inputMaxFrameSize the maximum allowed size of a frame (the real payload size, decoded frames can be bigger) - * - * @since 1.4.0 - */ - public Draft_6455( List inputExtensions , List inputProtocols, int inputMaxFrameSize ) { - if (inputExtensions == null || inputProtocols == null || inputMaxFrameSize < 1) { - throw new IllegalArgumentException(); - } - knownExtensions = new ArrayList( inputExtensions.size()); - knownProtocols = new ArrayList( inputProtocols.size()); - boolean hasDefault = false; - byteBufferList = new ArrayList(); - for( IExtension inputExtension : inputExtensions ) { - if( inputExtension.getClass().equals( DefaultExtension.class ) ) { - hasDefault = true; - } - } - knownExtensions.addAll( inputExtensions ); - //We always add the DefaultExtension to implement the normal RFC 6455 specification - if( !hasDefault ) { - knownExtensions.add( this.knownExtensions.size(), extension ); - } - knownProtocols.addAll( inputProtocols ); - maxFrameSize = inputMaxFrameSize; - } - - @Override - public HandshakeState acceptHandshakeAsServer( ClientHandshake handshakedata ) throws InvalidHandshakeException { - int v = readVersion( handshakedata ); - if( v != 13 ) { - log.trace("acceptHandshakeAsServer - Wrong websocket version."); - return HandshakeState.NOT_MATCHED; - } - HandshakeState extensionState = HandshakeState.NOT_MATCHED; - String requestedExtension = handshakedata.getFieldValue(SEC_WEB_SOCKET_EXTENSIONS); - for( IExtension knownExtension : knownExtensions ) { - if( knownExtension.acceptProvidedExtensionAsServer( requestedExtension ) ) { - extension = knownExtension; - extensionState = HandshakeState.MATCHED; - log.trace("acceptHandshakeAsServer - Matching extension found: {}", extension); - break; - } - } - HandshakeState protocolState = containsRequestedProtocol(handshakedata.getFieldValue(SEC_WEB_SOCKET_PROTOCOL)); - if (protocolState == HandshakeState.MATCHED && extensionState == HandshakeState.MATCHED) { - return HandshakeState.MATCHED; - } - log.trace("acceptHandshakeAsServer - No matching extension or protocol found."); - return HandshakeState.NOT_MATCHED; - } - - /** - * Check if the requested protocol is part of this draft - * @param requestedProtocol the requested protocol - * @return MATCHED if it is matched, otherwise NOT_MATCHED - */ - private HandshakeState containsRequestedProtocol(String requestedProtocol) { - for( IProtocol knownProtocol : knownProtocols ) { - if( knownProtocol.acceptProvidedProtocol( requestedProtocol ) ) { - protocol = knownProtocol; - log.trace("acceptHandshake - Matching protocol found: {}", protocol); - return HandshakeState.MATCHED; - } - } - return HandshakeState.NOT_MATCHED; - } - - @Override - public HandshakeState acceptHandshakeAsClient( ClientHandshake request, ServerHandshake response ) throws InvalidHandshakeException { - if (! basicAccept( response )) { - log.trace("acceptHandshakeAsClient - Missing/wrong upgrade or connection in handshake."); - return HandshakeState.NOT_MATCHED; - } - if( !request.hasFieldValue( SEC_WEB_SOCKET_KEY ) || !response.hasFieldValue( SEC_WEB_SOCKET_ACCEPT ) ) { - log.trace("acceptHandshakeAsClient - Missing Sec-WebSocket-Key or Sec-WebSocket-Accept"); - return HandshakeState.NOT_MATCHED; - } - - String seckeyAnswer = response.getFieldValue( SEC_WEB_SOCKET_ACCEPT ); - String seckeyChallenge = request.getFieldValue( SEC_WEB_SOCKET_KEY ); - seckeyChallenge = generateFinalKey( seckeyChallenge ); - - if( !seckeyChallenge.equals( seckeyAnswer ) ) { - log.trace("acceptHandshakeAsClient - Wrong key for Sec-WebSocket-Key."); - return HandshakeState.NOT_MATCHED; - } - HandshakeState extensionState = HandshakeState.NOT_MATCHED; - String requestedExtension = response.getFieldValue(SEC_WEB_SOCKET_EXTENSIONS); - for( IExtension knownExtension : knownExtensions ) { - if( knownExtension.acceptProvidedExtensionAsClient( requestedExtension ) ) { - extension = knownExtension; - extensionState = HandshakeState.MATCHED; - log.trace("acceptHandshakeAsClient - Matching extension found: {}",extension); - break; - } - } - HandshakeState protocolState = containsRequestedProtocol(response.getFieldValue(SEC_WEB_SOCKET_PROTOCOL)); - if (protocolState == HandshakeState.MATCHED && extensionState == HandshakeState.MATCHED) { - return HandshakeState.MATCHED; - } - log.trace("acceptHandshakeAsClient - No matching extension or protocol found."); - return HandshakeState.NOT_MATCHED; - } - - /** - * Getter for the extension which is used by this draft - * - * @return the extension which is used or null, if handshake is not yet done - */ - public IExtension getExtension() { - return extension; - } - - /** - * Getter for all available extensions for this draft - * @return the extensions which are enabled for this draft - */ - public List getKnownExtensions() { - return knownExtensions; - } - - /** - * Getter for the protocol which is used by this draft - * - * @return the protocol which is used or null, if handshake is not yet done or no valid protocols - * @since 1.3.7 - */ - public IProtocol getProtocol() { - return protocol; - } - - - /** - * Getter for the maximum allowed payload size which is used by this draft - * - * @return the size, which is allowed for the payload - * @since 1.4.0 - */ - public int getMaxFrameSize() { - return maxFrameSize; - } - - /** - * Getter for all available protocols for this draft - * @return the protocols which are enabled for this draft - * @since 1.3.7 - */ - public List getKnownProtocols() { - return knownProtocols; - } - - @Override - public ClientHandshakeBuilder postProcessHandshakeRequestAsClient( ClientHandshakeBuilder request ) { - request.put( UPGRADE, "websocket" ); - request.put( CONNECTION, UPGRADE ); // to respond to a Connection keep alives - byte[] random = new byte[16]; - reuseableRandom.nextBytes( random ); - request.put( SEC_WEB_SOCKET_KEY , Base64.encodeBytes( random ) ); - request.put( "Sec-WebSocket-Version", "13" );// overwriting the previous - StringBuilder requestedExtensions = new StringBuilder(); - for( IExtension knownExtension : knownExtensions ) { - if( knownExtension.getProvidedExtensionAsClient() != null && knownExtension.getProvidedExtensionAsClient().length() != 0 ) { - if (requestedExtensions.length() > 0) { - requestedExtensions.append( ", " ); - } - requestedExtensions.append( knownExtension.getProvidedExtensionAsClient() ); - } - } - if( requestedExtensions.length() != 0 ) { - request.put(SEC_WEB_SOCKET_EXTENSIONS, requestedExtensions.toString() ); - } - StringBuilder requestedProtocols = new StringBuilder(); - for( IProtocol knownProtocol : knownProtocols ) { - if( knownProtocol.getProvidedProtocol().length() != 0 ) { - if (requestedProtocols.length() > 0) { - requestedProtocols.append( ", " ); - } - requestedProtocols.append( knownProtocol.getProvidedProtocol() ); - } - } - if( requestedProtocols.length() != 0 ) { - request.put(SEC_WEB_SOCKET_PROTOCOL, requestedProtocols.toString() ); - } - return request; - } - - @Override - public HandshakeBuilder postProcessHandshakeResponseAsServer( ClientHandshake request, ServerHandshakeBuilder response ) throws InvalidHandshakeException { - response.put( UPGRADE, "websocket" ); - response.put( CONNECTION, request.getFieldValue( CONNECTION) ); // to respond to a Connection keep alives - String seckey = request.getFieldValue(SEC_WEB_SOCKET_KEY); - if( seckey == null || "".equals(seckey) ) - throw new InvalidHandshakeException( "missing Sec-WebSocket-Key" ); - response.put( SEC_WEB_SOCKET_ACCEPT, generateFinalKey( seckey ) ); - if( getExtension().getProvidedExtensionAsServer().length() != 0 ) { - response.put(SEC_WEB_SOCKET_EXTENSIONS, getExtension().getProvidedExtensionAsServer() ); - } - if( getProtocol() != null && getProtocol().getProvidedProtocol().length() != 0 ) { - response.put(SEC_WEB_SOCKET_PROTOCOL, getProtocol().getProvidedProtocol() ); - } - response.setHttpStatusMessage( "Web Socket Protocol Handshake" ); - response.put( "Server", "TooTallNate Java-WebSocket" ); - response.put( "Date", getServerTime() ); - return response; - } - - @Override - public Draft copyInstance() { - ArrayList newExtensions = new ArrayList(); - for( IExtension iExtension : getKnownExtensions() ) { - newExtensions.add( iExtension.copyInstance() ); - } - ArrayList newProtocols = new ArrayList(); - for( IProtocol iProtocol : getKnownProtocols() ) { - newProtocols.add( iProtocol.copyInstance() ); - } - return new Draft_6455( newExtensions, newProtocols, maxFrameSize ); - } - - @Override - public ByteBuffer createBinaryFrame( Framedata framedata ) { - getExtension().encodeFrame( framedata ); - if (log.isTraceEnabled()) - log.trace( "afterEnconding({}): {}" , framedata.getPayloadData().remaining(), ( framedata.getPayloadData().remaining() > 1000 ? "too big to display" : new String( framedata.getPayloadData().array() ) ) ); - return createByteBufferFromFramedata( framedata ); - } - - private ByteBuffer createByteBufferFromFramedata( Framedata framedata ) { - ByteBuffer mes = framedata.getPayloadData(); - boolean mask = role == Role.CLIENT; - int sizebytes = getSizeBytes(mes); - ByteBuffer buf = ByteBuffer.allocate( 1 + ( sizebytes > 1 ? sizebytes + 1 : sizebytes ) + ( mask ? 4 : 0 ) + mes.remaining() ); - byte optcode = fromOpcode( framedata.getOpcode() ); - byte one = ( byte ) ( framedata.isFin() ? -128 : 0 ); - one |= optcode; - if(framedata.isRSV1()) - one |= getRSVByte(1); - if(framedata.isRSV2()) - one |= getRSVByte(2); - if(framedata.isRSV3()) - one |= getRSVByte(3); - buf.put( one ); - byte[] payloadlengthbytes = toByteArray( mes.remaining(), sizebytes ); - assert ( payloadlengthbytes.length == sizebytes ); - - if( sizebytes == 1 ) { - buf.put( ( byte ) ( payloadlengthbytes[0] | getMaskByte(mask) ) ); - } else if( sizebytes == 2 ) { - buf.put( ( byte ) ( ( byte ) 126 | getMaskByte(mask))); - buf.put( payloadlengthbytes ); - } else if( sizebytes == 8 ) { - buf.put( ( byte ) ( ( byte ) 127 | getMaskByte(mask))); - buf.put( payloadlengthbytes ); - } else { - throw new IllegalStateException("Size representation not supported/specified"); - } - if( mask ) { - ByteBuffer maskkey = ByteBuffer.allocate( 4 ); - maskkey.putInt( reuseableRandom.nextInt() ); - buf.put( maskkey.array() ); - for( int i = 0; mes.hasRemaining(); i++ ) { - buf.put( ( byte ) ( mes.get() ^ maskkey.get( i % 4 ) ) ); - } - } else { - buf.put( mes ); - //Reset the position of the bytebuffer e.g. for additional use - mes.flip(); - } - assert ( buf.remaining() == 0 ) : buf.remaining(); - buf.flip(); - return buf; - } - - private Framedata translateSingleFrame( ByteBuffer buffer ) throws IncompleteException, InvalidDataException { - if (buffer == null) - throw new IllegalArgumentException(); - int maxpacketsize = buffer.remaining(); - int realpacketsize = 2; - translateSingleFrameCheckPacketSize(maxpacketsize, realpacketsize); - byte b1 = buffer.get( /*0*/ ); - boolean fin = b1 >> 8 != 0; - boolean rsv1 = ( b1 & 0x40 ) != 0; - boolean rsv2 = ( b1 & 0x20 ) != 0; - boolean rsv3 = ( b1 & 0x10 ) != 0; - byte b2 = buffer.get( /*1*/ ); - boolean mask = ( b2 & -128 ) != 0; - int payloadlength = ( byte ) ( b2 & ~( byte ) 128 ); - Opcode optcode = toOpcode( ( byte ) ( b1 & 15 ) ); - - if( !( payloadlength >= 0 && payloadlength <= 125 ) ) { - TranslatedPayloadMetaData payloadData = translateSingleFramePayloadLength(buffer, optcode, payloadlength ,maxpacketsize, realpacketsize); - payloadlength = payloadData.getPayloadLength(); - realpacketsize = payloadData.getRealPackageSize(); - } - translateSingleFrameCheckLengthLimit(payloadlength); - realpacketsize += ( mask ? 4 : 0 ); - realpacketsize += payloadlength; - translateSingleFrameCheckPacketSize(maxpacketsize, realpacketsize); - - ByteBuffer payload = ByteBuffer.allocate( checkAlloc( payloadlength ) ); - if( mask ) { - byte[] maskskey = new byte[4]; - buffer.get( maskskey ); - for( int i = 0; i < payloadlength; i++ ) { - payload.put( ( byte ) ( buffer.get( /*payloadstart + i*/ ) ^ maskskey[i % 4] ) ); - } - } else { - payload.put( buffer.array(), buffer.position(), payload.limit() ); - buffer.position( buffer.position() + payload.limit() ); - } - - FramedataImpl1 frame = FramedataImpl1.get( optcode ); - frame.setFin( fin ); - frame.setRSV1( rsv1 ); - frame.setRSV2( rsv2 ); - frame.setRSV3( rsv3 ); - payload.flip(); - frame.setPayload( payload ); - getExtension().isFrameValid(frame); - getExtension().decodeFrame(frame); - if (log.isTraceEnabled()) - log.trace( "afterDecoding({}): {}", frame.getPayloadData().remaining(), ( frame.getPayloadData().remaining() > 1000 ? "too big to display" : new String( frame.getPayloadData().array() ) ) ); - frame.isValid(); - return frame; - } - - /** - * Translate the buffer depending when it has an extended payload length (126 or 127) - * @param buffer the buffer to read from - * @param optcode the decoded optcode - * @param oldPayloadlength the old payload length - * @param maxpacketsize the max packet size allowed - * @param oldRealpacketsize the real packet size - * @return the new payload data containing new payload length and new packet size - * @throws InvalidFrameException thrown if a control frame has an invalid length - * @throws IncompleteException if the maxpacketsize is smaller than the realpackagesize - * @throws LimitExceededException if the payload length is to big - */ - private TranslatedPayloadMetaData translateSingleFramePayloadLength(ByteBuffer buffer, Opcode optcode, int oldPayloadlength, int maxpacketsize, int oldRealpacketsize) throws InvalidFrameException, IncompleteException, LimitExceededException { - int payloadlength = oldPayloadlength, - realpacketsize = oldRealpacketsize; - if( optcode == Opcode.PING || optcode == Opcode.PONG || optcode == Opcode.CLOSING ) { - log.trace( "Invalid frame: more than 125 octets" ); - throw new InvalidFrameException( "more than 125 octets" ); - } - if( payloadlength == 126 ) { - realpacketsize += 2; // additional length bytes - translateSingleFrameCheckPacketSize(maxpacketsize, realpacketsize); - byte[] sizebytes = new byte[3]; - sizebytes[1] = buffer.get( /*1 + 1*/ ); - sizebytes[2] = buffer.get( /*1 + 2*/ ); - payloadlength = new BigInteger( sizebytes ).intValue(); - } else { - realpacketsize += 8; // additional length bytes - translateSingleFrameCheckPacketSize(maxpacketsize, realpacketsize); - byte[] bytes = new byte[8]; - for( int i = 0; i < 8; i++ ) { - bytes[i] = buffer.get( /*1 + i*/ ); - } - long length = new BigInteger( bytes ).longValue(); - translateSingleFrameCheckLengthLimit(length); - payloadlength = ( int ) length; + /** + * Handshake specific field for the key + */ + private static final String SEC_WEB_SOCKET_KEY = "Sec-WebSocket-Key"; + + /** + * Handshake specific field for the protocol + */ + private static final String SEC_WEB_SOCKET_PROTOCOL = "Sec-WebSocket-Protocol"; + + /** + * Handshake specific field for the extension + */ + private static final String SEC_WEB_SOCKET_EXTENSIONS = "Sec-WebSocket-Extensions"; + + /** + * Handshake specific field for the accept + */ + private static final String SEC_WEB_SOCKET_ACCEPT = "Sec-WebSocket-Accept"; + + /** + * Handshake specific field for the upgrade + */ + private static final String UPGRADE = "Upgrade"; + + /** + * Handshake specific field for the connection + */ + private static final String CONNECTION = "Connection"; + + /** + * Logger instance + * + * @since 1.4.0 + */ + private final Logger log = LoggerFactory.getLogger(Draft_6455.class); + + /** + * Attribute for the used extension in this draft + */ + private IExtension extension = new DefaultExtension(); + + /** + * Attribute for all available extension in this draft + */ + private List knownExtensions; + + /** + * Attribute for the used protocol in this draft + */ + private IProtocol protocol; + + /** + * Attribute for all available protocols in this draft + */ + private List knownProtocols; + + /** + * Attribute for the current continuous frame + */ + private Framedata currentContinuousFrame; + + /** + * Attribute for the payload of the current continuous frame + */ + private final List byteBufferList; + + /** + * Attribute for the current incomplete frame + */ + private ByteBuffer incompleteframe; + + /** + * Attribute for the reusable random instance + */ + private final Random reuseableRandom = new Random(); + + /** + * Attribute for the maximum allowed size of a frame + * + * @since 1.4.0 + */ + private int maxFrameSize; + + /** + * Constructor for the websocket protocol specified by RFC 6455 with default extensions + * + * @since 1.3.5 + */ + public Draft_6455() { + this(Collections.emptyList()); + } + + /** + * Constructor for the websocket protocol specified by RFC 6455 with custom extensions + * + * @param inputExtension the extension which should be used for this draft + * @since 1.3.5 + */ + public Draft_6455(IExtension inputExtension) { + this(Collections.singletonList(inputExtension)); + } + + /** + * Constructor for the websocket protocol specified by RFC 6455 with custom extensions + * + * @param inputExtensions the extensions which should be used for this draft + * @since 1.3.5 + */ + public Draft_6455(List inputExtensions) { + this(inputExtensions, Collections.singletonList(new Protocol(""))); + } + + /** + * Constructor for the websocket protocol specified by RFC 6455 with custom extensions and + * protocols + * + * @param inputExtensions the extensions which should be used for this draft + * @param inputProtocols the protocols which should be used for this draft + * @since 1.3.7 + */ + public Draft_6455(List inputExtensions, List inputProtocols) { + this(inputExtensions, inputProtocols, Integer.MAX_VALUE); + } + + /** + * Constructor for the websocket protocol specified by RFC 6455 with custom extensions and + * protocols + * + * @param inputExtensions the extensions which should be used for this draft + * @param inputMaxFrameSize the maximum allowed size of a frame (the real payload size, decoded + * frames can be bigger) + * @since 1.4.0 + */ + public Draft_6455(List inputExtensions, int inputMaxFrameSize) { + this(inputExtensions, Collections.singletonList(new Protocol("")), + inputMaxFrameSize); + } + + /** + * Constructor for the websocket protocol specified by RFC 6455 with custom extensions and + * protocols + * + * @param inputExtensions the extensions which should be used for this draft + * @param inputProtocols the protocols which should be used for this draft + * @param inputMaxFrameSize the maximum allowed size of a frame (the real payload size, decoded + * frames can be bigger) + * @since 1.4.0 + */ + public Draft_6455(List inputExtensions, List inputProtocols, + int inputMaxFrameSize) { + if (inputExtensions == null || inputProtocols == null || inputMaxFrameSize < 1) { + throw new IllegalArgumentException(); + } + knownExtensions = new ArrayList(inputExtensions.size()); + knownProtocols = new ArrayList(inputProtocols.size()); + boolean hasDefault = false; + byteBufferList = new ArrayList(); + for (IExtension inputExtension : inputExtensions) { + if (inputExtension.getClass().equals(DefaultExtension.class)) { + hasDefault = true; + } + } + knownExtensions.addAll(inputExtensions); + //We always add the DefaultExtension to implement the normal RFC 6455 specification + if (!hasDefault) { + knownExtensions.add(this.knownExtensions.size(), extension); + } + knownProtocols.addAll(inputProtocols); + maxFrameSize = inputMaxFrameSize; + } + + @Override + public HandshakeState acceptHandshakeAsServer(ClientHandshake handshakedata) + throws InvalidHandshakeException { + int v = readVersion(handshakedata); + if (v != 13) { + log.trace("acceptHandshakeAsServer - Wrong websocket version."); + return HandshakeState.NOT_MATCHED; + } + HandshakeState extensionState = HandshakeState.NOT_MATCHED; + String requestedExtension = handshakedata.getFieldValue(SEC_WEB_SOCKET_EXTENSIONS); + for (IExtension knownExtension : knownExtensions) { + if (knownExtension.acceptProvidedExtensionAsServer(requestedExtension)) { + extension = knownExtension; + extensionState = HandshakeState.MATCHED; + log.trace("acceptHandshakeAsServer - Matching extension found: {}", extension); + break; + } + } + HandshakeState protocolState = containsRequestedProtocol( + handshakedata.getFieldValue(SEC_WEB_SOCKET_PROTOCOL)); + if (protocolState == HandshakeState.MATCHED && extensionState == HandshakeState.MATCHED) { + return HandshakeState.MATCHED; + } + log.trace("acceptHandshakeAsServer - No matching extension or protocol found."); + return HandshakeState.NOT_MATCHED; + } + + /** + * Check if the requested protocol is part of this draft + * + * @param requestedProtocol the requested protocol + * @return MATCHED if it is matched, otherwise NOT_MATCHED + */ + private HandshakeState containsRequestedProtocol(String requestedProtocol) { + for (IProtocol knownProtocol : knownProtocols) { + if (knownProtocol.acceptProvidedProtocol(requestedProtocol)) { + protocol = knownProtocol; + log.trace("acceptHandshake - Matching protocol found: {}", protocol); + return HandshakeState.MATCHED; + } + } + return HandshakeState.NOT_MATCHED; + } + + @Override + public HandshakeState acceptHandshakeAsClient(ClientHandshake request, ServerHandshake response) + throws InvalidHandshakeException { + if (!basicAccept(response)) { + log.trace("acceptHandshakeAsClient - Missing/wrong upgrade or connection in handshake."); + return HandshakeState.NOT_MATCHED; + } + if (!request.hasFieldValue(SEC_WEB_SOCKET_KEY) || !response + .hasFieldValue(SEC_WEB_SOCKET_ACCEPT)) { + log.trace("acceptHandshakeAsClient - Missing Sec-WebSocket-Key or Sec-WebSocket-Accept"); + return HandshakeState.NOT_MATCHED; + } + + String seckeyAnswer = response.getFieldValue(SEC_WEB_SOCKET_ACCEPT); + String seckeyChallenge = request.getFieldValue(SEC_WEB_SOCKET_KEY); + seckeyChallenge = generateFinalKey(seckeyChallenge); + + if (!seckeyChallenge.equals(seckeyAnswer)) { + log.trace("acceptHandshakeAsClient - Wrong key for Sec-WebSocket-Key."); + return HandshakeState.NOT_MATCHED; + } + HandshakeState extensionState = HandshakeState.NOT_MATCHED; + String requestedExtension = response.getFieldValue(SEC_WEB_SOCKET_EXTENSIONS); + for (IExtension knownExtension : knownExtensions) { + if (knownExtension.acceptProvidedExtensionAsClient(requestedExtension)) { + extension = knownExtension; + extensionState = HandshakeState.MATCHED; + log.trace("acceptHandshakeAsClient - Matching extension found: {}", extension); + break; + } + } + HandshakeState protocolState = containsRequestedProtocol( + response.getFieldValue(SEC_WEB_SOCKET_PROTOCOL)); + if (protocolState == HandshakeState.MATCHED && extensionState == HandshakeState.MATCHED) { + return HandshakeState.MATCHED; + } + log.trace("acceptHandshakeAsClient - No matching extension or protocol found."); + return HandshakeState.NOT_MATCHED; + } + + /** + * Getter for the extension which is used by this draft + * + * @return the extension which is used or null, if handshake is not yet done + */ + public IExtension getExtension() { + return extension; + } + + /** + * Getter for all available extensions for this draft + * + * @return the extensions which are enabled for this draft + */ + public List getKnownExtensions() { + return knownExtensions; + } + + /** + * Getter for the protocol which is used by this draft + * + * @return the protocol which is used or null, if handshake is not yet done or no valid protocols + * @since 1.3.7 + */ + public IProtocol getProtocol() { + return protocol; + } + + + /** + * Getter for the maximum allowed payload size which is used by this draft + * + * @return the size, which is allowed for the payload + * @since 1.4.0 + */ + public int getMaxFrameSize() { + return maxFrameSize; + } + + /** + * Getter for all available protocols for this draft + * + * @return the protocols which are enabled for this draft + * @since 1.3.7 + */ + public List getKnownProtocols() { + return knownProtocols; + } + + @Override + public ClientHandshakeBuilder postProcessHandshakeRequestAsClient( + ClientHandshakeBuilder request) { + request.put(UPGRADE, "websocket"); + request.put(CONNECTION, UPGRADE); // to respond to a Connection keep alives + byte[] random = new byte[16]; + reuseableRandom.nextBytes(random); + request.put(SEC_WEB_SOCKET_KEY, Base64.encodeBytes(random)); + request.put("Sec-WebSocket-Version", "13");// overwriting the previous + StringBuilder requestedExtensions = new StringBuilder(); + for (IExtension knownExtension : knownExtensions) { + if (knownExtension.getProvidedExtensionAsClient() != null + && knownExtension.getProvidedExtensionAsClient().length() != 0) { + if (requestedExtensions.length() > 0) { + requestedExtensions.append(", "); } - return new TranslatedPayloadMetaData(payloadlength, realpacketsize); - } - - /** - * Check if the frame size exceeds the allowed limit - * @param length the current payload length - * @throws LimitExceededException if the payload length is to big - */ - private void translateSingleFrameCheckLengthLimit(long length) throws LimitExceededException { - if( length > Integer.MAX_VALUE ) { - log.trace("Limit exedeed: Payloadsize is to big..."); - throw new LimitExceededException("Payloadsize is to big..."); - } - if( length > maxFrameSize) { - log.trace( "Payload limit reached. Allowed: {} Current: {}" , maxFrameSize, length); - throw new LimitExceededException( "Payload limit reached.", maxFrameSize ); - } - if( length < 0 ) { - log.trace("Limit underflow: Payloadsize is to little..."); - throw new LimitExceededException("Payloadsize is to little..."); - } - } - - /** - * Check if the max packet size is smaller than the real packet size - * @param maxpacketsize the max packet size - * @param realpacketsize the real packet size - * @throws IncompleteException if the maxpacketsize is smaller than the realpackagesize - */ - private void translateSingleFrameCheckPacketSize(int maxpacketsize, int realpacketsize) throws IncompleteException { - if( maxpacketsize < realpacketsize ) { - log.trace( "Incomplete frame: maxpacketsize < realpacketsize" ); - throw new IncompleteException( realpacketsize ); - } - } - - /** - * Get a byte that can set RSV bits when OR(|)'d. - * 0 1 2 3 4 5 6 7 - * +-+-+-+-+-------+ - * |F|R|R|R| opcode| - * |I|S|S|S| (4) | - * |N|V|V|V| | - * | |1|2|3| | - * @param rsv Can only be {0, 1, 2, 3} - * @return byte that represents which RSV bit is set. - */ - private byte getRSVByte(int rsv){ - if(rsv == 1) // 0100 0000 - return 0x40; - if(rsv == 2) // 0010 0000 - return 0x20; - if(rsv == 3) // 0001 0000 - return 0x10; - return 0; - } - - /** - * Get the mask byte if existing - * @param mask is mask active or not - * @return -128 for true, 0 for false - */ - private byte getMaskByte(boolean mask) { - return mask ? ( byte ) -128 : 0; - } - - /** - * Get the size bytes for the byte buffer - * @param mes the current buffer - * @return the size bytes - */ - private int getSizeBytes(ByteBuffer mes) { - if (mes.remaining() <= 125) { - return 1; - } else if (mes.remaining() <= 65535) { - return 2; - } - return 8; - } - - @Override - public List translateFrame( ByteBuffer buffer ) throws InvalidDataException { - while( true ) { - List frames = new LinkedList(); - Framedata cur; - if( incompleteframe != null ) { - // complete an incomplete frame - try { - buffer.mark(); - int availableNextByteCount = buffer.remaining();// The number of bytes received - int expectedNextByteCount = incompleteframe.remaining();// The number of bytes to complete the incomplete frame - - if( expectedNextByteCount > availableNextByteCount ) { - // did not receive enough bytes to complete the frame - incompleteframe.put( buffer.array(), buffer.position(), availableNextByteCount ); - buffer.position( buffer.position() + availableNextByteCount ); - return Collections.emptyList(); - } - incompleteframe.put( buffer.array(), buffer.position(), expectedNextByteCount ); - buffer.position( buffer.position() + expectedNextByteCount ); - cur = translateSingleFrame( ( ByteBuffer ) incompleteframe.duplicate().position( 0 ) ); - frames.add( cur ); - incompleteframe = null; - } catch ( IncompleteException e ) { - // extending as much as suggested - ByteBuffer extendedframe = ByteBuffer.allocate( checkAlloc( e.getPreferredSize() ) ); - assert ( extendedframe.limit() > incompleteframe.limit() ); - incompleteframe.rewind(); - extendedframe.put( incompleteframe ); - incompleteframe = extendedframe; - continue; - } - } - - while( buffer.hasRemaining() ) {// Read as much as possible full frames - buffer.mark(); - try { - cur = translateSingleFrame( buffer ); - frames.add( cur ); - } catch ( IncompleteException e ) { - // remember the incomplete data - buffer.reset(); - int pref = e.getPreferredSize(); - incompleteframe = ByteBuffer.allocate( checkAlloc( pref ) ); - incompleteframe.put( buffer ); - break; - } - } - return frames; - } - } - - @Override - public List createFrames( ByteBuffer binary, boolean mask ) { - BinaryFrame curframe = new BinaryFrame(); - curframe.setPayload( binary ); - curframe.setTransferemasked( mask ); - try { - curframe.isValid(); - } catch ( InvalidDataException e ) { - throw new NotSendableException( e ); - } - return Collections.singletonList( ( Framedata ) curframe ); - } - - @Override - public List createFrames( String text, boolean mask ) { - TextFrame curframe = new TextFrame(); - curframe.setPayload( ByteBuffer.wrap( Charsetfunctions.utf8Bytes( text ) ) ); - curframe.setTransferemasked( mask ); - try { - curframe.isValid(); - } catch ( InvalidDataException e ) { - throw new NotSendableException( e ); - } - return Collections.singletonList( ( Framedata ) curframe ); - } - - @Override - public void reset() { - incompleteframe = null; - if( extension != null ) { - extension.reset(); - } - extension = new DefaultExtension(); - protocol = null; - } - - /** - * Generate a date for for the date-header - * - * @return the server time - */ - private String getServerTime() { - Calendar calendar = Calendar.getInstance(); - SimpleDateFormat dateFormat = new SimpleDateFormat( - "EEE, dd MMM yyyy HH:mm:ss z", Locale.US ); - dateFormat.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); - return dateFormat.format( calendar.getTime() ); - } - - /** - * Generate a final key from a input string - * @param in the input string - * @return a final key - */ - private String generateFinalKey( String in ) { - String seckey = in.trim(); - String acc = seckey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; - MessageDigest sh1; - try { - sh1 = MessageDigest.getInstance( "SHA1" ); - } catch ( NoSuchAlgorithmException e ) { - throw new IllegalStateException( e ); - } - return Base64.encodeBytes( sh1.digest( acc.getBytes() ) ); - } - - private byte[] toByteArray( long val, int bytecount ) { - byte[] buffer = new byte[bytecount]; - int highest = 8 * bytecount - 8; - for( int i = 0; i < bytecount; i++ ) { - buffer[i] = ( byte ) ( val >>> ( highest - 8 * i ) ); - } - return buffer; - } - - - private byte fromOpcode( Opcode opcode ) { - if( opcode == Opcode.CONTINUOUS ) - return 0; - else if( opcode == Opcode.TEXT ) - return 1; - else if( opcode == Opcode.BINARY ) - return 2; - else if( opcode == Opcode.CLOSING ) - return 8; - else if( opcode == Opcode.PING ) - return 9; - else if( opcode == Opcode.PONG ) - return 10; - throw new IllegalArgumentException( "Don't know how to handle " + opcode.toString() ); - } - - private Opcode toOpcode( byte opcode ) throws InvalidFrameException { - switch(opcode) { - case 0: - return Opcode.CONTINUOUS; - case 1: - return Opcode.TEXT; - case 2: - return Opcode.BINARY; - // 3-7 are not yet defined - case 8: - return Opcode.CLOSING; - case 9: - return Opcode.PING; - case 10: - return Opcode.PONG; - // 11-15 are not yet defined - default: - throw new InvalidFrameException( "Unknown opcode " + ( short ) opcode ); - } - } - - @Override - public void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws InvalidDataException { - Opcode curop = frame.getOpcode(); - if( curop == Opcode.CLOSING ) { - processFrameClosing(webSocketImpl, frame); - } else if( curop == Opcode.PING ) { - webSocketImpl.getWebSocketListener().onWebsocketPing( webSocketImpl, frame ); - } else if( curop == Opcode.PONG ) { - webSocketImpl.updateLastPong(); - webSocketImpl.getWebSocketListener().onWebsocketPong( webSocketImpl, frame ); - } else if( !frame.isFin() || curop == Opcode.CONTINUOUS ) { - processFrameContinuousAndNonFin(webSocketImpl, frame, curop); - } else if( currentContinuousFrame != null ) { - log.error( "Protocol error: Continuous frame sequence not completed." ); - throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence not completed." ); - } else if( curop == Opcode.TEXT ) { - processFrameText(webSocketImpl, frame); - } else if( curop == Opcode.BINARY ) { - processFrameBinary(webSocketImpl, frame); - } else { - log.error( "non control or continious frame expected"); - throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "non control or continious frame expected" ); - } - } - - /** - * Process the frame if it is a continuous frame or the fin bit is not set - * @param webSocketImpl the websocket implementation to use - * @param frame the current frame - * @param curop the current Opcode - * @throws InvalidDataException if there is a protocol error - */ - private void processFrameContinuousAndNonFin(WebSocketImpl webSocketImpl, Framedata frame, Opcode curop) throws InvalidDataException { - if( curop != Opcode.CONTINUOUS ) { - processFrameIsNotFin(frame); - } else if( frame.isFin() ) { - processFrameIsFin(webSocketImpl, frame); - } else if( currentContinuousFrame == null ) { - log.error( "Protocol error: Continuous frame sequence was not started." ); - throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence was not started." ); + requestedExtensions.append(knownExtension.getProvidedExtensionAsClient()); + } + } + if (requestedExtensions.length() != 0) { + request.put(SEC_WEB_SOCKET_EXTENSIONS, requestedExtensions.toString()); + } + StringBuilder requestedProtocols = new StringBuilder(); + for (IProtocol knownProtocol : knownProtocols) { + if (knownProtocol.getProvidedProtocol().length() != 0) { + if (requestedProtocols.length() > 0) { + requestedProtocols.append(", "); } - //Check if the whole payload is valid utf8, when the opcode indicates a text - if( curop == Opcode.TEXT && !Charsetfunctions.isValidUTF8( frame.getPayloadData() ) ) { - log.error( "Protocol error: Payload is not UTF8" ); - throw new InvalidDataException( CloseFrame.NO_UTF8 ); + requestedProtocols.append(knownProtocol.getProvidedProtocol()); + } + } + if (requestedProtocols.length() != 0) { + request.put(SEC_WEB_SOCKET_PROTOCOL, requestedProtocols.toString()); + } + return request; + } + + @Override + public HandshakeBuilder postProcessHandshakeResponseAsServer(ClientHandshake request, + ServerHandshakeBuilder response) throws InvalidHandshakeException { + response.put(UPGRADE, "websocket"); + response.put(CONNECTION, + request.getFieldValue(CONNECTION)); // to respond to a Connection keep alives + String seckey = request.getFieldValue(SEC_WEB_SOCKET_KEY); + if (seckey == null || "".equals(seckey)) { + throw new InvalidHandshakeException("missing Sec-WebSocket-Key"); + } + response.put(SEC_WEB_SOCKET_ACCEPT, generateFinalKey(seckey)); + if (getExtension().getProvidedExtensionAsServer().length() != 0) { + response.put(SEC_WEB_SOCKET_EXTENSIONS, getExtension().getProvidedExtensionAsServer()); + } + if (getProtocol() != null && getProtocol().getProvidedProtocol().length() != 0) { + response.put(SEC_WEB_SOCKET_PROTOCOL, getProtocol().getProvidedProtocol()); + } + response.setHttpStatusMessage("Web Socket Protocol Handshake"); + response.put("Server", "TooTallNate Java-WebSocket"); + response.put("Date", getServerTime()); + return response; + } + + @Override + public Draft copyInstance() { + ArrayList newExtensions = new ArrayList(); + for (IExtension iExtension : getKnownExtensions()) { + newExtensions.add(iExtension.copyInstance()); + } + ArrayList newProtocols = new ArrayList(); + for (IProtocol iProtocol : getKnownProtocols()) { + newProtocols.add(iProtocol.copyInstance()); + } + return new Draft_6455(newExtensions, newProtocols, maxFrameSize); + } + + @Override + public ByteBuffer createBinaryFrame(Framedata framedata) { + getExtension().encodeFrame(framedata); + if (log.isTraceEnabled()) { + log.trace("afterEnconding({}): {}", framedata.getPayloadData().remaining(), + (framedata.getPayloadData().remaining() > 1000 ? "too big to display" + : new String(framedata.getPayloadData().array()))); + } + return createByteBufferFromFramedata(framedata); + } + + private ByteBuffer createByteBufferFromFramedata(Framedata framedata) { + ByteBuffer mes = framedata.getPayloadData(); + boolean mask = role == Role.CLIENT; + int sizebytes = getSizeBytes(mes); + ByteBuffer buf = ByteBuffer.allocate( + 1 + (sizebytes > 1 ? sizebytes + 1 : sizebytes) + (mask ? 4 : 0) + mes.remaining()); + byte optcode = fromOpcode(framedata.getOpcode()); + byte one = (byte) (framedata.isFin() ? -128 : 0); + one |= optcode; + if (framedata.isRSV1()) { + one |= getRSVByte(1); + } + if (framedata.isRSV2()) { + one |= getRSVByte(2); + } + if (framedata.isRSV3()) { + one |= getRSVByte(3); + } + buf.put(one); + byte[] payloadlengthbytes = toByteArray(mes.remaining(), sizebytes); + assert (payloadlengthbytes.length == sizebytes); + + if (sizebytes == 1) { + buf.put((byte) (payloadlengthbytes[0] | getMaskByte(mask))); + } else if (sizebytes == 2) { + buf.put((byte) ((byte) 126 | getMaskByte(mask))); + buf.put(payloadlengthbytes); + } else if (sizebytes == 8) { + buf.put((byte) ((byte) 127 | getMaskByte(mask))); + buf.put(payloadlengthbytes); + } else { + throw new IllegalStateException("Size representation not supported/specified"); + } + if (mask) { + ByteBuffer maskkey = ByteBuffer.allocate(4); + maskkey.putInt(reuseableRandom.nextInt()); + buf.put(maskkey.array()); + for (int i = 0; mes.hasRemaining(); i++) { + buf.put((byte) (mes.get() ^ maskkey.get(i % 4))); + } + } else { + buf.put(mes); + //Reset the position of the bytebuffer e.g. for additional use + mes.flip(); + } + assert (buf.remaining() == 0) : buf.remaining(); + buf.flip(); + return buf; + } + + private Framedata translateSingleFrame(ByteBuffer buffer) + throws IncompleteException, InvalidDataException { + if (buffer == null) { + throw new IllegalArgumentException(); + } + int maxpacketsize = buffer.remaining(); + int realpacketsize = 2; + translateSingleFrameCheckPacketSize(maxpacketsize, realpacketsize); + byte b1 = buffer.get( /*0*/); + boolean fin = b1 >> 8 != 0; + boolean rsv1 = (b1 & 0x40) != 0; + boolean rsv2 = (b1 & 0x20) != 0; + boolean rsv3 = (b1 & 0x10) != 0; + byte b2 = buffer.get( /*1*/); + boolean mask = (b2 & -128) != 0; + int payloadlength = (byte) (b2 & ~(byte) 128); + Opcode optcode = toOpcode((byte) (b1 & 15)); + + if (!(payloadlength >= 0 && payloadlength <= 125)) { + TranslatedPayloadMetaData payloadData = translateSingleFramePayloadLength(buffer, optcode, + payloadlength, maxpacketsize, realpacketsize); + payloadlength = payloadData.getPayloadLength(); + realpacketsize = payloadData.getRealPackageSize(); + } + translateSingleFrameCheckLengthLimit(payloadlength); + realpacketsize += (mask ? 4 : 0); + realpacketsize += payloadlength; + translateSingleFrameCheckPacketSize(maxpacketsize, realpacketsize); + + ByteBuffer payload = ByteBuffer.allocate(checkAlloc(payloadlength)); + if (mask) { + byte[] maskskey = new byte[4]; + buffer.get(maskskey); + for (int i = 0; i < payloadlength; i++) { + payload.put((byte) (buffer.get( /*payloadstart + i*/) ^ maskskey[i % 4])); + } + } else { + payload.put(buffer.array(), buffer.position(), payload.limit()); + buffer.position(buffer.position() + payload.limit()); + } + + FramedataImpl1 frame = FramedataImpl1.get(optcode); + frame.setFin(fin); + frame.setRSV1(rsv1); + frame.setRSV2(rsv2); + frame.setRSV3(rsv3); + payload.flip(); + frame.setPayload(payload); + getExtension().isFrameValid(frame); + getExtension().decodeFrame(frame); + if (log.isTraceEnabled()) { + log.trace("afterDecoding({}): {}", frame.getPayloadData().remaining(), + (frame.getPayloadData().remaining() > 1000 ? "too big to display" + : new String(frame.getPayloadData().array()))); + } + frame.isValid(); + return frame; + } + + /** + * Translate the buffer depending when it has an extended payload length (126 or 127) + * + * @param buffer the buffer to read from + * @param optcode the decoded optcode + * @param oldPayloadlength the old payload length + * @param maxpacketsize the max packet size allowed + * @param oldRealpacketsize the real packet size + * @return the new payload data containing new payload length and new packet size + * @throws InvalidFrameException thrown if a control frame has an invalid length + * @throws IncompleteException if the maxpacketsize is smaller than the realpackagesize + * @throws LimitExceededException if the payload length is to big + */ + private TranslatedPayloadMetaData translateSingleFramePayloadLength(ByteBuffer buffer, + Opcode optcode, int oldPayloadlength, int maxpacketsize, int oldRealpacketsize) + throws InvalidFrameException, IncompleteException, LimitExceededException { + int payloadlength = oldPayloadlength, + realpacketsize = oldRealpacketsize; + if (optcode == Opcode.PING || optcode == Opcode.PONG || optcode == Opcode.CLOSING) { + log.trace("Invalid frame: more than 125 octets"); + throw new InvalidFrameException("more than 125 octets"); + } + if (payloadlength == 126) { + realpacketsize += 2; // additional length bytes + translateSingleFrameCheckPacketSize(maxpacketsize, realpacketsize); + byte[] sizebytes = new byte[3]; + sizebytes[1] = buffer.get( /*1 + 1*/); + sizebytes[2] = buffer.get( /*1 + 2*/); + payloadlength = new BigInteger(sizebytes).intValue(); + } else { + realpacketsize += 8; // additional length bytes + translateSingleFrameCheckPacketSize(maxpacketsize, realpacketsize); + byte[] bytes = new byte[8]; + for (int i = 0; i < 8; i++) { + bytes[i] = buffer.get( /*1 + i*/); + } + long length = new BigInteger(bytes).longValue(); + translateSingleFrameCheckLengthLimit(length); + payloadlength = (int) length; + } + return new TranslatedPayloadMetaData(payloadlength, realpacketsize); + } + + /** + * Check if the frame size exceeds the allowed limit + * + * @param length the current payload length + * @throws LimitExceededException if the payload length is to big + */ + private void translateSingleFrameCheckLengthLimit(long length) throws LimitExceededException { + if (length > Integer.MAX_VALUE) { + log.trace("Limit exedeed: Payloadsize is to big..."); + throw new LimitExceededException("Payloadsize is to big..."); + } + if (length > maxFrameSize) { + log.trace("Payload limit reached. Allowed: {} Current: {}", maxFrameSize, length); + throw new LimitExceededException("Payload limit reached.", maxFrameSize); + } + if (length < 0) { + log.trace("Limit underflow: Payloadsize is to little..."); + throw new LimitExceededException("Payloadsize is to little..."); + } + } + + /** + * Check if the max packet size is smaller than the real packet size + * + * @param maxpacketsize the max packet size + * @param realpacketsize the real packet size + * @throws IncompleteException if the maxpacketsize is smaller than the realpackagesize + */ + private void translateSingleFrameCheckPacketSize(int maxpacketsize, int realpacketsize) + throws IncompleteException { + if (maxpacketsize < realpacketsize) { + log.trace("Incomplete frame: maxpacketsize < realpacketsize"); + throw new IncompleteException(realpacketsize); + } + } + + /** + * Get a byte that can set RSV bits when OR(|)'d. 0 1 2 3 4 5 6 7 +-+-+-+-+-------+ |F|R|R|R| + * opcode| |I|S|S|S| (4) | |N|V|V|V| | | |1|2|3| | + * + * @param rsv Can only be {0, 1, 2, 3} + * @return byte that represents which RSV bit is set. + */ + private byte getRSVByte(int rsv) { + if (rsv == 1) // 0100 0000 + { + return 0x40; + } + if (rsv == 2) // 0010 0000 + { + return 0x20; + } + if (rsv == 3) // 0001 0000 + { + return 0x10; + } + return 0; + } + + /** + * Get the mask byte if existing + * + * @param mask is mask active or not + * @return -128 for true, 0 for false + */ + private byte getMaskByte(boolean mask) { + return mask ? (byte) -128 : 0; + } + + /** + * Get the size bytes for the byte buffer + * + * @param mes the current buffer + * @return the size bytes + */ + private int getSizeBytes(ByteBuffer mes) { + if (mes.remaining() <= 125) { + return 1; + } else if (mes.remaining() <= 65535) { + return 2; + } + return 8; + } + + @Override + public List translateFrame(ByteBuffer buffer) throws InvalidDataException { + while (true) { + List frames = new LinkedList(); + Framedata cur; + if (incompleteframe != null) { + // complete an incomplete frame + try { + buffer.mark(); + int availableNextByteCount = buffer.remaining();// The number of bytes received + int expectedNextByteCount = incompleteframe + .remaining();// The number of bytes to complete the incomplete frame + + if (expectedNextByteCount > availableNextByteCount) { + // did not receive enough bytes to complete the frame + incompleteframe.put(buffer.array(), buffer.position(), availableNextByteCount); + buffer.position(buffer.position() + availableNextByteCount); + return Collections.emptyList(); + } + incompleteframe.put(buffer.array(), buffer.position(), expectedNextByteCount); + buffer.position(buffer.position() + expectedNextByteCount); + cur = translateSingleFrame((ByteBuffer) incompleteframe.duplicate().position(0)); + frames.add(cur); + incompleteframe = null; + } catch (IncompleteException e) { + // extending as much as suggested + ByteBuffer extendedframe = ByteBuffer.allocate(checkAlloc(e.getPreferredSize())); + assert (extendedframe.limit() > incompleteframe.limit()); + incompleteframe.rewind(); + extendedframe.put(incompleteframe); + incompleteframe = extendedframe; + continue; } - //Checking if the current continuous frame contains a correct payload with the other frames combined - if( curop == Opcode.CONTINUOUS && currentContinuousFrame != null ) { - addToBufferList(frame.getPayloadData()); + } + + while (buffer.hasRemaining()) {// Read as much as possible full frames + buffer.mark(); + try { + cur = translateSingleFrame(buffer); + frames.add(cur); + } catch (IncompleteException e) { + // remember the incomplete data + buffer.reset(); + int pref = e.getPreferredSize(); + incompleteframe = ByteBuffer.allocate(checkAlloc(pref)); + incompleteframe.put(buffer); + break; } + } + return frames; + } + } + + @Override + public List createFrames(ByteBuffer binary, boolean mask) { + BinaryFrame curframe = new BinaryFrame(); + curframe.setPayload(binary); + curframe.setTransferemasked(mask); + try { + curframe.isValid(); + } catch (InvalidDataException e) { + throw new NotSendableException(e); + } + return Collections.singletonList((Framedata) curframe); + } + + @Override + public List createFrames(String text, boolean mask) { + TextFrame curframe = new TextFrame(); + curframe.setPayload(ByteBuffer.wrap(Charsetfunctions.utf8Bytes(text))); + curframe.setTransferemasked(mask); + try { + curframe.isValid(); + } catch (InvalidDataException e) { + throw new NotSendableException(e); + } + return Collections.singletonList((Framedata) curframe); + } + + @Override + public void reset() { + incompleteframe = null; + if (extension != null) { + extension.reset(); + } + extension = new DefaultExtension(); + protocol = null; + } + + /** + * Generate a date for for the date-header + * + * @return the server time + */ + private String getServerTime() { + Calendar calendar = Calendar.getInstance(); + SimpleDateFormat dateFormat = new SimpleDateFormat( + "EEE, dd MMM yyyy HH:mm:ss z", Locale.US); + dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); + return dateFormat.format(calendar.getTime()); + } + + /** + * Generate a final key from a input string + * + * @param in the input string + * @return a final key + */ + private String generateFinalKey(String in) { + String seckey = in.trim(); + String acc = seckey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + MessageDigest sh1; + try { + sh1 = MessageDigest.getInstance("SHA1"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + return Base64.encodeBytes(sh1.digest(acc.getBytes())); + } + + private byte[] toByteArray(long val, int bytecount) { + byte[] buffer = new byte[bytecount]; + int highest = 8 * bytecount - 8; + for (int i = 0; i < bytecount; i++) { + buffer[i] = (byte) (val >>> (highest - 8 * i)); + } + return buffer; + } + + + private byte fromOpcode(Opcode opcode) { + if (opcode == Opcode.CONTINUOUS) { + return 0; + } else if (opcode == Opcode.TEXT) { + return 1; + } else if (opcode == Opcode.BINARY) { + return 2; + } else if (opcode == Opcode.CLOSING) { + return 8; + } else if (opcode == Opcode.PING) { + return 9; + } else if (opcode == Opcode.PONG) { + return 10; + } + throw new IllegalArgumentException("Don't know how to handle " + opcode.toString()); + } + + private Opcode toOpcode(byte opcode) throws InvalidFrameException { + switch (opcode) { + case 0: + return Opcode.CONTINUOUS; + case 1: + return Opcode.TEXT; + case 2: + return Opcode.BINARY; + // 3-7 are not yet defined + case 8: + return Opcode.CLOSING; + case 9: + return Opcode.PING; + case 10: + return Opcode.PONG; + // 11-15 are not yet defined + default: + throw new InvalidFrameException("Unknown opcode " + (short) opcode); + } + } + + @Override + public void processFrame(WebSocketImpl webSocketImpl, Framedata frame) + throws InvalidDataException { + Opcode curop = frame.getOpcode(); + if (curop == Opcode.CLOSING) { + processFrameClosing(webSocketImpl, frame); + } else if (curop == Opcode.PING) { + webSocketImpl.getWebSocketListener().onWebsocketPing(webSocketImpl, frame); + } else if (curop == Opcode.PONG) { + webSocketImpl.updateLastPong(); + webSocketImpl.getWebSocketListener().onWebsocketPong(webSocketImpl, frame); + } else if (!frame.isFin() || curop == Opcode.CONTINUOUS) { + processFrameContinuousAndNonFin(webSocketImpl, frame, curop); + } else if (currentContinuousFrame != null) { + log.error("Protocol error: Continuous frame sequence not completed."); + throw new InvalidDataException(CloseFrame.PROTOCOL_ERROR, + "Continuous frame sequence not completed."); + } else if (curop == Opcode.TEXT) { + processFrameText(webSocketImpl, frame); + } else if (curop == Opcode.BINARY) { + processFrameBinary(webSocketImpl, frame); + } else { + log.error("non control or continious frame expected"); + throw new InvalidDataException(CloseFrame.PROTOCOL_ERROR, + "non control or continious frame expected"); + } + } + + /** + * Process the frame if it is a continuous frame or the fin bit is not set + * + * @param webSocketImpl the websocket implementation to use + * @param frame the current frame + * @param curop the current Opcode + * @throws InvalidDataException if there is a protocol error + */ + private void processFrameContinuousAndNonFin(WebSocketImpl webSocketImpl, Framedata frame, + Opcode curop) throws InvalidDataException { + if (curop != Opcode.CONTINUOUS) { + processFrameIsNotFin(frame); + } else if (frame.isFin()) { + processFrameIsFin(webSocketImpl, frame); + } else if (currentContinuousFrame == null) { + log.error("Protocol error: Continuous frame sequence was not started."); + throw new InvalidDataException(CloseFrame.PROTOCOL_ERROR, + "Continuous frame sequence was not started."); + } + //Check if the whole payload is valid utf8, when the opcode indicates a text + if (curop == Opcode.TEXT && !Charsetfunctions.isValidUTF8(frame.getPayloadData())) { + log.error("Protocol error: Payload is not UTF8"); + throw new InvalidDataException(CloseFrame.NO_UTF8); + } + //Checking if the current continuous frame contains a correct payload with the other frames combined + if (curop == Opcode.CONTINUOUS && currentContinuousFrame != null) { + addToBufferList(frame.getPayloadData()); + } + } + + /** + * Process the frame if it is a binary frame + * + * @param webSocketImpl the websocket impl + * @param frame the frame + */ + private void processFrameBinary(WebSocketImpl webSocketImpl, Framedata frame) { + try { + webSocketImpl.getWebSocketListener() + .onWebsocketMessage(webSocketImpl, frame.getPayloadData()); + } catch (RuntimeException e) { + logRuntimeException(webSocketImpl, e); + } + } + + /** + * Log the runtime exception to the specific WebSocketImpl + * + * @param webSocketImpl the implementation of the websocket + * @param e the runtime exception + */ + private void logRuntimeException(WebSocketImpl webSocketImpl, RuntimeException e) { + log.error("Runtime exception during onWebsocketMessage", e); + webSocketImpl.getWebSocketListener().onWebsocketError(webSocketImpl, e); + } + + /** + * Process the frame if it is a text frame + * + * @param webSocketImpl the websocket impl + * @param frame the frame + */ + private void processFrameText(WebSocketImpl webSocketImpl, Framedata frame) + throws InvalidDataException { + try { + webSocketImpl.getWebSocketListener() + .onWebsocketMessage(webSocketImpl, Charsetfunctions.stringUtf8(frame.getPayloadData())); + } catch (RuntimeException e) { + logRuntimeException(webSocketImpl, e); + } + } + + /** + * Process the frame if it is the last frame + * + * @param webSocketImpl the websocket impl + * @param frame the frame + * @throws InvalidDataException if there is a protocol error + */ + private void processFrameIsFin(WebSocketImpl webSocketImpl, Framedata frame) + throws InvalidDataException { + if (currentContinuousFrame == null) { + log.trace("Protocol error: Previous continuous frame sequence not completed."); + throw new InvalidDataException(CloseFrame.PROTOCOL_ERROR, + "Continuous frame sequence was not started."); + } + addToBufferList(frame.getPayloadData()); + checkBufferLimit(); + if (currentContinuousFrame.getOpcode() == Opcode.TEXT) { + ((FramedataImpl1) currentContinuousFrame).setPayload(getPayloadFromByteBufferList()); + ((FramedataImpl1) currentContinuousFrame).isValid(); + try { + webSocketImpl.getWebSocketListener().onWebsocketMessage(webSocketImpl, + Charsetfunctions.stringUtf8(currentContinuousFrame.getPayloadData())); + } catch (RuntimeException e) { + logRuntimeException(webSocketImpl, e); + } + } else if (currentContinuousFrame.getOpcode() == Opcode.BINARY) { + ((FramedataImpl1) currentContinuousFrame).setPayload(getPayloadFromByteBufferList()); + ((FramedataImpl1) currentContinuousFrame).isValid(); + try { + webSocketImpl.getWebSocketListener() + .onWebsocketMessage(webSocketImpl, currentContinuousFrame.getPayloadData()); + } catch (RuntimeException e) { + logRuntimeException(webSocketImpl, e); + } + } + currentContinuousFrame = null; + clearBufferList(); + } + + /** + * Process the frame if it is not the last frame + * + * @param frame the frame + * @throws InvalidDataException if there is a protocol error + */ + private void processFrameIsNotFin(Framedata frame) throws InvalidDataException { + if (currentContinuousFrame != null) { + log.trace("Protocol error: Previous continuous frame sequence not completed."); + throw new InvalidDataException(CloseFrame.PROTOCOL_ERROR, + "Previous continuous frame sequence not completed."); + } + currentContinuousFrame = frame; + addToBufferList(frame.getPayloadData()); + checkBufferLimit(); + } + + /** + * Process the frame if it is a closing frame + * + * @param webSocketImpl the websocket impl + * @param frame the frame + */ + private void processFrameClosing(WebSocketImpl webSocketImpl, Framedata frame) { + int code = CloseFrame.NOCODE; + String reason = ""; + if (frame instanceof CloseFrame) { + CloseFrame cf = (CloseFrame) frame; + code = cf.getCloseCode(); + reason = cf.getMessage(); } + if (webSocketImpl.getReadyState() == ReadyState.CLOSING) { + // complete the close handshake by disconnecting + webSocketImpl.closeConnection(code, reason, true); + } else { + // echo close handshake + if (getCloseHandshakeType() == CloseHandshakeType.TWOWAY) { + webSocketImpl.close(code, reason, true); + } else { + webSocketImpl.flushAndClose(code, reason, false); + } + } + } + + /** + * Clear the current bytebuffer list + */ + private void clearBufferList() { + synchronized (byteBufferList) { + byteBufferList.clear(); + } + } + + /** + * Add a payload to the current bytebuffer list + * + * @param payloadData the new payload + */ + private void addToBufferList(ByteBuffer payloadData) { + synchronized (byteBufferList) { + byteBufferList.add(payloadData); + } + } + + /** + * Check the current size of the buffer and throw an exception if the size is bigger than the max + * allowed frame size + * + * @throws LimitExceededException if the current size is bigger than the allowed size + */ + private void checkBufferLimit() throws LimitExceededException { + long totalSize = getByteBufferListSize(); + if (totalSize > maxFrameSize) { + clearBufferList(); + log.trace("Payload limit reached. Allowed: {} Current: {}", maxFrameSize, totalSize); + throw new LimitExceededException(maxFrameSize); + } + } + + @Override + public CloseHandshakeType getCloseHandshakeType() { + return CloseHandshakeType.TWOWAY; + } + + @Override + public String toString() { + String result = super.toString(); + if (getExtension() != null) { + result += " extension: " + getExtension().toString(); + } + if (getProtocol() != null) { + result += " protocol: " + getProtocol().toString(); + } + result += " max frame size: " + this.maxFrameSize; + return result; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + Draft_6455 that = (Draft_6455) o; - /** - * Process the frame if it is a binary frame - * @param webSocketImpl the websocket impl - * @param frame the frame - */ - private void processFrameBinary(WebSocketImpl webSocketImpl, Framedata frame) { - try { - webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, frame.getPayloadData() ); - } catch ( RuntimeException e ) { - logRuntimeException(webSocketImpl, e); - } - } - - /** - * Log the runtime exception to the specific WebSocketImpl - * @param webSocketImpl the implementation of the websocket - * @param e the runtime exception - */ - private void logRuntimeException(WebSocketImpl webSocketImpl, RuntimeException e) { - log.error( "Runtime exception during onWebsocketMessage", e ); - webSocketImpl.getWebSocketListener().onWebsocketError( webSocketImpl, e ); - } - - /** - * Process the frame if it is a text frame - * @param webSocketImpl the websocket impl - * @param frame the frame - */ - private void processFrameText(WebSocketImpl webSocketImpl, Framedata frame) throws InvalidDataException { - try { - webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, Charsetfunctions.stringUtf8( frame.getPayloadData() ) ); - } catch ( RuntimeException e ) { - logRuntimeException(webSocketImpl, e); - } - } - - /** - * Process the frame if it is the last frame - * @param webSocketImpl the websocket impl - * @param frame the frame - * @throws InvalidDataException if there is a protocol error - */ - private void processFrameIsFin(WebSocketImpl webSocketImpl, Framedata frame) throws InvalidDataException { - if( currentContinuousFrame == null ) { - log.trace( "Protocol error: Previous continuous frame sequence not completed." ); - throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence was not started." ); - } - addToBufferList(frame.getPayloadData()); - checkBufferLimit(); - if( currentContinuousFrame.getOpcode() == Opcode.TEXT ) { - ((FramedataImpl1) currentContinuousFrame).setPayload( getPayloadFromByteBufferList() ); - ((FramedataImpl1) currentContinuousFrame).isValid(); - try { - webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, Charsetfunctions.stringUtf8( currentContinuousFrame.getPayloadData() ) ); - } catch ( RuntimeException e ) { - logRuntimeException(webSocketImpl, e); - } - } else if( currentContinuousFrame.getOpcode() == Opcode.BINARY ) { - ((FramedataImpl1) currentContinuousFrame).setPayload( getPayloadFromByteBufferList() ); - ((FramedataImpl1) currentContinuousFrame).isValid(); - try { - webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, currentContinuousFrame.getPayloadData() ); - } catch ( RuntimeException e ) { - logRuntimeException(webSocketImpl, e); - } - } - currentContinuousFrame = null; - clearBufferList(); - } - - /** - * Process the frame if it is not the last frame - * @param frame the frame - * @throws InvalidDataException if there is a protocol error - */ - private void processFrameIsNotFin(Framedata frame) throws InvalidDataException { - if( currentContinuousFrame != null ) { - log.trace( "Protocol error: Previous continuous frame sequence not completed." ); - throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Previous continuous frame sequence not completed." ); - } - currentContinuousFrame = frame; - addToBufferList(frame.getPayloadData()); - checkBufferLimit(); - } - - /** - * Process the frame if it is a closing frame - * @param webSocketImpl the websocket impl - * @param frame the frame - */ - private void processFrameClosing(WebSocketImpl webSocketImpl, Framedata frame) { - int code = CloseFrame.NOCODE; - String reason = ""; - if( frame instanceof CloseFrame ) { - CloseFrame cf = ( CloseFrame ) frame; - code = cf.getCloseCode(); - reason = cf.getMessage(); - } - if( webSocketImpl.getReadyState() == ReadyState.CLOSING ) { - // complete the close handshake by disconnecting - webSocketImpl.closeConnection( code, reason, true ); - } else { - // echo close handshake - if( getCloseHandshakeType() == CloseHandshakeType.TWOWAY ) - webSocketImpl.close( code, reason, true ); - else - webSocketImpl.flushAndClose( code, reason, false ); - } - } - - /** - * Clear the current bytebuffer list - */ - private void clearBufferList() { - synchronized (byteBufferList) { - byteBufferList.clear(); - } - } - - /** - * Add a payload to the current bytebuffer list - * @param payloadData the new payload - */ - private void addToBufferList(ByteBuffer payloadData) { - synchronized (byteBufferList) { - byteBufferList.add(payloadData); - } - } - - /** - * Check the current size of the buffer and throw an exception if the size is bigger than the max allowed frame size - * @throws LimitExceededException if the current size is bigger than the allowed size - */ - private void checkBufferLimit() throws LimitExceededException { - long totalSize = getByteBufferListSize(); - if( totalSize > maxFrameSize ) { - clearBufferList(); - log.trace("Payload limit reached. Allowed: {} Current: {}", maxFrameSize, totalSize); - throw new LimitExceededException(maxFrameSize); - } - } - - @Override - public CloseHandshakeType getCloseHandshakeType() { - return CloseHandshakeType.TWOWAY; - } - - @Override - public String toString() { - String result = super.toString(); - if( getExtension() != null ) - result += " extension: " + getExtension().toString(); - if ( getProtocol() != null ) - result += " protocol: " + getProtocol().toString(); - result += " max frame size: " + this.maxFrameSize; - return result; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Draft_6455 that = (Draft_6455) o; - - if (maxFrameSize != that.getMaxFrameSize()) return false; - if (extension != null ? !extension.equals(that.getExtension()) : that.getExtension() != null) return false; - return protocol != null ? protocol.equals(that.getProtocol()) : that.getProtocol() == null; - } - - @Override - public int hashCode() { - int result = extension != null ? extension.hashCode() : 0; - result = 31 * result + (protocol != null ? protocol.hashCode() : 0); - result = 31 * result + (maxFrameSize ^ (maxFrameSize >>> 32)); - return result; - } - - /** - * Method to generate a full bytebuffer out of all the fragmented frame payload - * @return a bytebuffer containing all the data - * @throws LimitExceededException will be thrown when the totalSize is bigger then Integer.MAX_VALUE due to not being able to allocate more - */ - private ByteBuffer getPayloadFromByteBufferList() throws LimitExceededException { - long totalSize = 0; - ByteBuffer resultingByteBuffer; - synchronized (byteBufferList) { - for (ByteBuffer buffer : byteBufferList) { - totalSize += buffer.limit(); - } - checkBufferLimit(); - resultingByteBuffer = ByteBuffer.allocate( (int) totalSize ); - for (ByteBuffer buffer : byteBufferList) { - resultingByteBuffer.put( buffer ); - } - } - resultingByteBuffer.flip(); - return resultingByteBuffer; - } - - /** - * Get the current size of the resulting bytebuffer in the bytebuffer list - * @return the size as long (to not get an integer overflow) - */ - private long getByteBufferListSize() { - long totalSize = 0; - synchronized (byteBufferList) { - for (ByteBuffer buffer : byteBufferList) { - totalSize += buffer.limit(); - } - } - return totalSize; - } - - private class TranslatedPayloadMetaData { - private int payloadLength; - private int realPackageSize; - - private int getPayloadLength() { - return payloadLength; - } - - private int getRealPackageSize() { - return realPackageSize; - } - - TranslatedPayloadMetaData(int newPayloadLength, int newRealPackageSize) { - this.payloadLength = newPayloadLength; - this.realPackageSize = newRealPackageSize; - } - } + if (maxFrameSize != that.getMaxFrameSize()) { + return false; + } + if (extension != null ? !extension.equals(that.getExtension()) : that.getExtension() != null) { + return false; + } + return protocol != null ? protocol.equals(that.getProtocol()) : that.getProtocol() == null; + } + + @Override + public int hashCode() { + int result = extension != null ? extension.hashCode() : 0; + result = 31 * result + (protocol != null ? protocol.hashCode() : 0); + result = 31 * result + (maxFrameSize ^ (maxFrameSize >>> 32)); + return result; + } + + /** + * Method to generate a full bytebuffer out of all the fragmented frame payload + * + * @return a bytebuffer containing all the data + * @throws LimitExceededException will be thrown when the totalSize is bigger then + * Integer.MAX_VALUE due to not being able to allocate more + */ + private ByteBuffer getPayloadFromByteBufferList() throws LimitExceededException { + long totalSize = 0; + ByteBuffer resultingByteBuffer; + synchronized (byteBufferList) { + for (ByteBuffer buffer : byteBufferList) { + totalSize += buffer.limit(); + } + checkBufferLimit(); + resultingByteBuffer = ByteBuffer.allocate((int) totalSize); + for (ByteBuffer buffer : byteBufferList) { + resultingByteBuffer.put(buffer); + } + } + resultingByteBuffer.flip(); + return resultingByteBuffer; + } + + /** + * Get the current size of the resulting bytebuffer in the bytebuffer list + * + * @return the size as long (to not get an integer overflow) + */ + private long getByteBufferListSize() { + long totalSize = 0; + synchronized (byteBufferList) { + for (ByteBuffer buffer : byteBufferList) { + totalSize += buffer.limit(); + } + } + return totalSize; + } + + private class TranslatedPayloadMetaData { + + private int payloadLength; + private int realPackageSize; + + private int getPayloadLength() { + return payloadLength; + } + + private int getRealPackageSize() { + return realPackageSize; + } + + TranslatedPayloadMetaData(int newPayloadLength, int newRealPackageSize) { + this.payloadLength = newPayloadLength; + this.realPackageSize = newRealPackageSize; + } + } } diff --git a/src/main/java/org/java_websocket/enums/CloseHandshakeType.java b/src/main/java/org/java_websocket/enums/CloseHandshakeType.java index 77ece10f5..0bd1f94d5 100644 --- a/src/main/java/org/java_websocket/enums/CloseHandshakeType.java +++ b/src/main/java/org/java_websocket/enums/CloseHandshakeType.java @@ -4,5 +4,5 @@ * Enum which represents type of handshake is required for a close */ public enum CloseHandshakeType { - NONE, ONEWAY, TWOWAY + NONE, ONEWAY, TWOWAY } \ No newline at end of file diff --git a/src/main/java/org/java_websocket/enums/HandshakeState.java b/src/main/java/org/java_websocket/enums/HandshakeState.java index 541718304..c87750601 100644 --- a/src/main/java/org/java_websocket/enums/HandshakeState.java +++ b/src/main/java/org/java_websocket/enums/HandshakeState.java @@ -4,8 +4,12 @@ * Enum which represents the states a handshake may be in */ public enum HandshakeState { - /** Handshake matched this Draft successfully */ - MATCHED, - /** Handshake is does not match this Draft */ - NOT_MATCHED + /** + * Handshake matched this Draft successfully + */ + MATCHED, + /** + * Handshake is does not match this Draft + */ + NOT_MATCHED } \ No newline at end of file diff --git a/src/main/java/org/java_websocket/enums/Opcode.java b/src/main/java/org/java_websocket/enums/Opcode.java index 765544661..cc65e31a0 100644 --- a/src/main/java/org/java_websocket/enums/Opcode.java +++ b/src/main/java/org/java_websocket/enums/Opcode.java @@ -4,6 +4,6 @@ * Enum which contains the different valid opcodes */ public enum Opcode { - CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING - // more to come + CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING + // more to come } \ No newline at end of file diff --git a/src/main/java/org/java_websocket/enums/ReadyState.java b/src/main/java/org/java_websocket/enums/ReadyState.java index 679732a9f..15bd5cc8d 100644 --- a/src/main/java/org/java_websocket/enums/ReadyState.java +++ b/src/main/java/org/java_websocket/enums/ReadyState.java @@ -4,5 +4,5 @@ * Enum which represents the state a websocket may be in */ public enum ReadyState { - NOT_YET_CONNECTED, OPEN, CLOSING, CLOSED + NOT_YET_CONNECTED, OPEN, CLOSING, CLOSED } \ No newline at end of file diff --git a/src/main/java/org/java_websocket/enums/Role.java b/src/main/java/org/java_websocket/enums/Role.java index acef4537c..8a057a308 100644 --- a/src/main/java/org/java_websocket/enums/Role.java +++ b/src/main/java/org/java_websocket/enums/Role.java @@ -4,5 +4,5 @@ * Enum which represents the states a websocket may be in */ public enum Role { - CLIENT, SERVER + CLIENT, SERVER } \ No newline at end of file diff --git a/src/main/java/org/java_websocket/exceptions/IncompleteException.java b/src/main/java/org/java_websocket/exceptions/IncompleteException.java index 6f95e3845..d3e83834d 100644 --- a/src/main/java/org/java_websocket/exceptions/IncompleteException.java +++ b/src/main/java/org/java_websocket/exceptions/IncompleteException.java @@ -30,29 +30,31 @@ */ public class IncompleteException extends Exception { - /** - * It's Serializable. - */ - private static final long serialVersionUID = 7330519489840500997L; + /** + * It's Serializable. + */ + private static final long serialVersionUID = 7330519489840500997L; - /** - * The preferred size - */ - private final int preferredSize; + /** + * The preferred size + */ + private final int preferredSize; - /** - * Constructor for the preferred size of a frame - * @param preferredSize the preferred size of a frame - */ - public IncompleteException( int preferredSize ) { - this.preferredSize = preferredSize; - } + /** + * Constructor for the preferred size of a frame + * + * @param preferredSize the preferred size of a frame + */ + public IncompleteException(int preferredSize) { + this.preferredSize = preferredSize; + } - /** - * Getter for the preferredSize - * @return the value of the preferred size - */ - public int getPreferredSize() { - return preferredSize; - } + /** + * Getter for the preferredSize + * + * @return the value of the preferred size + */ + public int getPreferredSize() { + return preferredSize; + } } diff --git a/src/main/java/org/java_websocket/exceptions/IncompleteHandshakeException.java b/src/main/java/org/java_websocket/exceptions/IncompleteHandshakeException.java index 87826e297..17307c379 100644 --- a/src/main/java/org/java_websocket/exceptions/IncompleteHandshakeException.java +++ b/src/main/java/org/java_websocket/exceptions/IncompleteHandshakeException.java @@ -30,41 +30,42 @@ */ public class IncompleteHandshakeException extends RuntimeException { - /** - * Serializable - */ - private static final long serialVersionUID = 7906596804233893092L; + /** + * Serializable + */ + private static final long serialVersionUID = 7906596804233893092L; - /** - * attribute which size of handshake would have been preferred - */ - private final int preferredSize; + /** + * attribute which size of handshake would have been preferred + */ + private final int preferredSize; - /** - * constructor for a IncompleteHandshakeException - *

    - * @param preferredSize the preferred size - */ - public IncompleteHandshakeException(int preferredSize) { - this.preferredSize = preferredSize; - } + /** + * constructor for a IncompleteHandshakeException + *

    + * + * @param preferredSize the preferred size + */ + public IncompleteHandshakeException(int preferredSize) { + this.preferredSize = preferredSize; + } - /** - * constructor for a IncompleteHandshakeException - *

    - * preferredSize will be 0 - */ - public IncompleteHandshakeException() { - this.preferredSize = 0; - } + /** + * constructor for a IncompleteHandshakeException + *

    + * preferredSize will be 0 + */ + public IncompleteHandshakeException() { + this.preferredSize = 0; + } - /** - * Getter preferredSize - * - * @return the preferredSize - */ - public int getPreferredSize() { - return preferredSize; - } + /** + * Getter preferredSize + * + * @return the preferredSize + */ + public int getPreferredSize() { + return preferredSize; + } } diff --git a/src/main/java/org/java_websocket/exceptions/InvalidDataException.java b/src/main/java/org/java_websocket/exceptions/InvalidDataException.java index 885cf4545..c34c8c941 100644 --- a/src/main/java/org/java_websocket/exceptions/InvalidDataException.java +++ b/src/main/java/org/java_websocket/exceptions/InvalidDataException.java @@ -30,66 +30,66 @@ */ public class InvalidDataException extends Exception { - /** - * Serializable - */ - private static final long serialVersionUID = 3731842424390998726L; + /** + * Serializable + */ + private static final long serialVersionUID = 3731842424390998726L; - /** - * attribute which closecode will be returned - */ - private final int closecode; + /** + * attribute which closecode will be returned + */ + private final int closecode; - /** - * constructor for a InvalidDataException - * - * @param closecode the closecode which will be returned - */ - public InvalidDataException(int closecode) { - this.closecode = closecode; - } + /** + * constructor for a InvalidDataException + * + * @param closecode the closecode which will be returned + */ + public InvalidDataException(int closecode) { + this.closecode = closecode; + } - /** - * constructor for a InvalidDataException. - * - * @param closecode the closecode which will be returned. - * @param s the detail message. - */ - public InvalidDataException(int closecode, String s) { - super(s); - this.closecode = closecode; - } + /** + * constructor for a InvalidDataException. + * + * @param closecode the closecode which will be returned. + * @param s the detail message. + */ + public InvalidDataException(int closecode, String s) { + super(s); + this.closecode = closecode; + } - /** - * constructor for a InvalidDataException. - * - * @param closecode the closecode which will be returned. - * @param t the throwable causing this exception. - */ - public InvalidDataException(int closecode, Throwable t) { - super(t); - this.closecode = closecode; - } + /** + * constructor for a InvalidDataException. + * + * @param closecode the closecode which will be returned. + * @param t the throwable causing this exception. + */ + public InvalidDataException(int closecode, Throwable t) { + super(t); + this.closecode = closecode; + } - /** - * constructor for a InvalidDataException. - * - * @param closecode the closecode which will be returned. - * @param s the detail message. - * @param t the throwable causing this exception. - */ - public InvalidDataException(int closecode, String s, Throwable t) { - super(s, t); - this.closecode = closecode; - } + /** + * constructor for a InvalidDataException. + * + * @param closecode the closecode which will be returned. + * @param s the detail message. + * @param t the throwable causing this exception. + */ + public InvalidDataException(int closecode, String s, Throwable t) { + super(s, t); + this.closecode = closecode; + } - /** - * Getter closecode - * - * @return the closecode - */ - public int getCloseCode() { - return closecode; - } + /** + * Getter closecode + * + * @return the closecode + */ + public int getCloseCode() { + return closecode; + } } diff --git a/src/main/java/org/java_websocket/exceptions/InvalidEncodingException.java b/src/main/java/org/java_websocket/exceptions/InvalidEncodingException.java index e966d8ec3..8fdbd1a38 100644 --- a/src/main/java/org/java_websocket/exceptions/InvalidEncodingException.java +++ b/src/main/java/org/java_websocket/exceptions/InvalidEncodingException.java @@ -9,27 +9,29 @@ */ public class InvalidEncodingException extends RuntimeException { - /** - * attribute for the encoding exception - */ - private final UnsupportedEncodingException encodingException; + /** + * attribute for the encoding exception + */ + private final UnsupportedEncodingException encodingException; - /** - * constructor for InvalidEncodingException - * - * @param encodingException the cause for this exception - */ - public InvalidEncodingException(UnsupportedEncodingException encodingException) { - if (encodingException == null) - throw new IllegalArgumentException(); - this.encodingException = encodingException; + /** + * constructor for InvalidEncodingException + * + * @param encodingException the cause for this exception + */ + public InvalidEncodingException(UnsupportedEncodingException encodingException) { + if (encodingException == null) { + throw new IllegalArgumentException(); } + this.encodingException = encodingException; + } - /** - * Get the exception which includes more information on the unsupported encoding - * @return an UnsupportedEncodingException - */ - public UnsupportedEncodingException getEncodingException() { - return encodingException; - } + /** + * Get the exception which includes more information on the unsupported encoding + * + * @return an UnsupportedEncodingException + */ + public UnsupportedEncodingException getEncodingException() { + return encodingException; + } } diff --git a/src/main/java/org/java_websocket/exceptions/InvalidFrameException.java b/src/main/java/org/java_websocket/exceptions/InvalidFrameException.java index 9d5ed55c9..7de2034da 100644 --- a/src/main/java/org/java_websocket/exceptions/InvalidFrameException.java +++ b/src/main/java/org/java_websocket/exceptions/InvalidFrameException.java @@ -32,51 +32,51 @@ */ public class InvalidFrameException extends InvalidDataException { - /** - * Serializable - */ - private static final long serialVersionUID = -9016496369828887591L; + /** + * Serializable + */ + private static final long serialVersionUID = -9016496369828887591L; - /** - * constructor for a InvalidFrameException - *

    - * calling InvalidDataException with closecode PROTOCOL_ERROR - */ - public InvalidFrameException() { - super( CloseFrame.PROTOCOL_ERROR); - } + /** + * constructor for a InvalidFrameException + *

    + * calling InvalidDataException with closecode PROTOCOL_ERROR + */ + public InvalidFrameException() { + super(CloseFrame.PROTOCOL_ERROR); + } - /** - * constructor for a InvalidFrameException - *

    - * calling InvalidDataException with closecode PROTOCOL_ERROR - * - * @param s the detail message. - */ - public InvalidFrameException(String s) { - super( CloseFrame.PROTOCOL_ERROR, s); - } + /** + * constructor for a InvalidFrameException + *

    + * calling InvalidDataException with closecode PROTOCOL_ERROR + * + * @param s the detail message. + */ + public InvalidFrameException(String s) { + super(CloseFrame.PROTOCOL_ERROR, s); + } - /** - * constructor for a InvalidFrameException - *

    - * calling InvalidDataException with closecode PROTOCOL_ERROR - * - * @param t the throwable causing this exception. - */ - public InvalidFrameException(Throwable t) { - super( CloseFrame.PROTOCOL_ERROR, t); - } + /** + * constructor for a InvalidFrameException + *

    + * calling InvalidDataException with closecode PROTOCOL_ERROR + * + * @param t the throwable causing this exception. + */ + public InvalidFrameException(Throwable t) { + super(CloseFrame.PROTOCOL_ERROR, t); + } - /** - * constructor for a InvalidFrameException - *

    - * calling InvalidDataException with closecode PROTOCOL_ERROR - * - * @param s the detail message. - * @param t the throwable causing this exception. - */ - public InvalidFrameException(String s, Throwable t) { - super( CloseFrame.PROTOCOL_ERROR, s, t); - } + /** + * constructor for a InvalidFrameException + *

    + * calling InvalidDataException with closecode PROTOCOL_ERROR + * + * @param s the detail message. + * @param t the throwable causing this exception. + */ + public InvalidFrameException(String s, Throwable t) { + super(CloseFrame.PROTOCOL_ERROR, s, t); + } } diff --git a/src/main/java/org/java_websocket/exceptions/InvalidHandshakeException.java b/src/main/java/org/java_websocket/exceptions/InvalidHandshakeException.java index 12209ec6f..af1fd2157 100644 --- a/src/main/java/org/java_websocket/exceptions/InvalidHandshakeException.java +++ b/src/main/java/org/java_websocket/exceptions/InvalidHandshakeException.java @@ -32,52 +32,52 @@ */ public class InvalidHandshakeException extends InvalidDataException { - /** - * Serializable - */ - private static final long serialVersionUID = -1426533877490484964L; + /** + * Serializable + */ + private static final long serialVersionUID = -1426533877490484964L; - /** - * constructor for a InvalidHandshakeException - *

    - * calling InvalidDataException with closecode PROTOCOL_ERROR - */ - public InvalidHandshakeException() { - super( CloseFrame.PROTOCOL_ERROR); - } + /** + * constructor for a InvalidHandshakeException + *

    + * calling InvalidDataException with closecode PROTOCOL_ERROR + */ + public InvalidHandshakeException() { + super(CloseFrame.PROTOCOL_ERROR); + } - /** - * constructor for a InvalidHandshakeException - *

    - * calling InvalidDataException with closecode PROTOCOL_ERROR - * - * @param s the detail message. - * @param t the throwable causing this exception. - */ - public InvalidHandshakeException(String s, Throwable t) { - super( CloseFrame.PROTOCOL_ERROR, s, t); - } + /** + * constructor for a InvalidHandshakeException + *

    + * calling InvalidDataException with closecode PROTOCOL_ERROR + * + * @param s the detail message. + * @param t the throwable causing this exception. + */ + public InvalidHandshakeException(String s, Throwable t) { + super(CloseFrame.PROTOCOL_ERROR, s, t); + } - /** - * constructor for a InvalidHandshakeException - *

    - * calling InvalidDataException with closecode PROTOCOL_ERROR - * - * @param s the detail message. - */ - public InvalidHandshakeException(String s) { - super( CloseFrame.PROTOCOL_ERROR, s); - } + /** + * constructor for a InvalidHandshakeException + *

    + * calling InvalidDataException with closecode PROTOCOL_ERROR + * + * @param s the detail message. + */ + public InvalidHandshakeException(String s) { + super(CloseFrame.PROTOCOL_ERROR, s); + } - /** - * constructor for a InvalidHandshakeException - *

    - * calling InvalidDataException with closecode PROTOCOL_ERROR - * - * @param t the throwable causing this exception. - */ - public InvalidHandshakeException(Throwable t) { - super( CloseFrame.PROTOCOL_ERROR, t); - } + /** + * constructor for a InvalidHandshakeException + *

    + * calling InvalidDataException with closecode PROTOCOL_ERROR + * + * @param t the throwable causing this exception. + */ + public InvalidHandshakeException(Throwable t) { + super(CloseFrame.PROTOCOL_ERROR, t); + } } diff --git a/src/main/java/org/java_websocket/exceptions/LimitExceededException.java b/src/main/java/org/java_websocket/exceptions/LimitExceededException.java index 9642a77d3..9f76d442f 100644 --- a/src/main/java/org/java_websocket/exceptions/LimitExceededException.java +++ b/src/main/java/org/java_websocket/exceptions/LimitExceededException.java @@ -32,61 +32,62 @@ */ public class LimitExceededException extends InvalidDataException { - /** - * Serializable - */ - private static final long serialVersionUID = 6908339749836826785L; + /** + * Serializable + */ + private static final long serialVersionUID = 6908339749836826785L; - /** - * A closer indication about the limit - */ - private final int limit; + /** + * A closer indication about the limit + */ + private final int limit; - /** - * constructor for a LimitExceededException - *

    - * calling LimitExceededException with closecode TOOBIG - */ - public LimitExceededException() { - this(Integer.MAX_VALUE); - } + /** + * constructor for a LimitExceededException + *

    + * calling LimitExceededException with closecode TOOBIG + */ + public LimitExceededException() { + this(Integer.MAX_VALUE); + } - /** - * constructor for a LimitExceededException - *

    - * calling InvalidDataException with closecode TOOBIG - */ - public LimitExceededException(int limit) { - super( CloseFrame.TOOBIG); - this.limit = limit; - } + /** + * constructor for a LimitExceededException + *

    + * calling InvalidDataException with closecode TOOBIG + */ + public LimitExceededException(int limit) { + super(CloseFrame.TOOBIG); + this.limit = limit; + } - /** - * constructor for a LimitExceededException - *

    - * calling InvalidDataException with closecode TOOBIG - */ - public LimitExceededException(String s, int limit) { - super( CloseFrame.TOOBIG, s); - this.limit = limit; - } + /** + * constructor for a LimitExceededException + *

    + * calling InvalidDataException with closecode TOOBIG + */ + public LimitExceededException(String s, int limit) { + super(CloseFrame.TOOBIG, s); + this.limit = limit; + } - /** - * constructor for a LimitExceededException - *

    - * calling InvalidDataException with closecode TOOBIG - * - * @param s the detail message. - */ - public LimitExceededException(String s) { - this(s, Integer.MAX_VALUE); - } + /** + * constructor for a LimitExceededException + *

    + * calling InvalidDataException with closecode TOOBIG + * + * @param s the detail message. + */ + public LimitExceededException(String s) { + this(s, Integer.MAX_VALUE); + } - /** - * Get the limit which was hit so this exception was caused - * @return the limit as int - */ - public int getLimit() { - return limit; - } + /** + * Get the limit which was hit so this exception was caused + * + * @return the limit as int + */ + public int getLimit() { + return limit; + } } diff --git a/src/main/java/org/java_websocket/exceptions/NotSendableException.java b/src/main/java/org/java_websocket/exceptions/NotSendableException.java index 4ec9a1a64..fbacca9c7 100644 --- a/src/main/java/org/java_websocket/exceptions/NotSendableException.java +++ b/src/main/java/org/java_websocket/exceptions/NotSendableException.java @@ -30,37 +30,37 @@ */ public class NotSendableException extends RuntimeException { - /** - * Serializable - */ - private static final long serialVersionUID = -6468967874576651628L; + /** + * Serializable + */ + private static final long serialVersionUID = -6468967874576651628L; - /** - * constructor for a NotSendableException - * - * @param s the detail message. - */ - public NotSendableException(String s) { - super(s); - } + /** + * constructor for a NotSendableException + * + * @param s the detail message. + */ + public NotSendableException(String s) { + super(s); + } - /** - * constructor for a NotSendableException - * - * @param t the throwable causing this exception. - */ - public NotSendableException(Throwable t) { - super(t); - } + /** + * constructor for a NotSendableException + * + * @param t the throwable causing this exception. + */ + public NotSendableException(Throwable t) { + super(t); + } - /** - * constructor for a NotSendableException - * - * @param s the detail message. - * @param t the throwable causing this exception. - */ - public NotSendableException(String s, Throwable t) { - super(s, t); - } + /** + * constructor for a NotSendableException + * + * @param s the detail message. + * @param t the throwable causing this exception. + */ + public NotSendableException(String s, Throwable t) { + super(s, t); + } } diff --git a/src/main/java/org/java_websocket/exceptions/WebsocketNotConnectedException.java b/src/main/java/org/java_websocket/exceptions/WebsocketNotConnectedException.java index 3818af06a..082f0bd5f 100644 --- a/src/main/java/org/java_websocket/exceptions/WebsocketNotConnectedException.java +++ b/src/main/java/org/java_websocket/exceptions/WebsocketNotConnectedException.java @@ -30,8 +30,8 @@ */ public class WebsocketNotConnectedException extends RuntimeException { - /** - * Serializable - */ - private static final long serialVersionUID = -785314021592982715L; + /** + * Serializable + */ + private static final long serialVersionUID = -785314021592982715L; } diff --git a/src/main/java/org/java_websocket/exceptions/WrappedIOException.java b/src/main/java/org/java_websocket/exceptions/WrappedIOException.java index 4603ad85a..f8f1b1a1c 100644 --- a/src/main/java/org/java_websocket/exceptions/WrappedIOException.java +++ b/src/main/java/org/java_websocket/exceptions/WrappedIOException.java @@ -31,44 +31,49 @@ import java.io.IOException; /** - * Exception to wrap an IOException and include information about the websocket which had the exception + * Exception to wrap an IOException and include information about the websocket which had the + * exception + * * @since 1.4.1 */ public class WrappedIOException extends Exception { - /** - * The websocket where the IOException happened - */ - private final WebSocket connection; + /** + * The websocket where the IOException happened + */ + private final WebSocket connection; - /** - * The IOException - */ - private final IOException ioException; + /** + * The IOException + */ + private final IOException ioException; - /** - * Wrapp an IOException and include the websocket - * @param connection the websocket where the IOException happened - * @param ioException the IOException - */ - public WrappedIOException(WebSocket connection, IOException ioException) { - this.connection = connection; - this.ioException = ioException; - } + /** + * Wrapp an IOException and include the websocket + * + * @param connection the websocket where the IOException happened + * @param ioException the IOException + */ + public WrappedIOException(WebSocket connection, IOException ioException) { + this.connection = connection; + this.ioException = ioException; + } - /** - * The websocket where the IOException happened - * @return the websocket for the wrapped IOException - */ - public WebSocket getConnection() { - return connection; - } + /** + * The websocket where the IOException happened + * + * @return the websocket for the wrapped IOException + */ + public WebSocket getConnection() { + return connection; + } - /** - * The wrapped IOException - * @return IOException which is wrapped - */ - public IOException getIOException() { - return ioException; - } + /** + * The wrapped IOException + * + * @return IOException which is wrapped + */ + public IOException getIOException() { + return ioException; + } } diff --git a/src/main/java/org/java_websocket/exceptions/package-info.java b/src/main/java/org/java_websocket/exceptions/package-info.java index 2b5d13621..2972d3c8a 100644 --- a/src/main/java/org/java_websocket/exceptions/package-info.java +++ b/src/main/java/org/java_websocket/exceptions/package-info.java @@ -24,6 +24,7 @@ */ /** - * This package encapsulates all implementations in relation with the exceptions thrown in this lib. + * This package encapsulates all implementations in relation with the exceptions thrown in this + * lib. */ package org.java_websocket.exceptions; \ No newline at end of file diff --git a/src/main/java/org/java_websocket/extensions/CompressionExtension.java b/src/main/java/org/java_websocket/extensions/CompressionExtension.java index 703a7d0cf..408a1588a 100644 --- a/src/main/java/org/java_websocket/extensions/CompressionExtension.java +++ b/src/main/java/org/java_websocket/extensions/CompressionExtension.java @@ -33,17 +33,23 @@ /** * Implementation for a compression extension specified by https://tools.ietf.org/html/rfc7692 + * * @since 1.3.5 */ public abstract class CompressionExtension extends DefaultExtension { - @Override - public void isFrameValid( Framedata inputFrame ) throws InvalidDataException { - if(( inputFrame instanceof DataFrame ) && ( inputFrame.isRSV2() || inputFrame.isRSV3() )) { - throw new InvalidFrameException( "bad rsv RSV1: " + inputFrame.isRSV1() + " RSV2: " + inputFrame.isRSV2() + " RSV3: " + inputFrame.isRSV3() ); - } - if(( inputFrame instanceof ControlFrame ) && ( inputFrame.isRSV1() || inputFrame.isRSV2() || inputFrame.isRSV3() )) { - throw new InvalidFrameException( "bad rsv RSV1: " + inputFrame.isRSV1() + " RSV2: " + inputFrame.isRSV2() + " RSV3: " + inputFrame.isRSV3() ); - } - } + @Override + public void isFrameValid(Framedata inputFrame) throws InvalidDataException { + if ((inputFrame instanceof DataFrame) && (inputFrame.isRSV2() || inputFrame.isRSV3())) { + throw new InvalidFrameException( + "bad rsv RSV1: " + inputFrame.isRSV1() + " RSV2: " + inputFrame.isRSV2() + " RSV3: " + + inputFrame.isRSV3()); + } + if ((inputFrame instanceof ControlFrame) && (inputFrame.isRSV1() || inputFrame.isRSV2() + || inputFrame.isRSV3())) { + throw new InvalidFrameException( + "bad rsv RSV1: " + inputFrame.isRSV1() + " RSV2: " + inputFrame.isRSV2() + " RSV3: " + + inputFrame.isRSV3()); + } + } } diff --git a/src/main/java/org/java_websocket/extensions/DefaultExtension.java b/src/main/java/org/java_websocket/extensions/DefaultExtension.java index 4bad78b45..3892990c1 100644 --- a/src/main/java/org/java_websocket/extensions/DefaultExtension.java +++ b/src/main/java/org/java_websocket/extensions/DefaultExtension.java @@ -31,71 +31,73 @@ /** * Class which represents the normal websocket implementation specified by rfc6455. - * + *

    * This is a fallback and will always be available for a Draft_6455 * * @since 1.3.5 */ public class DefaultExtension implements IExtension { - @Override - public void decodeFrame( Framedata inputFrame ) throws InvalidDataException { - //Nothing to do here - } + @Override + public void decodeFrame(Framedata inputFrame) throws InvalidDataException { + //Nothing to do here + } - @Override - public void encodeFrame( Framedata inputFrame ) { - //Nothing to do here - } + @Override + public void encodeFrame(Framedata inputFrame) { + //Nothing to do here + } - @Override - public boolean acceptProvidedExtensionAsServer( String inputExtension ) { - return true; - } + @Override + public boolean acceptProvidedExtensionAsServer(String inputExtension) { + return true; + } - @Override - public boolean acceptProvidedExtensionAsClient( String inputExtension ) { - return true; - } + @Override + public boolean acceptProvidedExtensionAsClient(String inputExtension) { + return true; + } - @Override - public void isFrameValid( Framedata inputFrame ) throws InvalidDataException { - if( inputFrame.isRSV1() || inputFrame.isRSV2() || inputFrame.isRSV3() ) { - throw new InvalidFrameException( "bad rsv RSV1: " + inputFrame.isRSV1() + " RSV2: " + inputFrame.isRSV2() + " RSV3: " + inputFrame.isRSV3() ); - } - } + @Override + public void isFrameValid(Framedata inputFrame) throws InvalidDataException { + if (inputFrame.isRSV1() || inputFrame.isRSV2() || inputFrame.isRSV3()) { + throw new InvalidFrameException( + "bad rsv RSV1: " + inputFrame.isRSV1() + " RSV2: " + inputFrame.isRSV2() + " RSV3: " + + inputFrame.isRSV3()); + } + } - @Override - public String getProvidedExtensionAsClient() { - return ""; - } + @Override + public String getProvidedExtensionAsClient() { + return ""; + } - @Override - public String getProvidedExtensionAsServer() { - return ""; - } + @Override + public String getProvidedExtensionAsServer() { + return ""; + } - @Override - public IExtension copyInstance() { - return new DefaultExtension(); - } + @Override + public IExtension copyInstance() { + return new DefaultExtension(); + } - public void reset() { - //Nothing to do here. No internal stats. - } + public void reset() { + //Nothing to do here. No internal stats. + } - @Override - public String toString() { - return getClass().getSimpleName(); - } + @Override + public String toString() { + return getClass().getSimpleName(); + } - @Override - public int hashCode() { - return getClass().hashCode(); - } + @Override + public int hashCode() { + return getClass().hashCode(); + } - @Override - public boolean equals( Object o ) { - return this == o || o != null && getClass() == o.getClass(); - } + @Override + public boolean equals(Object o) { + return this == o || o != null && getClass() == o.getClass(); + } } diff --git a/src/main/java/org/java_websocket/extensions/ExtensionRequestData.java b/src/main/java/org/java_websocket/extensions/ExtensionRequestData.java index 639dd802b..8d46d9566 100644 --- a/src/main/java/org/java_websocket/extensions/ExtensionRequestData.java +++ b/src/main/java/org/java_websocket/extensions/ExtensionRequestData.java @@ -5,48 +5,49 @@ public class ExtensionRequestData { - public static String EMPTY_VALUE = ""; + public static String EMPTY_VALUE = ""; - private Map extensionParameters; - private String extensionName; + private Map extensionParameters; + private String extensionName; - private ExtensionRequestData() { - extensionParameters = new LinkedHashMap(); - } - - public static ExtensionRequestData parseExtensionRequest(String extensionRequest) { - ExtensionRequestData extensionData = new ExtensionRequestData(); - String[] parts = extensionRequest.split(";"); - extensionData.extensionName = parts[0].trim(); + private ExtensionRequestData() { + extensionParameters = new LinkedHashMap(); + } - for(int i = 1; i < parts.length; i++) { - String[] keyValue = parts[i].split("="); - String value = EMPTY_VALUE; + public static ExtensionRequestData parseExtensionRequest(String extensionRequest) { + ExtensionRequestData extensionData = new ExtensionRequestData(); + String[] parts = extensionRequest.split(";"); + extensionData.extensionName = parts[0].trim(); - // Some parameters don't take a value. For those that do, parse the value. - if(keyValue.length > 1) { - String tempValue = keyValue[1].trim(); + for (int i = 1; i < parts.length; i++) { + String[] keyValue = parts[i].split("="); + String value = EMPTY_VALUE; - // If the value is wrapped in quotes, just get the data between them. - if((tempValue.startsWith("\"") && tempValue.endsWith("\"")) - || (tempValue.startsWith("'") && tempValue.endsWith("'")) - && tempValue.length() > 2) - tempValue = tempValue.substring(1, tempValue.length() - 1); + // Some parameters don't take a value. For those that do, parse the value. + if (keyValue.length > 1) { + String tempValue = keyValue[1].trim(); - value = tempValue; - } - - extensionData.extensionParameters.put(keyValue[0].trim(), value); + // If the value is wrapped in quotes, just get the data between them. + if ((tempValue.startsWith("\"") && tempValue.endsWith("\"")) + || (tempValue.startsWith("'") && tempValue.endsWith("'")) + && tempValue.length() > 2) { + tempValue = tempValue.substring(1, tempValue.length() - 1); } - return extensionData; - } + value = tempValue; + } - public String getExtensionName() { - return extensionName; + extensionData.extensionParameters.put(keyValue[0].trim(), value); } - public Map getExtensionParameters() { - return extensionParameters; - } + return extensionData; + } + + public String getExtensionName() { + return extensionName; + } + + public Map getExtensionParameters() { + return extensionParameters; + } } diff --git a/src/main/java/org/java_websocket/extensions/IExtension.java b/src/main/java/org/java_websocket/extensions/IExtension.java index b7236f2d8..02bf581a4 100644 --- a/src/main/java/org/java_websocket/extensions/IExtension.java +++ b/src/main/java/org/java_websocket/extensions/IExtension.java @@ -30,95 +30,109 @@ /** * Interface which specifies all required methods to develop a websocket extension. + * * @since 1.3.5 */ public interface IExtension { - /** - * Decode a frame with a extension specific algorithm. - * The algorithm is subject to be implemented by the specific extension. - * The resulting frame will be used in the application - * - * @param inputFrame the frame, which has do be decoded to be used in the application - * @throws InvalidDataException Throw InvalidDataException if the received frame is not correctly implemented by the other endpoint or there are other protocol errors/decoding errors - * @since 1.3.5 - */ - void decodeFrame( Framedata inputFrame ) throws InvalidDataException; + /** + * Decode a frame with a extension specific algorithm. The algorithm is subject to be implemented + * by the specific extension. The resulting frame will be used in the application + * + * @param inputFrame the frame, which has do be decoded to be used in the application + * @throws InvalidDataException Throw InvalidDataException if the received frame is not correctly + * implemented by the other endpoint or there are other protocol + * errors/decoding errors + * @since 1.3.5 + */ + void decodeFrame(Framedata inputFrame) throws InvalidDataException; - /** - * Encode a frame with a extension specific algorithm. - * The algorithm is subject to be implemented by the specific extension. - * The resulting frame will be send to the other endpoint. - * - * @param inputFrame the frame, which has do be encoded to be used on the other endpoint - * @since 1.3.5 - */ - void encodeFrame( Framedata inputFrame ); + /** + * Encode a frame with a extension specific algorithm. The algorithm is subject to be implemented + * by the specific extension. The resulting frame will be send to the other endpoint. + * + * @param inputFrame the frame, which has do be encoded to be used on the other endpoint + * @since 1.3.5 + */ + void encodeFrame(Framedata inputFrame); - /** - * Check if the received Sec-WebSocket-Extensions header field contains a offer for the specific extension if the endpoint is in the role of a server - * - * @param inputExtensionHeader the received Sec-WebSocket-Extensions header field offered by the other endpoint - * @return true, if the offer does fit to this specific extension - * @since 1.3.5 - */ - boolean acceptProvidedExtensionAsServer( String inputExtensionHeader ); + /** + * Check if the received Sec-WebSocket-Extensions header field contains a offer for the specific + * extension if the endpoint is in the role of a server + * + * @param inputExtensionHeader the received Sec-WebSocket-Extensions header field offered by the + * other endpoint + * @return true, if the offer does fit to this specific extension + * @since 1.3.5 + */ + boolean acceptProvidedExtensionAsServer(String inputExtensionHeader); - /** - * Check if the received Sec-WebSocket-Extensions header field contains a offer for the specific extension if the endpoint is in the role of a client - * - * @param inputExtensionHeader the received Sec-WebSocket-Extensions header field offered by the other endpoint - * @return true, if the offer does fit to this specific extension - * @since 1.3.5 - */ - boolean acceptProvidedExtensionAsClient( String inputExtensionHeader ); + /** + * Check if the received Sec-WebSocket-Extensions header field contains a offer for the specific + * extension if the endpoint is in the role of a client + * + * @param inputExtensionHeader the received Sec-WebSocket-Extensions header field offered by the + * other endpoint + * @return true, if the offer does fit to this specific extension + * @since 1.3.5 + */ + boolean acceptProvidedExtensionAsClient(String inputExtensionHeader); - /** - * Check if the received frame is correctly implemented by the other endpoint and there are no specification errors (like wrongly set RSV) - * - * @param inputFrame the received frame - * @throws InvalidDataException Throw InvalidDataException if the received frame is not correctly implementing the specification for the specific extension - * @since 1.3.5 - */ - void isFrameValid( Framedata inputFrame ) throws InvalidDataException; + /** + * Check if the received frame is correctly implemented by the other endpoint and there are no + * specification errors (like wrongly set RSV) + * + * @param inputFrame the received frame + * @throws InvalidDataException Throw InvalidDataException if the received frame is not correctly + * implementing the specification for the specific extension + * @since 1.3.5 + */ + void isFrameValid(Framedata inputFrame) throws InvalidDataException; - /** - * Return the specific Sec-WebSocket-Extensions header offer for this extension if the endpoint is in the role of a client. - * If the extension returns an empty string (""), the offer will not be included in the handshake. - * - * @return the specific Sec-WebSocket-Extensions header for this extension - * @since 1.3.5 - */ - String getProvidedExtensionAsClient(); + /** + * Return the specific Sec-WebSocket-Extensions header offer for this extension if the endpoint is + * in the role of a client. If the extension returns an empty string (""), the offer will not be + * included in the handshake. + * + * @return the specific Sec-WebSocket-Extensions header for this extension + * @since 1.3.5 + */ + String getProvidedExtensionAsClient(); - /** - * Return the specific Sec-WebSocket-Extensions header offer for this extension if the endpoint is in the role of a server. - * If the extension returns an empty string (""), the offer will not be included in the handshake. - * - * @return the specific Sec-WebSocket-Extensions header for this extension - * @since 1.3.5 - */ - String getProvidedExtensionAsServer(); + /** + * Return the specific Sec-WebSocket-Extensions header offer for this extension if the endpoint is + * in the role of a server. If the extension returns an empty string (""), the offer will not be + * included in the handshake. + * + * @return the specific Sec-WebSocket-Extensions header for this extension + * @since 1.3.5 + */ + String getProvidedExtensionAsServer(); - /** - * Extensions must only be by one websocket at all. To prevent extensions to be used more than once the Websocket implementation should call this method in order to create a new usable version of a given extension instance.
    - * The copy can be safely used in conjunction with a new websocket connection. - * @return a copy of the extension - * @since 1.3.5 - */ - IExtension copyInstance(); + /** + * Extensions must only be by one websocket at all. To prevent extensions to be used more than + * once the Websocket implementation should call this method in order to create a new usable + * version of a given extension instance.
    The copy can be safely used in conjunction with a + * new websocket connection. + * + * @return a copy of the extension + * @since 1.3.5 + */ + IExtension copyInstance(); - /** - * Cleaning up internal stats when the draft gets reset. - * @since 1.3.5 - */ - void reset(); + /** + * Cleaning up internal stats when the draft gets reset. + * + * @since 1.3.5 + */ + void reset(); - /** - * Return a string which should contain the class name as well as additional information about the current configurations for this extension (DEBUG purposes) - * - * @return a string containing the class name as well as additional information - * @since 1.3.5 - */ - String toString(); + /** + * Return a string which should contain the class name as well as additional information about the + * current configurations for this extension (DEBUG purposes) + * + * @return a string containing the class name as well as additional information + * @since 1.3.5 + */ + String toString(); } diff --git a/src/main/java/org/java_websocket/extensions/package-info.java b/src/main/java/org/java_websocket/extensions/package-info.java index 2a3338b7c..251cbdf9f 100644 --- a/src/main/java/org/java_websocket/extensions/package-info.java +++ b/src/main/java/org/java_websocket/extensions/package-info.java @@ -24,6 +24,7 @@ */ /** - * This package encapsulates all interfaces and implementations in relation with the WebSocket Sec-WebSocket-Extensions. + * This package encapsulates all interfaces and implementations in relation with the WebSocket + * Sec-WebSocket-Extensions. */ package org.java_websocket.extensions; \ No newline at end of file diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index d5f1d95b4..6e414636f 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -23,107 +23,106 @@ import java.util.zip.Inflater; /** - * PerMessage Deflate Extension (7. The "permessage-deflate" Extension in + * PerMessage Deflate Extension (7. The + * "permessage-deflate" Extension in * RFC 7692). * - * @see 7. The "permessage-deflate" Extension in RFC 7692 + * @see 7. The "permessage-deflate" + * Extension in RFC 7692 */ public class PerMessageDeflateExtension extends CompressionExtension { - // Name of the extension as registered by IETF https://tools.ietf.org/html/rfc7692#section-9. - private static final String EXTENSION_REGISTERED_NAME = "permessage-deflate"; - // Below values are defined for convenience. They are not used in the compression/decompression phase. - // They may be needed during the extension-negotiation offer in the future. - private static final String SERVER_NO_CONTEXT_TAKEOVER = "server_no_context_takeover"; - private static final String CLIENT_NO_CONTEXT_TAKEOVER = "client_no_context_takeover"; - private static final String SERVER_MAX_WINDOW_BITS = "server_max_window_bits"; - private static final String CLIENT_MAX_WINDOW_BITS = "client_max_window_bits"; - private static final int serverMaxWindowBits = 1 << 15; - private static final int clientMaxWindowBits = 1 << 15; - private static final byte[] TAIL_BYTES = { (byte)0x00, (byte)0x00, (byte)0xFF, (byte)0xFF }; - private static final int BUFFER_SIZE = 1 << 10; - - private boolean serverNoContextTakeover = true; - private boolean clientNoContextTakeover = false; - - // For WebSocketServers, this variable holds the extension parameters that the peer client has requested. - // For WebSocketClients, this variable holds the extension parameters that client himself has requested. - private Map requestedParameters = new LinkedHashMap(); - - private Inflater inflater = new Inflater(true); - private Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); - - public Inflater getInflater() { - return inflater; + // Name of the extension as registered by IETF https://tools.ietf.org/html/rfc7692#section-9. + private static final String EXTENSION_REGISTERED_NAME = "permessage-deflate"; + // Below values are defined for convenience. They are not used in the compression/decompression phase. + // They may be needed during the extension-negotiation offer in the future. + private static final String SERVER_NO_CONTEXT_TAKEOVER = "server_no_context_takeover"; + private static final String CLIENT_NO_CONTEXT_TAKEOVER = "client_no_context_takeover"; + private static final String SERVER_MAX_WINDOW_BITS = "server_max_window_bits"; + private static final String CLIENT_MAX_WINDOW_BITS = "client_max_window_bits"; + private static final int serverMaxWindowBits = 1 << 15; + private static final int clientMaxWindowBits = 1 << 15; + private static final byte[] TAIL_BYTES = {(byte) 0x00, (byte) 0x00, (byte) 0xFF, (byte) 0xFF}; + private static final int BUFFER_SIZE = 1 << 10; + + private boolean serverNoContextTakeover = true; + private boolean clientNoContextTakeover = false; + + // For WebSocketServers, this variable holds the extension parameters that the peer client has requested. + // For WebSocketClients, this variable holds the extension parameters that client himself has requested. + private Map requestedParameters = new LinkedHashMap(); + + private Inflater inflater = new Inflater(true); + private Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); + + public Inflater getInflater() { + return inflater; + } + + public void setInflater(Inflater inflater) { + this.inflater = inflater; + } + + public Deflater getDeflater() { + return deflater; + } + + public void setDeflater(Deflater deflater) { + this.deflater = deflater; + } + + /** + * @return serverNoContextTakeover + */ + public boolean isServerNoContextTakeover() { + return serverNoContextTakeover; + } + + /** + * @param serverNoContextTakeover + */ + public void setServerNoContextTakeover(boolean serverNoContextTakeover) { + this.serverNoContextTakeover = serverNoContextTakeover; + } + + /** + * @return clientNoContextTakeover + */ + public boolean isClientNoContextTakeover() { + return clientNoContextTakeover; + } + + /** + * @param clientNoContextTakeover + */ + public void setClientNoContextTakeover(boolean clientNoContextTakeover) { + this.clientNoContextTakeover = clientNoContextTakeover; + } + + /* + An endpoint uses the following algorithm to decompress a message. + 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the + payload of the message. + 2. Decompress the resulting data using DEFLATE. + See, https://tools.ietf.org/html/rfc7692#section-7.2.2 + */ + @Override + public void decodeFrame(Framedata inputFrame) throws InvalidDataException { + // Only DataFrames can be decompressed. + if (!(inputFrame instanceof DataFrame)) { + return; } - public void setInflater(Inflater inflater) { - this.inflater = inflater; + // RSV1 bit must be set only for the first frame. + if (inputFrame.getOpcode() == Opcode.CONTINUOUS && inputFrame.isRSV1()) { + throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, + "RSV1 bit can only be set for the first frame."); } - public Deflater getDeflater() { - return deflater; - } - - public void setDeflater(Deflater deflater) { - this.deflater = deflater; - } - - /** - * - * @return serverNoContextTakeover - */ - public boolean isServerNoContextTakeover() - { - return serverNoContextTakeover; - } - - /** - * - * @param serverNoContextTakeover - */ - public void setServerNoContextTakeover(boolean serverNoContextTakeover) { - this.serverNoContextTakeover = serverNoContextTakeover; - } - - /** - * - * @return clientNoContextTakeover - */ - public boolean isClientNoContextTakeover() - { - return clientNoContextTakeover; - } - - /** - * - * @param clientNoContextTakeover - */ - public void setClientNoContextTakeover(boolean clientNoContextTakeover) { - this.clientNoContextTakeover = clientNoContextTakeover; - } - - /* - An endpoint uses the following algorithm to decompress a message. - 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the - payload of the message. - 2. Decompress the resulting data using DEFLATE. - See, https://tools.ietf.org/html/rfc7692#section-7.2.2 - */ - @Override - public void decodeFrame(Framedata inputFrame) throws InvalidDataException { - // Only DataFrames can be decompressed. - if (!(inputFrame instanceof DataFrame)) - return; - - // RSV1 bit must be set only for the first frame. - if (inputFrame.getOpcode() == Opcode.CONTINUOUS && inputFrame.isRSV1()) - throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "RSV1 bit can only be set for the first frame."); - - // Decompressed output buffer. - ByteArrayOutputStream output = new ByteArrayOutputStream(); - try { - decompress(inputFrame.getPayloadData().array(), output); + // Decompressed output buffer. + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try { + decompress(inputFrame.getPayloadData().array(), output); /* If a message is "first fragmented and then compressed", as this project does, then the inflater @@ -133,67 +132,73 @@ We can check the getRemaining() method to see whether the data we supplied has b And if not, we just reset the inflater and decompress again. Note that this behavior doesn't occur if the message is "first compressed and then fragmented". */ - if (inflater.getRemaining() > 0) { - inflater = new Inflater(true); - decompress(inputFrame.getPayloadData().array(), output); - } - - if (inputFrame.isFin()) { - decompress(TAIL_BYTES, output); - // If context takeover is disabled, inflater can be reset. - if (clientNoContextTakeover) - inflater = new Inflater(true); - } - } catch (DataFormatException e) { - throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, e.getMessage()); + if (inflater.getRemaining() > 0) { + inflater = new Inflater(true); + decompress(inputFrame.getPayloadData().array(), output); + } + + if (inputFrame.isFin()) { + decompress(TAIL_BYTES, output); + // If context takeover is disabled, inflater can be reset. + if (clientNoContextTakeover) { + inflater = new Inflater(true); } + } + } catch (DataFormatException e) { + throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, e.getMessage()); + } - // RSV1 bit must be cleared after decoding, so that other extensions don't throw an exception. - if (inputFrame.isRSV1()) - ((DataFrame) inputFrame).setRSV1(false); + // RSV1 bit must be cleared after decoding, so that other extensions don't throw an exception. + if (inputFrame.isRSV1()) { + ((DataFrame) inputFrame).setRSV1(false); + } - // Set frames payload to the new decompressed data. - ((FramedataImpl1) inputFrame).setPayload(ByteBuffer.wrap(output.toByteArray(), 0, output.size())); + // Set frames payload to the new decompressed data. + ((FramedataImpl1) inputFrame) + .setPayload(ByteBuffer.wrap(output.toByteArray(), 0, output.size())); + } + + /** + * @param data the bytes of data + * @param outputBuffer the output stream + * @throws DataFormatException + */ + private void decompress(byte[] data, ByteArrayOutputStream outputBuffer) + throws DataFormatException { + inflater.setInput(data); + byte[] buffer = new byte[BUFFER_SIZE]; + + int bytesInflated; + while ((bytesInflated = inflater.inflate(buffer)) > 0) { + outputBuffer.write(buffer, 0, bytesInflated); } + } - /** - * - * @param data the bytes of data - * @param outputBuffer the output stream - * @throws DataFormatException - */ - private void decompress(byte[] data, ByteArrayOutputStream outputBuffer) throws DataFormatException { - inflater.setInput(data); - byte[] buffer = new byte[BUFFER_SIZE]; - - int bytesInflated; - while ((bytesInflated = inflater.inflate(buffer)) > 0) { - outputBuffer.write(buffer, 0, bytesInflated); - } + @Override + public void encodeFrame(Framedata inputFrame) { + // Only DataFrames can be decompressed. + if (!(inputFrame instanceof DataFrame)) { + return; } - @Override - public void encodeFrame(Framedata inputFrame) { - // Only DataFrames can be decompressed. - if (!(inputFrame instanceof DataFrame)) - return; - - // Only the first frame's RSV1 must be set. - if (!(inputFrame instanceof ContinuousFrame)) - ((DataFrame) inputFrame).setRSV1(true); - - deflater.setInput(inputFrame.getPayloadData().array()); - // Compressed output buffer. - ByteArrayOutputStream output = new ByteArrayOutputStream(); - // Temporary buffer to hold compressed output. - byte[] buffer = new byte[1024]; - int bytesCompressed; - while ((bytesCompressed = deflater.deflate(buffer, 0, buffer.length, Deflater.SYNC_FLUSH)) > 0) { - output.write(buffer, 0, bytesCompressed); - } + // Only the first frame's RSV1 must be set. + if (!(inputFrame instanceof ContinuousFrame)) { + ((DataFrame) inputFrame).setRSV1(true); + } - byte outputBytes[] = output.toByteArray(); - int outputLength = outputBytes.length; + deflater.setInput(inputFrame.getPayloadData().array()); + // Compressed output buffer. + ByteArrayOutputStream output = new ByteArrayOutputStream(); + // Temporary buffer to hold compressed output. + byte[] buffer = new byte[1024]; + int bytesCompressed; + while ((bytesCompressed = deflater.deflate(buffer, 0, buffer.length, Deflater.SYNC_FLUSH)) + > 0) { + output.write(buffer, 0, bytesCompressed); + } + + byte outputBytes[] = output.toByteArray(); + int outputLength = outputBytes.length; /* https://tools.ietf.org/html/rfc7692#section-7.2.1 states that if the final fragment's compressed @@ -201,110 +206,122 @@ public void encodeFrame(Framedata inputFrame) { To simulate removal, we just pass 4 bytes less to the new payload if the frame is final and outputBytes ends with 0x00 0x00 0xff 0xff. */ - if (inputFrame.isFin()) { - if (endsWithTail(outputBytes)) - outputLength -= TAIL_BYTES.length; - - if (serverNoContextTakeover) { - deflater.end(); - deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); - } - } - - // Set frames payload to the new compressed data. - ((FramedataImpl1) inputFrame).setPayload(ByteBuffer.wrap(outputBytes, 0, outputLength)); - } - - /** - * - * @param data the bytes of data - * @return true if the data is OK - */ - private boolean endsWithTail(byte[] data) { - if (data.length < 4) - return false; - - int length = data.length; - for (int i = 0; i < TAIL_BYTES.length; i++) { - if (TAIL_BYTES[i] != data[length - TAIL_BYTES.length + i]) - return false; - } - - return true; + if (inputFrame.isFin()) { + if (endsWithTail(outputBytes)) { + outputLength -= TAIL_BYTES.length; + } + + if (serverNoContextTakeover) { + deflater.end(); + deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); + } } - @Override - public boolean acceptProvidedExtensionAsServer(String inputExtension) { - String[] requestedExtensions = inputExtension.split(","); - for (String extension : requestedExtensions) { - ExtensionRequestData extensionData = ExtensionRequestData.parseExtensionRequest(extension); - if (!EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extensionData.getExtensionName())) - continue; - - // Holds parameters that peer client has sent. - Map headers = extensionData.getExtensionParameters(); - requestedParameters.putAll(headers); - if (requestedParameters.containsKey(CLIENT_NO_CONTEXT_TAKEOVER)) - clientNoContextTakeover = true; - - return true; - } - - return false; + // Set frames payload to the new compressed data. + ((FramedataImpl1) inputFrame).setPayload(ByteBuffer.wrap(outputBytes, 0, outputLength)); + } + + /** + * @param data the bytes of data + * @return true if the data is OK + */ + private boolean endsWithTail(byte[] data) { + if (data.length < 4) { + return false; } - @Override - public boolean acceptProvidedExtensionAsClient(String inputExtension) { - String[] requestedExtensions = inputExtension.split(","); - for (String extension : requestedExtensions) { - ExtensionRequestData extensionData = ExtensionRequestData.parseExtensionRequest(extension); - if (!EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extensionData.getExtensionName())) - continue; - - // Holds parameters that are sent by the server, as a response to our initial extension request. - Map headers = extensionData.getExtensionParameters(); - // After this point, parameters that the server sent back can be configured, but we don't use them for now. - return true; - } - + int length = data.length; + for (int i = 0; i < TAIL_BYTES.length; i++) { + if (TAIL_BYTES[i] != data[length - TAIL_BYTES.length + i]) { return false; + } } - @Override - public String getProvidedExtensionAsClient() { - requestedParameters.put(CLIENT_NO_CONTEXT_TAKEOVER, ExtensionRequestData.EMPTY_VALUE); - requestedParameters.put(SERVER_NO_CONTEXT_TAKEOVER, ExtensionRequestData.EMPTY_VALUE); - - return EXTENSION_REGISTERED_NAME + "; " + SERVER_NO_CONTEXT_TAKEOVER + "; " + CLIENT_NO_CONTEXT_TAKEOVER; + return true; + } + + @Override + public boolean acceptProvidedExtensionAsServer(String inputExtension) { + String[] requestedExtensions = inputExtension.split(","); + for (String extension : requestedExtensions) { + ExtensionRequestData extensionData = ExtensionRequestData.parseExtensionRequest(extension); + if (!EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extensionData.getExtensionName())) { + continue; + } + + // Holds parameters that peer client has sent. + Map headers = extensionData.getExtensionParameters(); + requestedParameters.putAll(headers); + if (requestedParameters.containsKey(CLIENT_NO_CONTEXT_TAKEOVER)) { + clientNoContextTakeover = true; + } + + return true; } - @Override - public String getProvidedExtensionAsServer() { - return EXTENSION_REGISTERED_NAME - + "; " + SERVER_NO_CONTEXT_TAKEOVER - + (clientNoContextTakeover ? "; " + CLIENT_NO_CONTEXT_TAKEOVER : ""); + return false; + } + + @Override + public boolean acceptProvidedExtensionAsClient(String inputExtension) { + String[] requestedExtensions = inputExtension.split(","); + for (String extension : requestedExtensions) { + ExtensionRequestData extensionData = ExtensionRequestData.parseExtensionRequest(extension); + if (!EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extensionData.getExtensionName())) { + continue; + } + + // Holds parameters that are sent by the server, as a response to our initial extension request. + Map headers = extensionData.getExtensionParameters(); + // After this point, parameters that the server sent back can be configured, but we don't use them for now. + return true; } - @Override - public IExtension copyInstance() { - return new PerMessageDeflateExtension(); + return false; + } + + @Override + public String getProvidedExtensionAsClient() { + requestedParameters.put(CLIENT_NO_CONTEXT_TAKEOVER, ExtensionRequestData.EMPTY_VALUE); + requestedParameters.put(SERVER_NO_CONTEXT_TAKEOVER, ExtensionRequestData.EMPTY_VALUE); + + return EXTENSION_REGISTERED_NAME + "; " + SERVER_NO_CONTEXT_TAKEOVER + "; " + + CLIENT_NO_CONTEXT_TAKEOVER; + } + + @Override + public String getProvidedExtensionAsServer() { + return EXTENSION_REGISTERED_NAME + + "; " + SERVER_NO_CONTEXT_TAKEOVER + + (clientNoContextTakeover ? "; " + CLIENT_NO_CONTEXT_TAKEOVER : ""); + } + + @Override + public IExtension copyInstance() { + return new PerMessageDeflateExtension(); + } + + /** + * This extension requires the RSV1 bit to be set only for the first frame. If the frame is type + * is CONTINUOUS, RSV1 bit must be unset. + */ + @Override + public void isFrameValid(Framedata inputFrame) throws InvalidDataException { + if ((inputFrame instanceof TextFrame || inputFrame instanceof BinaryFrame) && !inputFrame + .isRSV1()) { + throw new InvalidFrameException("RSV1 bit must be set for DataFrames."); } - - /** - * This extension requires the RSV1 bit to be set only for the first frame. - * If the frame is type is CONTINUOUS, RSV1 bit must be unset. - */ - @Override - public void isFrameValid(Framedata inputFrame) throws InvalidDataException { - if ((inputFrame instanceof TextFrame || inputFrame instanceof BinaryFrame) && !inputFrame.isRSV1()) - throw new InvalidFrameException("RSV1 bit must be set for DataFrames."); - if ((inputFrame instanceof ContinuousFrame) && (inputFrame.isRSV1() || inputFrame.isRSV2() || inputFrame.isRSV3())) - throw new InvalidFrameException( "bad rsv RSV1: " + inputFrame.isRSV1() + " RSV2: " + inputFrame.isRSV2() + " RSV3: " + inputFrame.isRSV3() ); - super.isFrameValid(inputFrame); + if ((inputFrame instanceof ContinuousFrame) && (inputFrame.isRSV1() || inputFrame.isRSV2() + || inputFrame.isRSV3())) { + throw new InvalidFrameException( + "bad rsv RSV1: " + inputFrame.isRSV1() + " RSV2: " + inputFrame.isRSV2() + " RSV3: " + + inputFrame.isRSV3()); } + super.isFrameValid(inputFrame); + } - @Override - public String toString() { - return "PerMessageDeflateExtension"; - } + @Override + public String toString() { + return "PerMessageDeflateExtension"; + } } diff --git a/src/main/java/org/java_websocket/framing/BinaryFrame.java b/src/main/java/org/java_websocket/framing/BinaryFrame.java index bd0125991..dc0544954 100644 --- a/src/main/java/org/java_websocket/framing/BinaryFrame.java +++ b/src/main/java/org/java_websocket/framing/BinaryFrame.java @@ -32,10 +32,10 @@ */ public class BinaryFrame extends DataFrame { - /** - * constructor which sets the opcode of this frame to binary - */ - public BinaryFrame() { - super(Opcode.BINARY); - } + /** + * constructor which sets the opcode of this frame to binary + */ + public BinaryFrame() { + super(Opcode.BINARY); + } } diff --git a/src/main/java/org/java_websocket/framing/CloseFrame.java b/src/main/java/org/java_websocket/framing/CloseFrame.java index 229b24822..15cd8cc41 100644 --- a/src/main/java/org/java_websocket/framing/CloseFrame.java +++ b/src/main/java/org/java_websocket/framing/CloseFrame.java @@ -38,302 +38,305 @@ */ public class CloseFrame extends ControlFrame { - /** - * indicates a normal closure, meaning whatever purpose the - * connection was established for has been fulfilled. - */ - public static final int NORMAL = 1000; - /** - * 1001 indicates that an endpoint is "going away", such as a server - * going down, or a browser having navigated away from a page. - */ - public static final int GOING_AWAY = 1001; - /** - * 1002 indicates that an endpoint is terminating the connection due - * to a protocol error. - */ - public static final int PROTOCOL_ERROR = 1002; - /** - * 1003 indicates that an endpoint is terminating the connection - * because it has received a type of data it cannot accept (e.g. an - * endpoint that understands only text data MAY send this if it - * receives a binary message). - */ - public static final int REFUSE = 1003; - /*1004: Reserved. The specific meaning might be defined in the future.*/ - /** - * 1005 is a reserved value and MUST NOT be set as a status code in a - * Close control frame by an endpoint. It is designated for use in - * applications expecting a status code to indicate that no status - * code was actually present. - */ - public static final int NOCODE = 1005; - /** - * 1006 is a reserved value and MUST NOT be set as a status code in a - * Close control frame by an endpoint. It is designated for use in - * applications expecting a status code to indicate that the - * connection was closed abnormally, e.g. without sending or - * receiving a Close control frame. - */ - public static final int ABNORMAL_CLOSE = 1006; - /** - * 1007 indicates that an endpoint is terminating the connection - * because it has received data within a message that was not - * consistent with the type of the message (e.g., non-UTF-8 [RFC3629] - * data within a text message). - */ - public static final int NO_UTF8 = 1007; - /** - * 1008 indicates that an endpoint is terminating the connection - * because it has received a message that violates its policy. This - * is a generic status code that can be returned when there is no - * other more suitable status code (e.g. 1003 or 1009), or if there - * is a need to hide specific details about the policy. - */ - public static final int POLICY_VALIDATION = 1008; - /** - * 1009 indicates that an endpoint is terminating the connection - * because it has received a message which is too big for it to - * process. - */ - public static final int TOOBIG = 1009; - /** - * 1010 indicates that an endpoint (client) is terminating the - * connection because it has expected the server to negotiate one or - * more extension, but the server didn't return them in the response - * message of the WebSocket handshake. The list of extensions which - * are needed SHOULD appear in the /reason/ part of the Close frame. - * Note that this status code is not used by the server, because it - * can fail the WebSocket handshake instead. - */ - public static final int EXTENSION = 1010; - /** - * 1011 indicates that a server is terminating the connection because - * it encountered an unexpected condition that prevented it from - * fulfilling the request. - **/ - public static final int UNEXPECTED_CONDITION = 1011; - /** - * 1012 indicates that the service is restarted. - * A client may reconnect, and if it choses to do, should reconnect using a randomized delay of 5 - 30s. - * See https://www.ietf.org/mail-archive/web/hybi/current/msg09670.html for more information. - * - * @since 1.3.8 - **/ - public static final int SERVICE_RESTART = 1012; - /** - * 1013 indicates that the service is experiencing overload. - * A client should only connect to a different IP (when there are multiple for the target) - * or reconnect to the same IP upon user action. - * See https://www.ietf.org/mail-archive/web/hybi/current/msg09670.html for more information. - * - * @since 1.3.8 - **/ - public static final int TRY_AGAIN_LATER = 1013; - /** - * 1014 indicates that the server was acting as a gateway or proxy and received an - * invalid response from the upstream server. This is similar to 502 HTTP Status Code - * See https://www.ietf.org/mail-archive/web/hybi/current/msg10748.html fore more information. - * - * @since 1.3.8 - **/ - public static final int BAD_GATEWAY = 1014; - /** - * 1015 is a reserved value and MUST NOT be set as a status code in a - * Close control frame by an endpoint. It is designated for use in - * applications expecting a status code to indicate that the - * connection was closed due to a failure to perform a TLS handshake - * (e.g., the server certificate can't be verified). - **/ - public static final int TLS_ERROR = 1015; + /** + * indicates a normal closure, meaning whatever purpose the connection was established for has + * been fulfilled. + */ + public static final int NORMAL = 1000; + /** + * 1001 indicates that an endpoint is "going away", such as a server going down, or a browser + * having navigated away from a page. + */ + public static final int GOING_AWAY = 1001; + /** + * 1002 indicates that an endpoint is terminating the connection due to a protocol error. + */ + public static final int PROTOCOL_ERROR = 1002; + /** + * 1003 indicates that an endpoint is terminating the connection because it has received a type of + * data it cannot accept (e.g. an endpoint that understands only text data MAY send this if it + * receives a binary message). + */ + public static final int REFUSE = 1003; + /*1004: Reserved. The specific meaning might be defined in the future.*/ + /** + * 1005 is a reserved value and MUST NOT be set as a status code in a Close control frame by an + * endpoint. It is designated for use in applications expecting a status code to indicate that no + * status code was actually present. + */ + public static final int NOCODE = 1005; + /** + * 1006 is a reserved value and MUST NOT be set as a status code in a Close control frame by an + * endpoint. It is designated for use in applications expecting a status code to indicate that the + * connection was closed abnormally, e.g. without sending or receiving a Close control frame. + */ + public static final int ABNORMAL_CLOSE = 1006; + /** + * 1007 indicates that an endpoint is terminating the connection because it has received data + * within a message that was not consistent with the type of the message (e.g., non-UTF-8 + * [RFC3629] data within a text message). + */ + public static final int NO_UTF8 = 1007; + /** + * 1008 indicates that an endpoint is terminating the connection because it has received a message + * that violates its policy. This is a generic status code that can be returned when there is no + * other more suitable status code (e.g. 1003 or 1009), or if there is a need to hide specific + * details about the policy. + */ + public static final int POLICY_VALIDATION = 1008; + /** + * 1009 indicates that an endpoint is terminating the connection because it has received a message + * which is too big for it to process. + */ + public static final int TOOBIG = 1009; + /** + * 1010 indicates that an endpoint (client) is terminating the connection because it has expected + * the server to negotiate one or more extension, but the server didn't return them in the + * response message of the WebSocket handshake. The list of extensions which are needed SHOULD + * appear in the /reason/ part of the Close frame. Note that this status code is not used by the + * server, because it can fail the WebSocket handshake instead. + */ + public static final int EXTENSION = 1010; + /** + * 1011 indicates that a server is terminating the connection because it encountered an unexpected + * condition that prevented it from fulfilling the request. + **/ + public static final int UNEXPECTED_CONDITION = 1011; + /** + * 1012 indicates that the service is restarted. A client may reconnect, and if it choses to do, + * should reconnect using a randomized delay of 5 - 30s. See https://www.ietf.org/mail-archive/web/hybi/current/msg09670.html + * for more information. + * + * @since 1.3.8 + **/ + public static final int SERVICE_RESTART = 1012; + /** + * 1013 indicates that the service is experiencing overload. A client should only connect to a + * different IP (when there are multiple for the target) or reconnect to the same IP upon user + * action. See https://www.ietf.org/mail-archive/web/hybi/current/msg09670.html for more + * information. + * + * @since 1.3.8 + **/ + public static final int TRY_AGAIN_LATER = 1013; + /** + * 1014 indicates that the server was acting as a gateway or proxy and received an invalid + * response from the upstream server. This is similar to 502 HTTP Status Code See + * https://www.ietf.org/mail-archive/web/hybi/current/msg10748.html fore more information. + * + * @since 1.3.8 + **/ + public static final int BAD_GATEWAY = 1014; + /** + * 1015 is a reserved value and MUST NOT be set as a status code in a Close control frame by an + * endpoint. It is designated for use in applications expecting a status code to indicate that the + * connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate + * can't be verified). + **/ + public static final int TLS_ERROR = 1015; - /** - * The connection had never been established - */ - public static final int NEVER_CONNECTED = -1; + /** + * The connection had never been established + */ + public static final int NEVER_CONNECTED = -1; - /** - * The connection had a buggy close (this should not happen) - */ - public static final int BUGGYCLOSE = -2; + /** + * The connection had a buggy close (this should not happen) + */ + public static final int BUGGYCLOSE = -2; - /** - * The connection was flushed and closed - */ - public static final int FLASHPOLICY = -3; + /** + * The connection was flushed and closed + */ + public static final int FLASHPOLICY = -3; - /** - * The close code used in this close frame - */ - private int code; + /** + * The close code used in this close frame + */ + private int code; - /** - * The close message used in this close frame - */ - private String reason; + /** + * The close message used in this close frame + */ + private String reason; - /** - * Constructor for a close frame - *

    - * Using opcode closing and fin = true - */ - public CloseFrame() { - super(Opcode.CLOSING); - setReason(""); - setCode(CloseFrame.NORMAL); + /** + * Constructor for a close frame + *

    + * Using opcode closing and fin = true + */ + public CloseFrame() { + super(Opcode.CLOSING); + setReason(""); + setCode(CloseFrame.NORMAL); + } + + /** + * Set the close code for this close frame + * + * @param code the close code + */ + public void setCode(int code) { + this.code = code; + // CloseFrame.TLS_ERROR is not allowed to be transferred over the wire + if (code == CloseFrame.TLS_ERROR) { + this.code = CloseFrame.NOCODE; + this.reason = ""; } + updatePayload(); + } - /** - * Set the close code for this close frame - * @param code the close code - */ - public void setCode(int code) { - this.code = code; - // CloseFrame.TLS_ERROR is not allowed to be transferred over the wire - if (code == CloseFrame.TLS_ERROR) { - this.code = CloseFrame.NOCODE; - this.reason = ""; - } - updatePayload(); + /** + * Set the close reason for this close frame + * + * @param reason the reason code + */ + public void setReason(String reason) { + if (reason == null) { + reason = ""; } + this.reason = reason; + updatePayload(); + } + + /** + * Get the used close code + * + * @return the used close code + */ + public int getCloseCode() { + return code; + } + + /** + * Get the message that closeframe is containing + * + * @return the message in this frame + */ + public String getMessage() { + return reason; + } - /** - * Set the close reason for this close frame - * @param reason the reason code - */ - public void setReason(String reason) { - if (reason == null) { - reason = ""; - } - this.reason = reason; - updatePayload(); + @Override + public String toString() { + return super.toString() + "code: " + code; + } + + @Override + public void isValid() throws InvalidDataException { + super.isValid(); + if (code == CloseFrame.NO_UTF8 && reason.isEmpty()) { + throw new InvalidDataException(CloseFrame.NO_UTF8, "Received text is no valid utf8 string!"); } - /** - * Get the used close code - * - * @return the used close code - */ - public int getCloseCode() { - return code; + if (code == CloseFrame.NOCODE && 0 < reason.length()) { + throw new InvalidDataException(PROTOCOL_ERROR, + "A close frame must have a closecode if it has a reason"); } - - /** - * Get the message that closeframe is containing - * - * @return the message in this frame - */ - public String getMessage() { - return reason; + //Intentional check for code != CloseFrame.TLS_ERROR just to make sure even if the code earlier changes + if ((code > CloseFrame.TLS_ERROR && code < 3000)) { + throw new InvalidDataException(PROTOCOL_ERROR, "Trying to send an illegal close code!"); } + if (code == CloseFrame.ABNORMAL_CLOSE || code == CloseFrame.TLS_ERROR + || code == CloseFrame.NOCODE || code > 4999 || code < 1000 || code == 1004) { + throw new InvalidFrameException("closecode must not be sent over the wire: " + code); + } + } - @Override - public String toString() { - return super.toString() + "code: " + code; + @Override + public void setPayload(ByteBuffer payload) { + code = CloseFrame.NOCODE; + reason = ""; + payload.mark(); + if (payload.remaining() == 0) { + code = CloseFrame.NORMAL; + } else if (payload.remaining() == 1) { + code = CloseFrame.PROTOCOL_ERROR; + } else { + if (payload.remaining() >= 2) { + ByteBuffer bb = ByteBuffer.allocate(4); + bb.position(2); + bb.putShort(payload.getShort()); + bb.position(0); + code = bb.getInt(); + } + payload.reset(); + try { + int mark = payload.position();// because stringUtf8 also creates a mark + validateUtf8(payload, mark); + } catch (InvalidDataException e) { + code = CloseFrame.NO_UTF8; + reason = null; + } } + } - @Override - public void isValid() throws InvalidDataException { - super.isValid(); - if (code == CloseFrame.NO_UTF8 && reason.isEmpty()) { - throw new InvalidDataException( CloseFrame.NO_UTF8, "Received text is no valid utf8 string!"); - } - if (code == CloseFrame.NOCODE && 0 < reason.length()) { - throw new InvalidDataException(PROTOCOL_ERROR, "A close frame must have a closecode if it has a reason"); - } - //Intentional check for code != CloseFrame.TLS_ERROR just to make sure even if the code earlier changes - if ((code > CloseFrame.TLS_ERROR && code < 3000)) { - throw new InvalidDataException(PROTOCOL_ERROR, "Trying to send an illegal close code!"); - } - if (code == CloseFrame.ABNORMAL_CLOSE || code == CloseFrame.TLS_ERROR || code == CloseFrame.NOCODE || code > 4999 || code < 1000 || code == 1004) { - throw new InvalidFrameException("closecode must not be sent over the wire: " + code); - } + /** + * Validate the payload to valid utf8 + * + * @param mark the current mark + * @param payload the current payload + * @throws InvalidDataException the current payload is not a valid utf8 + */ + private void validateUtf8(ByteBuffer payload, int mark) throws InvalidDataException { + try { + payload.position(payload.position() + 2); + reason = Charsetfunctions.stringUtf8(payload); + } catch (IllegalArgumentException e) { + throw new InvalidDataException(CloseFrame.NO_UTF8); + } finally { + payload.position(mark); } + } - @Override - public void setPayload(ByteBuffer payload) { - code = CloseFrame.NOCODE; - reason = ""; - payload.mark(); - if( payload.remaining() == 0 ) { - code = CloseFrame.NORMAL; - } else if( payload.remaining() == 1 ) { - code = CloseFrame.PROTOCOL_ERROR; - } else { - if( payload.remaining() >= 2 ) { - ByteBuffer bb = ByteBuffer.allocate( 4 ); - bb.position( 2 ); - bb.putShort( payload.getShort() ); - bb.position( 0 ); - code = bb.getInt(); - } - payload.reset(); - try { - int mark = payload.position();// because stringUtf8 also creates a mark - validateUtf8(payload, mark); - } catch ( InvalidDataException e ) { - code = CloseFrame.NO_UTF8; - reason = null; - } - } - } + /** + * Update the payload to represent the close code and the reason + */ + private void updatePayload() { + byte[] by = Charsetfunctions.utf8Bytes(reason); + ByteBuffer buf = ByteBuffer.allocate(4); + buf.putInt(code); + buf.position(2); + ByteBuffer pay = ByteBuffer.allocate(2 + by.length); + pay.put(buf); + pay.put(by); + pay.rewind(); + super.setPayload(pay); + } - /** - * Validate the payload to valid utf8 - * @param mark the current mark - * @param payload the current payload - * @throws InvalidDataException the current payload is not a valid utf8 - */ - private void validateUtf8(ByteBuffer payload, int mark) throws InvalidDataException { - try { - payload.position( payload.position() + 2 ); - reason = Charsetfunctions.stringUtf8( payload ); - } catch ( IllegalArgumentException e ) { - throw new InvalidDataException( CloseFrame.NO_UTF8 ); - } finally { - payload.position( mark ); - } + @Override + public ByteBuffer getPayloadData() { + if (code == NOCODE) { + return ByteBufferUtils.getEmptyByteBuffer(); } + return super.getPayloadData(); + } - /** - * Update the payload to represent the close code and the reason - */ - private void updatePayload() { - byte[] by = Charsetfunctions.utf8Bytes(reason); - ByteBuffer buf = ByteBuffer.allocate(4); - buf.putInt(code); - buf.position(2); - ByteBuffer pay = ByteBuffer.allocate(2 + by.length); - pay.put(buf); - pay.put(by); - pay.rewind(); - super.setPayload(pay); + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - @Override - public ByteBuffer getPayloadData() { - if (code == NOCODE) - return ByteBufferUtils.getEmptyByteBuffer(); - return super.getPayloadData(); + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; - - CloseFrame that = (CloseFrame) o; + CloseFrame that = (CloseFrame) o; - if (code != that.code) return false; - return reason != null ? reason.equals(that.reason) : that.reason == null; + if (code != that.code) { + return false; } + return reason != null ? reason.equals(that.reason) : that.reason == null; + } - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + code; - result = 31 * result + (reason != null ? reason.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + code; + result = 31 * result + (reason != null ? reason.hashCode() : 0); + return result; + } } diff --git a/src/main/java/org/java_websocket/framing/ContinuousFrame.java b/src/main/java/org/java_websocket/framing/ContinuousFrame.java index 7e8738278..c518cc3bd 100644 --- a/src/main/java/org/java_websocket/framing/ContinuousFrame.java +++ b/src/main/java/org/java_websocket/framing/ContinuousFrame.java @@ -32,10 +32,10 @@ */ public class ContinuousFrame extends DataFrame { - /** - * constructor which sets the opcode of this frame to continuous - */ - public ContinuousFrame() { - super( Opcode.CONTINUOUS ); - } + /** + * constructor which sets the opcode of this frame to continuous + */ + public ContinuousFrame() { + super(Opcode.CONTINUOUS); + } } diff --git a/src/main/java/org/java_websocket/framing/ControlFrame.java b/src/main/java/org/java_websocket/framing/ControlFrame.java index e8848ed84..1469dc5e6 100644 --- a/src/main/java/org/java_websocket/framing/ControlFrame.java +++ b/src/main/java/org/java_websocket/framing/ControlFrame.java @@ -34,27 +34,28 @@ */ public abstract class ControlFrame extends FramedataImpl1 { - /** - * Class to represent a control frame - * @param opcode the opcode to use - */ - public ControlFrame( Opcode opcode ) { - super( opcode ); - } + /** + * Class to represent a control frame + * + * @param opcode the opcode to use + */ + public ControlFrame(Opcode opcode) { + super(opcode); + } - @Override - public void isValid() throws InvalidDataException { - if( !isFin() ) { - throw new InvalidFrameException( "Control frame can't have fin==false set" ); - } - if( isRSV1() ) { - throw new InvalidFrameException( "Control frame can't have rsv1==true set" ); - } - if( isRSV2() ) { - throw new InvalidFrameException( "Control frame can't have rsv2==true set" ); - } - if( isRSV3() ) { - throw new InvalidFrameException( "Control frame can't have rsv3==true set" ); - } - } + @Override + public void isValid() throws InvalidDataException { + if (!isFin()) { + throw new InvalidFrameException("Control frame can't have fin==false set"); + } + if (isRSV1()) { + throw new InvalidFrameException("Control frame can't have rsv1==true set"); + } + if (isRSV2()) { + throw new InvalidFrameException("Control frame can't have rsv2==true set"); + } + if (isRSV3()) { + throw new InvalidFrameException("Control frame can't have rsv3==true set"); + } + } } diff --git a/src/main/java/org/java_websocket/framing/DataFrame.java b/src/main/java/org/java_websocket/framing/DataFrame.java index 0a3ada56e..c845c2ced 100644 --- a/src/main/java/org/java_websocket/framing/DataFrame.java +++ b/src/main/java/org/java_websocket/framing/DataFrame.java @@ -33,17 +33,17 @@ */ public abstract class DataFrame extends FramedataImpl1 { - /** - * Class to represent a data frame - * @param opcode the opcode to use - */ - public DataFrame(Opcode opcode) { - super(opcode); - } + /** + * Class to represent a data frame + * + * @param opcode the opcode to use + */ + public DataFrame(Opcode opcode) { + super(opcode); + } - @Override - public void isValid() throws InvalidDataException - { - //Nothing specific to check - } + @Override + public void isValid() throws InvalidDataException { + //Nothing specific to check + } } diff --git a/src/main/java/org/java_websocket/framing/Framedata.java b/src/main/java/org/java_websocket/framing/Framedata.java index 03074dbdd..11c4e01ce 100644 --- a/src/main/java/org/java_websocket/framing/Framedata.java +++ b/src/main/java/org/java_websocket/framing/Framedata.java @@ -33,53 +33,62 @@ */ public interface Framedata { - /** - * Indicates that this is the final fragment in a message. The first fragment MAY also be the final fragment. - * @return true, if this frame is the final fragment - */ - boolean isFin(); + /** + * Indicates that this is the final fragment in a message. The first fragment MAY also be the + * final fragment. + * + * @return true, if this frame is the final fragment + */ + boolean isFin(); - /** - * Indicates that this frame has the rsv1 bit set. - * @return true, if this frame has the rsv1 bit set - */ - boolean isRSV1(); + /** + * Indicates that this frame has the rsv1 bit set. + * + * @return true, if this frame has the rsv1 bit set + */ + boolean isRSV1(); - /** - * Indicates that this frame has the rsv2 bit set. - * @return true, if this frame has the rsv2 bit set - */ - boolean isRSV2(); + /** + * Indicates that this frame has the rsv2 bit set. + * + * @return true, if this frame has the rsv2 bit set + */ + boolean isRSV2(); - /** - * Indicates that this frame has the rsv3 bit set. - * @return true, if this frame has the rsv3 bit set - */ - boolean isRSV3(); + /** + * Indicates that this frame has the rsv3 bit set. + * + * @return true, if this frame has the rsv3 bit set + */ + boolean isRSV3(); - /** - * Defines whether the "Payload data" is masked. - * @return true, "Payload data" is masked - */ - boolean getTransfereMasked(); + /** + * Defines whether the "Payload data" is masked. + * + * @return true, "Payload data" is masked + */ + boolean getTransfereMasked(); - /** - * Defines the interpretation of the "Payload data". - * @return the interpretation as a Opcode - */ - Opcode getOpcode(); + /** + * Defines the interpretation of the "Payload data". + * + * @return the interpretation as a Opcode + */ + Opcode getOpcode(); - /** - * The "Payload data" which was sent in this frame - * @return the "Payload data" as ByteBuffer - */ - ByteBuffer getPayloadData();// TODO the separation of the application data and the extension data is yet to be done + /** + * The "Payload data" which was sent in this frame + * + * @return the "Payload data" as ByteBuffer + */ + ByteBuffer getPayloadData();// TODO the separation of the application data and the extension data is yet to be done - /** - * Appends an additional frame to the current frame - * - * This methods does not override the opcode, but does override the fin - * @param nextframe the additional frame - */ - void append( Framedata nextframe ); + /** + * Appends an additional frame to the current frame + *

    + * This methods does not override the opcode, but does override the fin + * + * @param nextframe the additional frame + */ + void append(Framedata nextframe); } diff --git a/src/main/java/org/java_websocket/framing/FramedataImpl1.java b/src/main/java/org/java_websocket/framing/FramedataImpl1.java index f3e3f97e1..5dc30cf8a 100644 --- a/src/main/java/org/java_websocket/framing/FramedataImpl1.java +++ b/src/main/java/org/java_websocket/framing/FramedataImpl1.java @@ -36,239 +36,260 @@ */ public abstract class FramedataImpl1 implements Framedata { - /** - * Indicates that this is the final fragment in a message. - */ - private boolean fin; - /** - * Defines the interpretation of the "Payload data". - */ - private Opcode optcode; - - /** - * The unmasked "Payload data" which was sent in this frame - */ - private ByteBuffer unmaskedpayload; - - /** - * Defines whether the "Payload data" is masked. - */ - private boolean transferemasked; - - /** - * Indicates that the rsv1 bit is set or not - */ - private boolean rsv1; - - /** - * Indicates that the rsv2 bit is set or not - */ - private boolean rsv2; - - /** - * Indicates that the rsv3 bit is set or not - */ - private boolean rsv3; - - /** - * Check if the frame is valid due to specification - * - * @throws InvalidDataException thrown if the frame is not a valid frame - */ - public abstract void isValid() throws InvalidDataException; - - /** - * Constructor for a FramedataImpl without any attributes set apart from the opcode - * - * @param op the opcode to use - */ - public FramedataImpl1(Opcode op) { - optcode = op; - unmaskedpayload = ByteBufferUtils.getEmptyByteBuffer(); - fin = true; - transferemasked = false; - rsv1 = false; - rsv2 = false; - rsv3 = false; + /** + * Indicates that this is the final fragment in a message. + */ + private boolean fin; + /** + * Defines the interpretation of the "Payload data". + */ + private Opcode optcode; + + /** + * The unmasked "Payload data" which was sent in this frame + */ + private ByteBuffer unmaskedpayload; + + /** + * Defines whether the "Payload data" is masked. + */ + private boolean transferemasked; + + /** + * Indicates that the rsv1 bit is set or not + */ + private boolean rsv1; + + /** + * Indicates that the rsv2 bit is set or not + */ + private boolean rsv2; + + /** + * Indicates that the rsv3 bit is set or not + */ + private boolean rsv3; + + /** + * Check if the frame is valid due to specification + * + * @throws InvalidDataException thrown if the frame is not a valid frame + */ + public abstract void isValid() throws InvalidDataException; + + /** + * Constructor for a FramedataImpl without any attributes set apart from the opcode + * + * @param op the opcode to use + */ + public FramedataImpl1(Opcode op) { + optcode = op; + unmaskedpayload = ByteBufferUtils.getEmptyByteBuffer(); + fin = true; + transferemasked = false; + rsv1 = false; + rsv2 = false; + rsv3 = false; + } + + @Override + public boolean isRSV1() { + return rsv1; + } + + @Override + public boolean isRSV2() { + return rsv2; + } + + @Override + public boolean isRSV3() { + return rsv3; + } + + @Override + public boolean isFin() { + return fin; + } + + @Override + public Opcode getOpcode() { + return optcode; + } + + @Override + public boolean getTransfereMasked() { + return transferemasked; + } + + @Override + public ByteBuffer getPayloadData() { + return unmaskedpayload; + } + + @Override + public void append(Framedata nextframe) { + ByteBuffer b = nextframe.getPayloadData(); + if (unmaskedpayload == null) { + unmaskedpayload = ByteBuffer.allocate(b.remaining()); + b.mark(); + unmaskedpayload.put(b); + b.reset(); + } else { + b.mark(); + unmaskedpayload.position(unmaskedpayload.limit()); + unmaskedpayload.limit(unmaskedpayload.capacity()); + + if (b.remaining() > unmaskedpayload.remaining()) { + ByteBuffer tmp = ByteBuffer.allocate(b.remaining() + unmaskedpayload.capacity()); + unmaskedpayload.flip(); + tmp.put(unmaskedpayload); + tmp.put(b); + unmaskedpayload = tmp; + + } else { + unmaskedpayload.put(b); + } + unmaskedpayload.rewind(); + b.reset(); } - - @Override - public boolean isRSV1() { - return rsv1; - } - - @Override - public boolean isRSV2() { - return rsv2; - } - - @Override - public boolean isRSV3() { - return rsv3; - } - - @Override - public boolean isFin() { - return fin; - } - - @Override - public Opcode getOpcode() { - return optcode; - } - - @Override - public boolean getTransfereMasked() { - return transferemasked; - } - - @Override - public ByteBuffer getPayloadData() { - return unmaskedpayload; + fin = nextframe.isFin(); + + } + + @Override + public String toString() { + return "Framedata{ opcode:" + getOpcode() + ", fin:" + isFin() + ", rsv1:" + isRSV1() + + ", rsv2:" + isRSV2() + ", rsv3:" + isRSV3() + ", payload length:[pos:" + unmaskedpayload + .position() + ", len:" + unmaskedpayload.remaining() + "], payload:" + ( + unmaskedpayload.remaining() > 1000 ? "(too big to display)" + : new String(unmaskedpayload.array())) + '}'; + } + + /** + * Set the payload of this frame to the provided payload + * + * @param payload the payload which is to set + */ + public void setPayload(ByteBuffer payload) { + this.unmaskedpayload = payload; + } + + /** + * Set the fin of this frame to the provided boolean + * + * @param fin true if fin has to be set + */ + public void setFin(boolean fin) { + this.fin = fin; + } + + /** + * Set the rsv1 of this frame to the provided boolean + * + * @param rsv1 true if rsv1 has to be set + */ + public void setRSV1(boolean rsv1) { + this.rsv1 = rsv1; + } + + /** + * Set the rsv2 of this frame to the provided boolean + * + * @param rsv2 true if rsv2 has to be set + */ + public void setRSV2(boolean rsv2) { + this.rsv2 = rsv2; + } + + /** + * Set the rsv3 of this frame to the provided boolean + * + * @param rsv3 true if rsv3 has to be set + */ + public void setRSV3(boolean rsv3) { + this.rsv3 = rsv3; + } + + /** + * Set the tranferemask of this frame to the provided boolean + * + * @param transferemasked true if transferemasked has to be set + */ + public void setTransferemasked(boolean transferemasked) { + this.transferemasked = transferemasked; + } + + /** + * Get a frame with a specific opcode + * + * @param opcode the opcode representing the frame + * @return the frame with a specific opcode + */ + public static FramedataImpl1 get(Opcode opcode) { + if (opcode == null) { + throw new IllegalArgumentException("Supplied opcode cannot be null"); } - - @Override - public void append(Framedata nextframe) { - ByteBuffer b = nextframe.getPayloadData(); - if (unmaskedpayload == null) { - unmaskedpayload = ByteBuffer.allocate(b.remaining()); - b.mark(); - unmaskedpayload.put(b); - b.reset(); - } else { - b.mark(); - unmaskedpayload.position(unmaskedpayload.limit()); - unmaskedpayload.limit(unmaskedpayload.capacity()); - - if (b.remaining() > unmaskedpayload.remaining()) { - ByteBuffer tmp = ByteBuffer.allocate(b.remaining() + unmaskedpayload.capacity()); - unmaskedpayload.flip(); - tmp.put(unmaskedpayload); - tmp.put(b); - unmaskedpayload = tmp; - - } else { - unmaskedpayload.put(b); - } - unmaskedpayload.rewind(); - b.reset(); - } - fin = nextframe.isFin(); - + switch (opcode) { + case PING: + return new PingFrame(); + case PONG: + return new PongFrame(); + case TEXT: + return new TextFrame(); + case BINARY: + return new BinaryFrame(); + case CLOSING: + return new CloseFrame(); + case CONTINUOUS: + return new ContinuousFrame(); + default: + throw new IllegalArgumentException("Supplied opcode is invalid"); } + } - @Override - public String toString() { - return "Framedata{ opcode:" + getOpcode() + ", fin:" + isFin() + ", rsv1:" + isRSV1() + ", rsv2:" + isRSV2() + ", rsv3:" + isRSV3() + ", payload length:[pos:" + unmaskedpayload.position() + ", len:" + unmaskedpayload.remaining() + "], payload:" + ( unmaskedpayload.remaining() > 1000 ? "(too big to display)" : new String( unmaskedpayload.array() ) ) + '}'; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - /** - * Set the payload of this frame to the provided payload - * - * @param payload the payload which is to set - */ - public void setPayload(ByteBuffer payload) { - this.unmaskedpayload = payload; + if (o == null || getClass() != o.getClass()) { + return false; } - /** - * Set the fin of this frame to the provided boolean - * - * @param fin true if fin has to be set - */ - public void setFin(boolean fin) { - this.fin = fin; - } + FramedataImpl1 that = (FramedataImpl1) o; - /** - * Set the rsv1 of this frame to the provided boolean - * - * @param rsv1 true if rsv1 has to be set - */ - public void setRSV1(boolean rsv1) { - this.rsv1 = rsv1; + if (fin != that.fin) { + return false; } - - /** - * Set the rsv2 of this frame to the provided boolean - * - * @param rsv2 true if rsv2 has to be set - */ - public void setRSV2(boolean rsv2) { - this.rsv2 = rsv2; + if (transferemasked != that.transferemasked) { + return false; } - - /** - * Set the rsv3 of this frame to the provided boolean - * - * @param rsv3 true if rsv3 has to be set - */ - public void setRSV3(boolean rsv3) { - this.rsv3 = rsv3; + if (rsv1 != that.rsv1) { + return false; } - - /** - * Set the tranferemask of this frame to the provided boolean - * - * @param transferemasked true if transferemasked has to be set - */ - public void setTransferemasked(boolean transferemasked) { - this.transferemasked = transferemasked; + if (rsv2 != that.rsv2) { + return false; } - - /** - * Get a frame with a specific opcode - * - * @param opcode the opcode representing the frame - * @return the frame with a specific opcode - */ - public static FramedataImpl1 get(Opcode opcode) { - if (opcode== null) { - throw new IllegalArgumentException("Supplied opcode cannot be null"); - } - switch (opcode) { - case PING: - return new PingFrame(); - case PONG: - return new PongFrame(); - case TEXT: - return new TextFrame(); - case BINARY: - return new BinaryFrame(); - case CLOSING: - return new CloseFrame(); - case CONTINUOUS: - return new ContinuousFrame(); - default: - throw new IllegalArgumentException("Supplied opcode is invalid"); - } - } - - @Override - public boolean equals( Object o ) { - if( this == o ) return true; - if( o == null || getClass() != o.getClass() ) return false; - - FramedataImpl1 that = ( FramedataImpl1 ) o; - - if( fin != that.fin ) return false; - if( transferemasked != that.transferemasked ) return false; - if( rsv1 != that.rsv1 ) return false; - if( rsv2 != that.rsv2 ) return false; - if( rsv3 != that.rsv3 ) return false; - if( optcode != that.optcode ) return false; - return unmaskedpayload != null ? unmaskedpayload.equals( that.unmaskedpayload ) : that.unmaskedpayload == null; + if (rsv3 != that.rsv3) { + return false; } - - @Override - public int hashCode() { - int result = ( fin ? 1 : 0 ); - result = 31 * result + optcode.hashCode(); - result = 31 * result + ( unmaskedpayload != null ? unmaskedpayload.hashCode() : 0 ); - result = 31 * result + ( transferemasked ? 1 : 0 ); - result = 31 * result + ( rsv1 ? 1 : 0 ); - result = 31 * result + ( rsv2 ? 1 : 0 ); - result = 31 * result + ( rsv3 ? 1 : 0 ); - return result; + if (optcode != that.optcode) { + return false; } + return unmaskedpayload != null ? unmaskedpayload.equals(that.unmaskedpayload) + : that.unmaskedpayload == null; + } + + @Override + public int hashCode() { + int result = (fin ? 1 : 0); + result = 31 * result + optcode.hashCode(); + result = 31 * result + (unmaskedpayload != null ? unmaskedpayload.hashCode() : 0); + result = 31 * result + (transferemasked ? 1 : 0); + result = 31 * result + (rsv1 ? 1 : 0); + result = 31 * result + (rsv2 ? 1 : 0); + result = 31 * result + (rsv3 ? 1 : 0); + return result; + } } diff --git a/src/main/java/org/java_websocket/framing/PingFrame.java b/src/main/java/org/java_websocket/framing/PingFrame.java index fc60b9390..ae2b29119 100644 --- a/src/main/java/org/java_websocket/framing/PingFrame.java +++ b/src/main/java/org/java_websocket/framing/PingFrame.java @@ -32,10 +32,10 @@ */ public class PingFrame extends ControlFrame { - /** - * constructor which sets the opcode of this frame to ping - */ - public PingFrame() { - super(Opcode.PING); - } + /** + * constructor which sets the opcode of this frame to ping + */ + public PingFrame() { + super(Opcode.PING); + } } diff --git a/src/main/java/org/java_websocket/framing/PongFrame.java b/src/main/java/org/java_websocket/framing/PongFrame.java index 31f5eb397..4b58139ea 100644 --- a/src/main/java/org/java_websocket/framing/PongFrame.java +++ b/src/main/java/org/java_websocket/framing/PongFrame.java @@ -32,20 +32,20 @@ */ public class PongFrame extends ControlFrame { - /** - * constructor which sets the opcode of this frame to pong - */ - public PongFrame() { - super(Opcode.PONG); - } + /** + * constructor which sets the opcode of this frame to pong + */ + public PongFrame() { + super(Opcode.PONG); + } - /** - * constructor which sets the opcode of this frame to ping copying over the payload of the ping - * - * @param pingFrame the PingFrame which payload is to copy - */ - public PongFrame(PingFrame pingFrame) { - super(Opcode.PONG); - setPayload(pingFrame.getPayloadData()); - } + /** + * constructor which sets the opcode of this frame to ping copying over the payload of the ping + * + * @param pingFrame the PingFrame which payload is to copy + */ + public PongFrame(PingFrame pingFrame) { + super(Opcode.PONG); + setPayload(pingFrame.getPayloadData()); + } } diff --git a/src/main/java/org/java_websocket/framing/TextFrame.java b/src/main/java/org/java_websocket/framing/TextFrame.java index 8dc77f181..52154b47e 100644 --- a/src/main/java/org/java_websocket/framing/TextFrame.java +++ b/src/main/java/org/java_websocket/framing/TextFrame.java @@ -34,18 +34,18 @@ */ public class TextFrame extends DataFrame { - /** - * constructor which sets the opcode of this frame to text - */ - public TextFrame() { - super(Opcode.TEXT); - } + /** + * constructor which sets the opcode of this frame to text + */ + public TextFrame() { + super(Opcode.TEXT); + } - @Override - public void isValid() throws InvalidDataException { - super.isValid(); - if (!Charsetfunctions.isValidUTF8( getPayloadData() )) { - throw new InvalidDataException(CloseFrame.NO_UTF8, "Received text is no valid utf8 string!"); - } + @Override + public void isValid() throws InvalidDataException { + super.isValid(); + if (!Charsetfunctions.isValidUTF8(getPayloadData())) { + throw new InvalidDataException(CloseFrame.NO_UTF8, "Received text is no valid utf8 string!"); } + } } diff --git a/src/main/java/org/java_websocket/framing/package-info.java b/src/main/java/org/java_websocket/framing/package-info.java index d5d73d161..12e1510ec 100644 --- a/src/main/java/org/java_websocket/framing/package-info.java +++ b/src/main/java/org/java_websocket/framing/package-info.java @@ -24,6 +24,7 @@ */ /** - * This package encapsulates all interfaces and implementations in relation with the WebSocket frames. + * This package encapsulates all interfaces and implementations in relation with the WebSocket + * frames. */ package org.java_websocket.framing; \ No newline at end of file diff --git a/src/main/java/org/java_websocket/handshake/ClientHandshake.java b/src/main/java/org/java_websocket/handshake/ClientHandshake.java index 2108b913c..f0cbc3ab9 100644 --- a/src/main/java/org/java_websocket/handshake/ClientHandshake.java +++ b/src/main/java/org/java_websocket/handshake/ClientHandshake.java @@ -30,9 +30,10 @@ */ public interface ClientHandshake extends Handshakedata { - /** - * returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2 - * @return the HTTP Request-URI - */ - String getResourceDescriptor(); + /** + * returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2 + * + * @return the HTTP Request-URI + */ + String getResourceDescriptor(); } diff --git a/src/main/java/org/java_websocket/handshake/ClientHandshakeBuilder.java b/src/main/java/org/java_websocket/handshake/ClientHandshakeBuilder.java index ea69a4395..81875153d 100644 --- a/src/main/java/org/java_websocket/handshake/ClientHandshakeBuilder.java +++ b/src/main/java/org/java_websocket/handshake/ClientHandshakeBuilder.java @@ -30,9 +30,10 @@ */ public interface ClientHandshakeBuilder extends HandshakeBuilder, ClientHandshake { - /** - * Set a specific resource descriptor - * @param resourceDescriptor the resource descriptior to set - */ - void setResourceDescriptor( String resourceDescriptor ); + /** + * Set a specific resource descriptor + * + * @param resourceDescriptor the resource descriptior to set + */ + void setResourceDescriptor(String resourceDescriptor); } diff --git a/src/main/java/org/java_websocket/handshake/HandshakeBuilder.java b/src/main/java/org/java_websocket/handshake/HandshakeBuilder.java index 949f307f3..1f4de2067 100644 --- a/src/main/java/org/java_websocket/handshake/HandshakeBuilder.java +++ b/src/main/java/org/java_websocket/handshake/HandshakeBuilder.java @@ -30,16 +30,18 @@ */ public interface HandshakeBuilder extends Handshakedata { - /** - * Setter for the content of the handshake - * @param content the content to set - */ - void setContent( byte[] content ); + /** + * Setter for the content of the handshake + * + * @param content the content to set + */ + void setContent(byte[] content); - /** - * Adding a specific field with a specific value - * @param name the http field - * @param value the value for this field - */ - void put( String name, String value ); + /** + * Adding a specific field with a specific value + * + * @param name the http field + * @param value the value for this field + */ + void put(String name, String value); } diff --git a/src/main/java/org/java_websocket/handshake/HandshakeImpl1Client.java b/src/main/java/org/java_websocket/handshake/HandshakeImpl1Client.java index f8b64e961..11ffa43dd 100644 --- a/src/main/java/org/java_websocket/handshake/HandshakeImpl1Client.java +++ b/src/main/java/org/java_websocket/handshake/HandshakeImpl1Client.java @@ -30,20 +30,21 @@ */ public class HandshakeImpl1Client extends HandshakedataImpl1 implements ClientHandshakeBuilder { - /** - * Attribute for the resource descriptor - */ - private String resourceDescriptor = "*"; + /** + * Attribute for the resource descriptor + */ + private String resourceDescriptor = "*"; - @Override - public void setResourceDescriptor( String resourceDescriptor ) { - if(resourceDescriptor==null) - throw new IllegalArgumentException( "http resource descriptor must not be null" ); - this.resourceDescriptor = resourceDescriptor; - } + @Override + public void setResourceDescriptor(String resourceDescriptor) { + if (resourceDescriptor == null) { + throw new IllegalArgumentException("http resource descriptor must not be null"); + } + this.resourceDescriptor = resourceDescriptor; + } - @Override - public String getResourceDescriptor() { - return resourceDescriptor; - } + @Override + public String getResourceDescriptor() { + return resourceDescriptor; + } } diff --git a/src/main/java/org/java_websocket/handshake/HandshakeImpl1Server.java b/src/main/java/org/java_websocket/handshake/HandshakeImpl1Server.java index 9df98d64d..87540141d 100644 --- a/src/main/java/org/java_websocket/handshake/HandshakeImpl1Server.java +++ b/src/main/java/org/java_websocket/handshake/HandshakeImpl1Server.java @@ -30,33 +30,33 @@ */ public class HandshakeImpl1Server extends HandshakedataImpl1 implements ServerHandshakeBuilder { - /** - * Attribute for the http status - */ - private short httpstatus; - - /** - * Attribute for the http status message - */ - private String httpstatusmessage; - - @Override - public String getHttpStatusMessage() { - return httpstatusmessage; - } - - @Override - public short getHttpStatus() { - return httpstatus; - } - - @Override - public void setHttpStatusMessage( String message ) { - this.httpstatusmessage = message; - } - - @Override - public void setHttpStatus( short status ) { - httpstatus = status; - } + /** + * Attribute for the http status + */ + private short httpstatus; + + /** + * Attribute for the http status message + */ + private String httpstatusmessage; + + @Override + public String getHttpStatusMessage() { + return httpstatusmessage; + } + + @Override + public short getHttpStatus() { + return httpstatus; + } + + @Override + public void setHttpStatusMessage(String message) { + this.httpstatusmessage = message; + } + + @Override + public void setHttpStatus(short status) { + httpstatus = status; + } } diff --git a/src/main/java/org/java_websocket/handshake/Handshakedata.java b/src/main/java/org/java_websocket/handshake/Handshakedata.java index f2746095b..fd270ecb6 100644 --- a/src/main/java/org/java_websocket/handshake/Handshakedata.java +++ b/src/main/java/org/java_websocket/handshake/Handshakedata.java @@ -32,29 +32,33 @@ */ public interface Handshakedata { - /** - * Iterator for the http fields - * @return the http fields - */ - Iterator iterateHttpFields(); + /** + * Iterator for the http fields + * + * @return the http fields + */ + Iterator iterateHttpFields(); - /** - * Gets the value of the field - * @param name The name of the field - * @return the value of the field or an empty String if not in the handshake - */ - String getFieldValue( String name ); + /** + * Gets the value of the field + * + * @param name The name of the field + * @return the value of the field or an empty String if not in the handshake + */ + String getFieldValue(String name); - /** - * Checks if this handshake contains a specific field - * @param name The name of the field - * @return true, if it contains the field - */ - boolean hasFieldValue( String name ); + /** + * Checks if this handshake contains a specific field + * + * @param name The name of the field + * @return true, if it contains the field + */ + boolean hasFieldValue(String name); - /** - * Get the content of the handshake - * @return the content as byte-array - */ - byte[] getContent(); + /** + * Get the content of the handshake + * + * @return the content as byte-array + */ + byte[] getContent(); } diff --git a/src/main/java/org/java_websocket/handshake/HandshakedataImpl1.java b/src/main/java/org/java_websocket/handshake/HandshakedataImpl1.java index 4eb0654e4..bc59993c6 100644 --- a/src/main/java/org/java_websocket/handshake/HandshakedataImpl1.java +++ b/src/main/java/org/java_websocket/handshake/HandshakedataImpl1.java @@ -34,54 +34,54 @@ */ public class HandshakedataImpl1 implements HandshakeBuilder { - /** - * Attribute for the content of the handshake - */ - private byte[] content; + /** + * Attribute for the content of the handshake + */ + private byte[] content; - /** - * Attribute for the http fields and values - */ - private TreeMap map; + /** + * Attribute for the http fields and values + */ + private TreeMap map; - /** - * Constructor for handshake implementation - */ - public HandshakedataImpl1() { - map = new TreeMap( String.CASE_INSENSITIVE_ORDER ); - } + /** + * Constructor for handshake implementation + */ + public HandshakedataImpl1() { + map = new TreeMap(String.CASE_INSENSITIVE_ORDER); + } - @Override - public Iterator iterateHttpFields() { - return Collections.unmodifiableSet( map.keySet() ).iterator();// Safety first - } + @Override + public Iterator iterateHttpFields() { + return Collections.unmodifiableSet(map.keySet()).iterator();// Safety first + } - @Override - public String getFieldValue( String name ) { - String s = map.get( name ); - if ( s == null ) { - return ""; - } - return s; - } + @Override + public String getFieldValue(String name) { + String s = map.get(name); + if (s == null) { + return ""; + } + return s; + } - @Override - public byte[] getContent() { - return content; - } + @Override + public byte[] getContent() { + return content; + } - @Override - public void setContent( byte[] content ) { - this.content = content; - } + @Override + public void setContent(byte[] content) { + this.content = content; + } - @Override - public void put( String name, String value ) { - map.put( name, value ); - } + @Override + public void put(String name, String value) { + map.put(name, value); + } - @Override - public boolean hasFieldValue( String name ) { - return map.containsKey( name ); - } + @Override + public boolean hasFieldValue(String name) { + return map.containsKey(name); + } } diff --git a/src/main/java/org/java_websocket/handshake/ServerHandshake.java b/src/main/java/org/java_websocket/handshake/ServerHandshake.java index c3e79b856..1b5a5a9b8 100644 --- a/src/main/java/org/java_websocket/handshake/ServerHandshake.java +++ b/src/main/java/org/java_websocket/handshake/ServerHandshake.java @@ -30,15 +30,17 @@ */ public interface ServerHandshake extends Handshakedata { - /** - * Get the http status code - * @return the http status code - */ - short getHttpStatus(); + /** + * Get the http status code + * + * @return the http status code + */ + short getHttpStatus(); - /** - * Get the http status message - * @return the http status message - */ - String getHttpStatusMessage(); + /** + * Get the http status message + * + * @return the http status message + */ + String getHttpStatusMessage(); } diff --git a/src/main/java/org/java_websocket/handshake/ServerHandshakeBuilder.java b/src/main/java/org/java_websocket/handshake/ServerHandshakeBuilder.java index 49acc755e..51212f048 100644 --- a/src/main/java/org/java_websocket/handshake/ServerHandshakeBuilder.java +++ b/src/main/java/org/java_websocket/handshake/ServerHandshakeBuilder.java @@ -30,15 +30,17 @@ */ public interface ServerHandshakeBuilder extends HandshakeBuilder, ServerHandshake { - /** - * Setter for the http status code - * @param status the http status code - */ - void setHttpStatus( short status ); + /** + * Setter for the http status code + * + * @param status the http status code + */ + void setHttpStatus(short status); - /** - * Setter for the http status message - * @param message the http status message - */ - void setHttpStatusMessage( String message ); + /** + * Setter for the http status message + * + * @param message the http status message + */ + void setHttpStatusMessage(String message); } diff --git a/src/main/java/org/java_websocket/handshake/package-info.java b/src/main/java/org/java_websocket/handshake/package-info.java index c9ba3c6fe..7af26d497 100644 --- a/src/main/java/org/java_websocket/handshake/package-info.java +++ b/src/main/java/org/java_websocket/handshake/package-info.java @@ -24,7 +24,8 @@ */ /** - * This package encapsulates all interfaces and implementations in relation with the WebSocket handshake. + * This package encapsulates all interfaces and implementations in relation with the WebSocket + * handshake. */ package org.java_websocket.handshake; diff --git a/src/main/java/org/java_websocket/interfaces/ISSLChannel.java b/src/main/java/org/java_websocket/interfaces/ISSLChannel.java index 6bfb6d5fa..c783c5844 100644 --- a/src/main/java/org/java_websocket/interfaces/ISSLChannel.java +++ b/src/main/java/org/java_websocket/interfaces/ISSLChannel.java @@ -35,9 +35,10 @@ */ public interface ISSLChannel { - /** - * Get the ssl engine used for the de- and encryption of the communication. - * @return the ssl engine of this channel - */ - SSLEngine getSSLEngine(); + /** + * Get the ssl engine used for the de- and encryption of the communication. + * + * @return the ssl engine of this channel + */ + SSLEngine getSSLEngine(); } diff --git a/src/main/java/org/java_websocket/protocols/IProtocol.java b/src/main/java/org/java_websocket/protocols/IProtocol.java index 03ebe5a24..5300aed2a 100644 --- a/src/main/java/org/java_websocket/protocols/IProtocol.java +++ b/src/main/java/org/java_websocket/protocols/IProtocol.java @@ -32,36 +32,41 @@ */ public interface IProtocol { - /** - * Check if the received Sec-WebSocket-Protocol header field contains a offer for the specific protocol - * - * @param inputProtocolHeader the received Sec-WebSocket-Protocol header field offered by the other endpoint - * @return true, if the offer does fit to this specific protocol - * @since 1.3.7 - */ - boolean acceptProvidedProtocol( String inputProtocolHeader ); + /** + * Check if the received Sec-WebSocket-Protocol header field contains a offer for the specific + * protocol + * + * @param inputProtocolHeader the received Sec-WebSocket-Protocol header field offered by the + * other endpoint + * @return true, if the offer does fit to this specific protocol + * @since 1.3.7 + */ + boolean acceptProvidedProtocol(String inputProtocolHeader); - /** - * Return the specific Sec-WebSocket-protocol header offer for this protocol if the endpoint. - * If the extension returns an empty string (""), the offer will not be included in the handshake. - * - * @return the specific Sec-WebSocket-Protocol header for this protocol - * @since 1.3.7 - */ - String getProvidedProtocol(); + /** + * Return the specific Sec-WebSocket-protocol header offer for this protocol if the endpoint. If + * the extension returns an empty string (""), the offer will not be included in the handshake. + * + * @return the specific Sec-WebSocket-Protocol header for this protocol + * @since 1.3.7 + */ + String getProvidedProtocol(); - /** - * To prevent protocols to be used more than once the Websocket implementation should call this method in order to create a new usable version of a given protocol instance. - * @return a copy of the protocol - * @since 1.3.7 - */ - IProtocol copyInstance(); + /** + * To prevent protocols to be used more than once the Websocket implementation should call this + * method in order to create a new usable version of a given protocol instance. + * + * @return a copy of the protocol + * @since 1.3.7 + */ + IProtocol copyInstance(); - /** - * Return a string which should contain the protocol name as well as additional information about the current configurations for this protocol (DEBUG purposes) - * - * @return a string containing the protocol name as well as additional information - * @since 1.3.7 - */ - String toString(); + /** + * Return a string which should contain the protocol name as well as additional information about + * the current configurations for this protocol (DEBUG purposes) + * + * @return a string containing the protocol name as well as additional information + * @since 1.3.7 + */ + String toString(); } diff --git a/src/main/java/org/java_websocket/protocols/Protocol.java b/src/main/java/org/java_websocket/protocols/Protocol.java index 9c63115a9..f7fbfb58b 100644 --- a/src/main/java/org/java_websocket/protocols/Protocol.java +++ b/src/main/java/org/java_websocket/protocols/Protocol.java @@ -34,68 +34,72 @@ */ public class Protocol implements IProtocol { - private static final Pattern patternSpace = Pattern.compile(" "); - private static final Pattern patternComma = Pattern.compile(","); + private static final Pattern patternSpace = Pattern.compile(" "); + private static final Pattern patternComma = Pattern.compile(","); - /** - * Attribute for the provided protocol - */ - private final String providedProtocol; + /** + * Attribute for the provided protocol + */ + private final String providedProtocol; - /** - * Constructor for a Sec-Websocket-Protocol - * - * @param providedProtocol the protocol string - */ - public Protocol( String providedProtocol ) { - if( providedProtocol == null ) { - throw new IllegalArgumentException(); - } - this.providedProtocol = providedProtocol; - } + /** + * Constructor for a Sec-Websocket-Protocol + * + * @param providedProtocol the protocol string + */ + public Protocol(String providedProtocol) { + if (providedProtocol == null) { + throw new IllegalArgumentException(); + } + this.providedProtocol = providedProtocol; + } - @Override - public boolean acceptProvidedProtocol( String inputProtocolHeader ) { - if ("".equals(providedProtocol)) { - return true; - } - String protocolHeader = patternSpace.matcher(inputProtocolHeader).replaceAll(""); - String[] headers = patternComma.split(protocolHeader); - for( String header : headers ) { - if( providedProtocol.equals( header ) ) { - return true; - } - } - return false; - } + @Override + public boolean acceptProvidedProtocol(String inputProtocolHeader) { + if ("".equals(providedProtocol)) { + return true; + } + String protocolHeader = patternSpace.matcher(inputProtocolHeader).replaceAll(""); + String[] headers = patternComma.split(protocolHeader); + for (String header : headers) { + if (providedProtocol.equals(header)) { + return true; + } + } + return false; + } - @Override - public String getProvidedProtocol() { - return this.providedProtocol; - } + @Override + public String getProvidedProtocol() { + return this.providedProtocol; + } - @Override - public IProtocol copyInstance() { - return new Protocol( getProvidedProtocol() ); - } + @Override + public IProtocol copyInstance() { + return new Protocol(getProvidedProtocol()); + } - @Override - public String toString() { - return getProvidedProtocol(); - } + @Override + public String toString() { + return getProvidedProtocol(); + } - @Override - public boolean equals( Object o ) { - if( this == o ) return true; - if( o == null || getClass() != o.getClass() ) return false; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } - Protocol protocol = ( Protocol ) o; + Protocol protocol = (Protocol) o; - return providedProtocol.equals( protocol.providedProtocol ); - } + return providedProtocol.equals(protocol.providedProtocol); + } - @Override - public int hashCode() { - return providedProtocol.hashCode(); - } + @Override + public int hashCode() { + return providedProtocol.hashCode(); + } } diff --git a/src/main/java/org/java_websocket/protocols/package-info.java b/src/main/java/org/java_websocket/protocols/package-info.java index 52016edd1..6f8132b55 100644 --- a/src/main/java/org/java_websocket/protocols/package-info.java +++ b/src/main/java/org/java_websocket/protocols/package-info.java @@ -24,6 +24,7 @@ */ /** - * This package encapsulates all interfaces and implementations in relation with the WebSocket Sec-WebSocket-Protocol. + * This package encapsulates all interfaces and implementations in relation with the WebSocket + * Sec-WebSocket-Protocol. */ package org.java_websocket.protocols; \ No newline at end of file diff --git a/src/main/java/org/java_websocket/server/CustomSSLWebSocketServerFactory.java b/src/main/java/org/java_websocket/server/CustomSSLWebSocketServerFactory.java index a5900c2ab..6fc0c6970 100644 --- a/src/main/java/org/java_websocket/server/CustomSSLWebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/server/CustomSSLWebSocketServerFactory.java @@ -41,52 +41,61 @@ */ public class CustomSSLWebSocketServerFactory extends DefaultSSLWebSocketServerFactory { - /** - * The enabled protocols saved as a String array - */ - private final String[] enabledProtocols; + /** + * The enabled protocols saved as a String array + */ + private final String[] enabledProtocols; - /** - * The enabled ciphersuites saved as a String array - */ - private final String[] enabledCiphersuites; + /** + * The enabled ciphersuites saved as a String array + */ + private final String[] enabledCiphersuites; - /** - * New CustomSSLWebSocketServerFactory configured to only support given protocols and given cipher suites. - * - * @param sslContext - can not be null - * @param enabledProtocols - only these protocols are enabled, when null default settings will be used. - * @param enabledCiphersuites - only these cipher suites are enabled, when null default settings will be used. - */ - public CustomSSLWebSocketServerFactory(SSLContext sslContext, String[] enabledProtocols, String[] enabledCiphersuites) { - this(sslContext, Executors.newSingleThreadScheduledExecutor(), enabledProtocols, enabledCiphersuites); - } + /** + * New CustomSSLWebSocketServerFactory configured to only support given protocols and given cipher + * suites. + * + * @param sslContext - can not be null + * @param enabledProtocols - only these protocols are enabled, when null default + * settings will be used. + * @param enabledCiphersuites - only these cipher suites are enabled, when null + * default settings will be used. + */ + public CustomSSLWebSocketServerFactory(SSLContext sslContext, String[] enabledProtocols, + String[] enabledCiphersuites) { + this(sslContext, Executors.newSingleThreadScheduledExecutor(), enabledProtocols, + enabledCiphersuites); + } - /** - * New CustomSSLWebSocketServerFactory configured to only support given protocols and given cipher suites. - * - * @param sslContext - can not be null - * @param executerService - can not be null - * @param enabledProtocols - only these protocols are enabled, when null default settings will be used. - * @param enabledCiphersuites - only these cipher suites are enabled, when null default settings will be used. - */ - public CustomSSLWebSocketServerFactory(SSLContext sslContext, ExecutorService executerService, String[] enabledProtocols, String[] enabledCiphersuites) { - super(sslContext, executerService); - this.enabledProtocols = enabledProtocols; - this.enabledCiphersuites = enabledCiphersuites; - } + /** + * New CustomSSLWebSocketServerFactory configured to only support given protocols and given cipher + * suites. + * + * @param sslContext - can not be null + * @param executerService - can not be null + * @param enabledProtocols - only these protocols are enabled, when null default + * settings will be used. + * @param enabledCiphersuites - only these cipher suites are enabled, when null + * default settings will be used. + */ + public CustomSSLWebSocketServerFactory(SSLContext sslContext, ExecutorService executerService, + String[] enabledProtocols, String[] enabledCiphersuites) { + super(sslContext, executerService); + this.enabledProtocols = enabledProtocols; + this.enabledCiphersuites = enabledCiphersuites; + } - @Override - public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException { - SSLEngine e = sslcontext.createSSLEngine(); - if (enabledProtocols != null) { - e.setEnabledProtocols(enabledProtocols); - } - if (enabledCiphersuites != null) { - e.setEnabledCipherSuites(enabledCiphersuites); - } - e.setUseClientMode(false); - return new SSLSocketChannel2(channel, e, exec, key); + @Override + public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException { + SSLEngine e = sslcontext.createSSLEngine(); + if (enabledProtocols != null) { + e.setEnabledProtocols(enabledProtocols); + } + if (enabledCiphersuites != null) { + e.setEnabledCipherSuites(enabledCiphersuites); } + e.setUseClientMode(false); + return new SSLSocketChannel2(channel, e, exec, key); + } } \ No newline at end of file diff --git a/src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java b/src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java index 0874287e7..0af105e3c 100644 --- a/src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java @@ -24,6 +24,7 @@ */ package org.java_websocket.server; + import java.io.IOException; import java.nio.channels.ByteChannel; import java.nio.channels.SelectionKey; @@ -41,47 +42,50 @@ import org.java_websocket.drafts.Draft; public class DefaultSSLWebSocketServerFactory implements WebSocketServerFactory { - protected SSLContext sslcontext; - protected ExecutorService exec; - public DefaultSSLWebSocketServerFactory( SSLContext sslContext ) { - this( sslContext, Executors.newSingleThreadScheduledExecutor() ); - } + protected SSLContext sslcontext; + protected ExecutorService exec; + + public DefaultSSLWebSocketServerFactory(SSLContext sslContext) { + this(sslContext, Executors.newSingleThreadScheduledExecutor()); + } + + public DefaultSSLWebSocketServerFactory(SSLContext sslContext, ExecutorService exec) { + if (sslContext == null || exec == null) { + throw new IllegalArgumentException(); + } + this.sslcontext = sslContext; + this.exec = exec; + } - public DefaultSSLWebSocketServerFactory( SSLContext sslContext , ExecutorService exec ) { - if( sslContext == null || exec == null ) - throw new IllegalArgumentException(); - this.sslcontext = sslContext; - this.exec = exec; - } + @Override + public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException { + SSLEngine e = sslcontext.createSSLEngine(); + /* + * See https://github.com/TooTallNate/Java-WebSocket/issues/466 + * + * We remove TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 from the enabled ciphers since it is just available when you patch your java installation directly. + * E.g. firefox requests this cipher and this causes some dcs/instable connections + */ + List ciphers = new ArrayList(Arrays.asList(e.getEnabledCipherSuites())); + ciphers.remove("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"); + e.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()])); + e.setUseClientMode(false); + return new SSLSocketChannel2(channel, e, exec, key); + } - @Override - public ByteChannel wrapChannel( SocketChannel channel, SelectionKey key ) throws IOException { - SSLEngine e = sslcontext.createSSLEngine(); - /* - * See https://github.com/TooTallNate/Java-WebSocket/issues/466 - * - * We remove TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 from the enabled ciphers since it is just available when you patch your java installation directly. - * E.g. firefox requests this cipher and this causes some dcs/instable connections - */ - List ciphers = new ArrayList( Arrays.asList(e.getEnabledCipherSuites())); - ciphers.remove("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"); - e.setEnabledCipherSuites( ciphers.toArray( new String[ciphers.size()] ) ); - e.setUseClientMode( false ); - return new SSLSocketChannel2( channel, e, exec, key ); - } + @Override + public WebSocketImpl createWebSocket(WebSocketAdapter a, Draft d) { + return new WebSocketImpl(a, d); + } - @Override - public WebSocketImpl createWebSocket( WebSocketAdapter a, Draft d) { - return new WebSocketImpl( a, d ); - } + @Override + public WebSocketImpl createWebSocket(WebSocketAdapter a, List d) { + return new WebSocketImpl(a, d); + } - @Override - public WebSocketImpl createWebSocket( WebSocketAdapter a, List d) { - return new WebSocketImpl( a, d ); - } - @Override - public void close() { - exec.shutdown(); - } + @Override + public void close() { + exec.shutdown(); + } } \ No newline at end of file diff --git a/src/main/java/org/java_websocket/server/DefaultWebSocketServerFactory.java b/src/main/java/org/java_websocket/server/DefaultWebSocketServerFactory.java index ec2e75767..8e9c7a197 100644 --- a/src/main/java/org/java_websocket/server/DefaultWebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/server/DefaultWebSocketServerFactory.java @@ -35,20 +35,24 @@ import org.java_websocket.WebSocketServerFactory; public class DefaultWebSocketServerFactory implements WebSocketServerFactory { - @Override - public WebSocketImpl createWebSocket( WebSocketAdapter a, Draft d) { - return new WebSocketImpl( a, d ); - } - @Override - public WebSocketImpl createWebSocket( WebSocketAdapter a, List d) { - return new WebSocketImpl( a, d ); - } - @Override - public SocketChannel wrapChannel( SocketChannel channel, SelectionKey key ) { - return channel; - } - @Override - public void close() { - //Nothing to do for a normal ws factory - } + + @Override + public WebSocketImpl createWebSocket(WebSocketAdapter a, Draft d) { + return new WebSocketImpl(a, d); + } + + @Override + public WebSocketImpl createWebSocket(WebSocketAdapter a, List d) { + return new WebSocketImpl(a, d); + } + + @Override + public SocketChannel wrapChannel(SocketChannel channel, SelectionKey key) { + return channel; + } + + @Override + public void close() { + //Nothing to do for a normal ws factory + } } \ No newline at end of file diff --git a/src/main/java/org/java_websocket/server/SSLParametersWebSocketServerFactory.java b/src/main/java/org/java_websocket/server/SSLParametersWebSocketServerFactory.java index 3f78a9976..a98474dd5 100644 --- a/src/main/java/org/java_websocket/server/SSLParametersWebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/server/SSLParametersWebSocketServerFactory.java @@ -45,23 +45,26 @@ public class SSLParametersWebSocketServerFactory extends DefaultSSLWebSocketServ private final SSLParameters sslParameters; /** - * New CustomSSLWebSocketServerFactory configured to only support given protocols and given cipher suites. + * New CustomSSLWebSocketServerFactory configured to only support given protocols and given cipher + * suites. * - * @param sslContext - can not be null - * @param sslParameters - can not be null + * @param sslContext - can not be null + * @param sslParameters - can not be null */ public SSLParametersWebSocketServerFactory(SSLContext sslContext, SSLParameters sslParameters) { this(sslContext, Executors.newSingleThreadScheduledExecutor(), sslParameters); } /** - * New CustomSSLWebSocketServerFactory configured to only support given protocols and given cipher suites. + * New CustomSSLWebSocketServerFactory configured to only support given protocols and given cipher + * suites. * - * @param sslContext - can not be null - * @param executerService - can not be null - * @param sslParameters - can not be null + * @param sslContext - can not be null + * @param executerService - can not be null + * @param sslParameters - can not be null */ - public SSLParametersWebSocketServerFactory(SSLContext sslContext, ExecutorService executerService, SSLParameters sslParameters) { + public SSLParametersWebSocketServerFactory(SSLContext sslContext, ExecutorService executerService, + SSLParameters sslParameters) { super(sslContext, executerService); if (sslParameters == null) { throw new IllegalArgumentException(); diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 0e73523b9..d46e46065 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -55,1001 +55,1036 @@ /** * WebSocketServer is an abstract class that only takes care of the - * HTTP handshake portion of WebSockets. It's up to a subclass to add - * functionality/purpose to the server. - * + * HTTP handshake portion of WebSockets. It's up to a subclass to add functionality/purpose to the + * server. */ public abstract class WebSocketServer extends AbstractWebSocket implements Runnable { - private static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); - - /** - * Logger instance - * - * @since 1.4.0 - */ - private final Logger log = LoggerFactory.getLogger(WebSocketServer.class); - - /** - * Holds the list of active WebSocket connections. "Active" means WebSocket - * handshake is complete and socket can be written to, or read from. - */ - private final Collection connections; - /** - * The port number that this WebSocket server should listen on. Default is - * WebSocketImpl.DEFAULT_PORT. - */ - private final InetSocketAddress address; - /** - * The socket channel for this WebSocket server. - */ - private ServerSocketChannel server; - /** - * The 'Selector' used to get event keys from the underlying socket. - */ - private Selector selector; - /** - * The Draft of the WebSocket protocol the Server is adhering to. - */ - private List drafts; - - private Thread selectorthread; - - private final AtomicBoolean isclosed = new AtomicBoolean( false ); - - protected List decoders; - - private List iqueue; - private BlockingQueue buffers; - private int queueinvokes = 0; - private final AtomicInteger queuesize = new AtomicInteger( 0 ); - - private WebSocketServerFactory wsf = new DefaultWebSocketServerFactory(); - - /** - * Attribute which allows you to configure the socket "backlog" parameter - * which determines how many client connections can be queued. - * @since 1.5.0 - */ - private int maxPendingConnections = -1; - - /** - * Creates a WebSocketServer that will attempt to - * listen on port WebSocketImpl.DEFAULT_PORT. - * - * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here - */ - public WebSocketServer() { - this( new InetSocketAddress( WebSocketImpl.DEFAULT_PORT ), AVAILABLE_PROCESSORS, null ); - } - - /** - * Creates a WebSocketServer that will attempt to bind/listen on the given address. - * - * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here - * @param address The address to listen to - */ - public WebSocketServer( InetSocketAddress address ) { - this( address, AVAILABLE_PROCESSORS, null ); - } - - /** - * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here - * @param address - * The address (host:port) this server should listen on. - * @param decodercount - * The number of {@link WebSocketWorker}s that will be used to process the incoming network data. By default this will be Runtime.getRuntime().availableProcessors() - */ - public WebSocketServer( InetSocketAddress address , int decodercount ) { - this( address, decodercount, null ); - } - - /** - * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here - * - * @param address - * The address (host:port) this server should listen on. - * @param drafts - * The versions of the WebSocket protocol that this server - * instance should comply to. Clients that use an other protocol version will be rejected. - * - */ - public WebSocketServer( InetSocketAddress address , List drafts ) { - this( address, AVAILABLE_PROCESSORS, drafts ); - } - - /** - * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here - * - * @param address - * The address (host:port) this server should listen on. - * @param decodercount - * The number of {@link WebSocketWorker}s that will be used to process the incoming network data. By default this will be Runtime.getRuntime().availableProcessors() - * @param drafts - * The versions of the WebSocket protocol that this server - * instance should comply to. Clients that use an other protocol version will be rejected. - - */ - public WebSocketServer( InetSocketAddress address , int decodercount , List drafts ) { - this( address, decodercount, drafts, new HashSet() ); - } - - /** - * Creates a WebSocketServer that will attempt to bind/listen on the given address, - * and comply with Draft version draft. - * - * @param address - * The address (host:port) this server should listen on. - * @param decodercount - * The number of {@link WebSocketWorker}s that will be used to process the incoming network data. By default this will be Runtime.getRuntime().availableProcessors() - * @param drafts - * The versions of the WebSocket protocol that this server - * instance should comply to. Clients that use an other protocol version will be rejected. - * - * @param connectionscontainer - * Allows to specify a collection that will be used to store the websockets in.
    - * If you plan to often iterate through the currently connected websockets you may want to use a collection that does not require synchronization like a {@link CopyOnWriteArraySet}. In that case make sure that you overload {@link #removeConnection(WebSocket)} and {@link #addConnection(WebSocket)}.
    - * By default a {@link HashSet} will be used. - * - * @see #removeConnection(WebSocket) for more control over syncronized operation - * @see more about drafts - */ - public WebSocketServer( InetSocketAddress address , int decodercount , List drafts , Collection connectionscontainer ) { - if( address == null || decodercount < 1 || connectionscontainer == null ) { - throw new IllegalArgumentException( "address and connectionscontainer must not be null and you need at least 1 decoder" ); - } - - if( drafts == null ) - this.drafts = Collections.emptyList(); - else - this.drafts = drafts; - - this.address = address; - this.connections = connectionscontainer; - setTcpNoDelay(false); - setReuseAddr(false); - iqueue = new LinkedList(); - - decoders = new ArrayList( decodercount ); - buffers = new LinkedBlockingQueue(); - for( int i = 0 ; i < decodercount ; i++ ) { - WebSocketWorker ex = new WebSocketWorker(); - decoders.add( ex ); - } - } - - - /** - * Starts the server selectorthread that binds to the currently set port number and - * listeners for WebSocket connection requests. Creates a fixed thread pool with the size {@link WebSocketServer#AVAILABLE_PROCESSORS}
    - * May only be called once. - * - * Alternatively you can call {@link WebSocketServer#run()} directly. - * - * @throws IllegalStateException Starting an instance again - */ - public void start() { - if( selectorthread != null ) - throw new IllegalStateException( getClass().getName() + " can only be started once." ); - new Thread( this ).start(); - } - - /** - * Closes all connected clients sockets, then closes the underlying - * ServerSocketChannel, effectively killing the server socket selectorthread, - * freeing the port the server was bound to and stops all internal workerthreads. - * - * If this method is called before the server is started it will never start. - * - * @param timeout - * Specifies how many milliseconds the overall close handshaking may take altogether before the connections are closed without proper close handshaking.
    - * - * @throws InterruptedException Interrupt - */ - public void stop( int timeout ) throws InterruptedException { - if( !isclosed.compareAndSet( false, true ) ) { // this also makes sure that no further connections will be added to this.connections - return; - } - - List socketsToClose; - - // copy the connections in a list (prevent callback deadlocks) - synchronized ( connections ) { - socketsToClose = new ArrayList( connections ); - } - - for( WebSocket ws : socketsToClose ) { - ws.close( CloseFrame.GOING_AWAY ); - } - - wsf.close(); - - synchronized ( this ) { - if( selectorthread != null && selector != null) { - selector.wakeup(); - selectorthread.join( timeout ); - } - } - } - public void stop() throws IOException , InterruptedException { - stop( 0 ); - } - - /** - * Returns all currently connected clients. - * This collection does not allow any modification e.g. removing a client. - * - * @return A unmodifiable collection of all currently connected clients - * @since 1.3.8 - */ - public Collection getConnections() { - synchronized (connections) { - return Collections.unmodifiableCollection( new ArrayList(connections) ); - } - } - - public InetSocketAddress getAddress() { - return this.address; - } - - /** - * Gets the port number that this server listens on. - * - * @return The port number. - */ - public int getPort() { - int port = getAddress().getPort(); - if( port == 0 && server != null ) { - port = server.socket().getLocalPort(); - } - return port; - } - - /** - * Get the list of active drafts - * @return the available drafts for this server - */ - public List getDraft() { - return Collections.unmodifiableList( drafts ); - } - - /** - * Set the requested maximum number of pending connections on the socket. The exact semantics are implementation - * specific. The value provided should be greater than 0. If it is less than or equal to 0, then - * an implementation specific default will be used. This option will be passed as "backlog" parameter to {@link ServerSocket#bind(SocketAddress, int)} - * @since 1.5.0 - */ - public void setMaxPendingConnections(int numberOfConnections) { - maxPendingConnections = numberOfConnections; - } - - /** - * Returns the currently configured maximum number of pending connections. - * - * @see #setMaxPendingConnections(int) - * @since 1.5.0 - */ - public int getMaxPendingConnections() { - return maxPendingConnections; - } - - // Runnable IMPLEMENTATION ///////////////////////////////////////////////// - public void run() { - if (!doEnsureSingleThread()) { - return; - } - if (!doSetupSelectorAndServerThread()) { - return; - } - try { - int iShutdownCount = 5; - int selectTimeout = 0; - while ( !selectorthread.isInterrupted() && iShutdownCount != 0) { - SelectionKey key = null; - try { - if (isclosed.get()) { - selectTimeout = 5; - } - int keyCount = selector.select( selectTimeout ); - if (keyCount == 0 && isclosed.get()) { - iShutdownCount--; - } - Set keys = selector.selectedKeys(); - Iterator i = keys.iterator(); - - while ( i.hasNext() ) { - key = i.next(); - - if( !key.isValid() ) { - continue; - } - - if( key.isAcceptable() ) { - doAccept(key, i); - continue; - } - - if( key.isReadable() && !doRead(key, i)) { - continue; - } - - if( key.isWritable() ) { - doWrite(key); - } - } - doAdditionalRead(); - } catch ( CancelledKeyException e ) { - // an other thread may cancel the key - } catch ( ClosedByInterruptException e ) { - return; // do the same stuff as when InterruptedException is thrown - } catch ( WrappedIOException ex) { - handleIOException( key, ex.getConnection(), ex.getIOException()); - } catch ( IOException ex ) { - handleIOException( key, null, ex ); - } catch ( InterruptedException e ) { - // FIXME controlled shutdown (e.g. take care of buffermanagement) - Thread.currentThread().interrupt(); - } - } - } catch ( RuntimeException e ) { - // should hopefully never occur - handleFatal( null, e ); - } finally { - doServerShutdown(); - } - } - - /** - * Do an additional read - * @throws InterruptedException thrown by taking a buffer - * @throws IOException if an error happened during read - */ - private void doAdditionalRead() throws InterruptedException, IOException { - WebSocketImpl conn; - while ( !iqueue.isEmpty() ) { - conn = iqueue.remove( 0 ); - WrappedByteChannel c = ( (WrappedByteChannel) conn.getChannel() ); - ByteBuffer buf = takeBuffer(); - try { - if( SocketChannelIOHelper.readMore( buf, conn, c ) ) - iqueue.add( conn ); - if( buf.hasRemaining() ) { - conn.inQueue.put( buf ); - queue( conn ); - } else { - pushBuffer( buf ); - } - } catch ( IOException e ) { - pushBuffer( buf ); - throw e; - } - } - } - - /** - * Execute a accept operation - * @param key the selectionkey to read off - * @param i the iterator for the selection keys - * @throws InterruptedException thrown by taking a buffer - * @throws IOException if an error happened during accept - */ - private void doAccept(SelectionKey key, Iterator i) throws IOException, InterruptedException { - if( !onConnect( key ) ) { - key.cancel(); - return; - } - - SocketChannel channel = server.accept(); - if(channel==null){ - return; - } - channel.configureBlocking( false ); - Socket socket = channel.socket(); - socket.setTcpNoDelay( isTcpNoDelay() ); - socket.setKeepAlive( true ); - WebSocketImpl w = wsf.createWebSocket( this, drafts ); - w.setSelectionKey(channel.register( selector, SelectionKey.OP_READ, w )); - try { - w.setChannel( wsf.wrapChannel( channel, w.getSelectionKey() )); - i.remove(); - allocateBuffers( w ); - } catch (IOException ex) { - if( w.getSelectionKey() != null ) - w.getSelectionKey().cancel(); - - handleIOException( w.getSelectionKey(), null, ex ); - } - } - - /** - * Execute a read operation - * @param key the selectionkey to read off - * @param i the iterator for the selection keys - * @return true, if the read was successful, or false if there was an error - * @throws InterruptedException thrown by taking a buffer - * @throws IOException if an error happened during read - */ - private boolean doRead(SelectionKey key, Iterator i) throws InterruptedException, WrappedIOException { - WebSocketImpl conn = (WebSocketImpl) key.attachment(); - ByteBuffer buf = takeBuffer(); - if(conn.getChannel() == null){ - key.cancel(); - - handleIOException( key, conn, new IOException() ); - return false; - } - try { - if( SocketChannelIOHelper.read( buf, conn, conn.getChannel() ) ) { - if( buf.hasRemaining() ) { - conn.inQueue.put( buf ); - queue( conn ); - i.remove(); - if( conn.getChannel() instanceof WrappedByteChannel && ( (WrappedByteChannel) conn.getChannel() ).isNeedRead() ) { - iqueue.add( conn ); - } - } else { - pushBuffer(buf); - } - } else { - pushBuffer( buf ); - } - } catch ( IOException e ) { - pushBuffer( buf ); - throw new WrappedIOException(conn, e); - } - return true; - } - - /** - * Execute a write operation - * @param key the selectionkey to write on - * @throws IOException if an error happened during batch - */ - private void doWrite(SelectionKey key) throws WrappedIOException { - WebSocketImpl conn = (WebSocketImpl) key.attachment(); - try { - if (SocketChannelIOHelper.batch(conn, conn.getChannel())) { - if (key.isValid()) { - key.interestOps(SelectionKey.OP_READ); - } - } - } catch (IOException e) { - throw new WrappedIOException(conn, e); - } - } - - /** - * Setup the selector thread as well as basic server settings - * @return true, if everything was successful, false if some error happened - */ - private boolean doSetupSelectorAndServerThread() { - selectorthread.setName( "WebSocketSelector-" + selectorthread.getId() ); - try { - server = ServerSocketChannel.open(); - server.configureBlocking( false ); - ServerSocket socket = server.socket(); - socket.setReceiveBufferSize( WebSocketImpl.RCVBUF ); - socket.setReuseAddress( isReuseAddr() ); - socket.bind( address, getMaxPendingConnections() ); - selector = Selector.open(); - server.register( selector, server.validOps() ); - startConnectionLostTimer(); - for( WebSocketWorker ex : decoders ){ - ex.start(); - } - onStart(); - } catch ( IOException ex ) { - handleFatal( null, ex ); - return false; - } - return true; - } - - /** - * The websocket server can only be started once - * @return true, if the server can be started, false if already a thread is running - */ - private boolean doEnsureSingleThread() { - synchronized ( this ) { - if( selectorthread != null ) - throw new IllegalStateException( getClass().getName() + " can only be started once." ); - selectorthread = Thread.currentThread(); - if( isclosed.get() ) { - return false; - } - } - return true; - } - - /** - * Clean up everything after a shutdown - */ - private void doServerShutdown() { - stopConnectionLostTimer(); - if( decoders != null ) { - for( WebSocketWorker w : decoders ) { - w.interrupt(); - } - } - if( selector != null ) { - try { - selector.close(); - } catch ( IOException e ) { - log.error( "IOException during selector.close", e ); - onError( null, e ); - } - } - if( server != null ) { - try { - server.close(); - } catch ( IOException e ) { - log.error( "IOException during server.close", e ); - onError( null, e ); - } - } - } - - protected void allocateBuffers( WebSocket c ) throws InterruptedException { - if( queuesize.get() >= 2 * decoders.size() + 1 ) { - return; - } - queuesize.incrementAndGet(); - buffers.put( createBuffer() ); - } - - protected void releaseBuffers( WebSocket c ) throws InterruptedException { - // queuesize.decrementAndGet(); - // takeBuffer(); - } - - public ByteBuffer createBuffer() { - return ByteBuffer.allocate( WebSocketImpl.RCVBUF ); - } - - protected void queue( WebSocketImpl ws ) throws InterruptedException { - if( ws.getWorkerThread() == null ) { - ws.setWorkerThread(decoders.get( queueinvokes % decoders.size() )); - queueinvokes++; - } - ws.getWorkerThread().put( ws ); - } - - private ByteBuffer takeBuffer() throws InterruptedException { - return buffers.take(); - } - - private void pushBuffer( ByteBuffer buf ) throws InterruptedException { - if( buffers.size() > queuesize.intValue() ) - return; - buffers.put( buf ); - } - - private void handleIOException( SelectionKey key, WebSocket conn, IOException ex ) { - // onWebsocketError( conn, ex );// conn may be null here - if (key != null) { - key.cancel(); - } - if( conn != null ) { - conn.closeConnection( CloseFrame.ABNORMAL_CLOSE, ex.getMessage() ); - } else if( key != null ) { - SelectableChannel channel = key.channel(); - if( channel != null && channel.isOpen() ) { // this could be the case if the IOException ex is a SSLException - try { - channel.close(); - } catch ( IOException e ) { - // there is nothing that must be done here - } - log.trace("Connection closed because of exception",ex); - } - } - } - - private void handleFatal( WebSocket conn, Exception e ) { - log.error( "Shutdown due to fatal error", e ); - onError( conn, e ); - //Shutting down WebSocketWorkers, see #222 - if( decoders != null ) { - for( WebSocketWorker w : decoders ) { - w.interrupt(); - } - } - if (selectorthread != null) { - selectorthread.interrupt(); - } - try { - stop(); - } catch ( IOException e1 ) { - log.error( "Error during shutdown", e1 ); - onError( null, e1 ); - } catch ( InterruptedException e1 ) { - Thread.currentThread().interrupt(); - log.error( "Interrupt during stop", e ); - onError( null, e1 ); - } - } - - @Override - public final void onWebsocketMessage( WebSocket conn, String message ) { - onMessage( conn, message ); - } - - - @Override - public final void onWebsocketMessage( WebSocket conn, ByteBuffer blob ) { - onMessage( conn, blob ); - } - - @Override - public final void onWebsocketOpen( WebSocket conn, Handshakedata handshake ) { - if( addConnection( conn ) ) { - onOpen( conn, (ClientHandshake) handshake ); - } - } - - @Override - public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) { - selector.wakeup(); - try { - if( removeConnection( conn ) ) { - onClose( conn, code, reason, remote ); - } - } finally { - try { - releaseBuffers( conn ); - } catch ( InterruptedException e ) { - Thread.currentThread().interrupt(); - } - } - - } - - /** - * This method performs remove operations on the connection and therefore also gives control over whether the operation shall be synchronized - *

    - * {@link #WebSocketServer(InetSocketAddress, int, List, Collection)} allows to specify a collection which will be used to store current connections in.
    - * Depending on the type on the connection, modifications of that collection may have to be synchronized. - * @param ws The Websocket connection which should be removed - * @return Removing connection successful - */ - protected boolean removeConnection( WebSocket ws ) { - boolean removed = false; - synchronized ( connections ) { - if (this.connections.contains( ws )) { - removed = this.connections.remove( ws ); - } else { - //Don't throw an assert error if the ws is not in the list. e.g. when the other endpoint did not send any handshake. see #512 - log.trace("Removing connection which is not in the connections collection! Possible no handshake received! {}", ws); - } - } - if( isclosed.get() && connections.isEmpty() ) { - selectorthread.interrupt(); - } - return removed; - } - - /** - * @see #removeConnection(WebSocket) - * @param ws the Websocket connection which should be added - * @return Adding connection successful - */ - protected boolean addConnection( WebSocket ws ) { - if( !isclosed.get() ) { - synchronized ( connections ) { - return this.connections.add( ws ); - } - } else { - // This case will happen when a new connection gets ready while the server is already stopping. - ws.close( CloseFrame.GOING_AWAY ); - return true;// for consistency sake we will make sure that both onOpen will be called - } - } - - @Override - public final void onWebsocketError( WebSocket conn, Exception ex ) { - onError( conn, ex ); - } - - @Override - public final void onWriteDemand( WebSocket w ) { - WebSocketImpl conn = (WebSocketImpl) w; - try { - conn.getSelectionKey().interestOps( SelectionKey.OP_READ | SelectionKey.OP_WRITE ); - } catch ( CancelledKeyException e ) { - // the thread which cancels key is responsible for possible cleanup - conn.outQueue.clear(); - } - selector.wakeup(); - } - - @Override - public void onWebsocketCloseInitiated( WebSocket conn, int code, String reason ) { - onCloseInitiated( conn, code, reason ); - } - - @Override - public void onWebsocketClosing( WebSocket conn, int code, String reason, boolean remote ) { - onClosing( conn, code, reason, remote ); - - } - - public void onCloseInitiated( WebSocket conn, int code, String reason ) { - } - - public void onClosing( WebSocket conn, int code, String reason, boolean remote ) { - - } - - public final void setWebSocketFactory( WebSocketServerFactory wsf ) { - if (this.wsf != null) - this.wsf.close(); - this.wsf = wsf; - } - - public final WebSocketFactory getWebSocketFactory() { - return wsf; - } - - /** - * Returns whether a new connection shall be accepted or not.
    - * Therefore method is well suited to implement some kind of connection limitation.
    - * - * @see #onOpen(WebSocket, ClientHandshake) - * @see #onWebsocketHandshakeReceivedAsServer(WebSocket, Draft, ClientHandshake) - * @param key the SelectionKey for the new connection - * @return Can this new connection be accepted - **/ - protected boolean onConnect( SelectionKey key ) { - return true; - } - - /** - * Getter to return the socket used by this specific connection - * @param conn The specific connection - * @return The socket used by this connection - */ - private Socket getSocket( WebSocket conn ) { - WebSocketImpl impl = (WebSocketImpl) conn; - return ( (SocketChannel) impl.getSelectionKey().channel() ).socket(); - } - - @Override - public InetSocketAddress getLocalSocketAddress( WebSocket conn ) { - return (InetSocketAddress) getSocket( conn ).getLocalSocketAddress(); - } - - @Override - public InetSocketAddress getRemoteSocketAddress( WebSocket conn ) { - return (InetSocketAddress) getSocket( conn ).getRemoteSocketAddress(); - } - - /** Called after an opening handshake has been performed and the given websocket is ready to be written on. - * @param conn The WebSocket instance this event is occurring on. - * @param handshake The handshake of the websocket instance - */ - public abstract void onOpen( WebSocket conn, ClientHandshake handshake ); - /** - * Called after the websocket connection has been closed. - * - * @param conn The WebSocket instance this event is occurring on. - * @param code - * The codes can be looked up here: {@link CloseFrame} - * @param reason - * Additional information string - * @param remote - * Returns whether or not the closing of the connection was initiated by the remote host. - **/ - public abstract void onClose( WebSocket conn, int code, String reason, boolean remote ); - /** - * Callback for string messages received from the remote host - * - * @see #onMessage(WebSocket, ByteBuffer) - * @param conn The WebSocket instance this event is occurring on. - * @param message The UTF-8 decoded message that was received. - **/ - public abstract void onMessage( WebSocket conn, String message ); - /** - * Called when errors occurs. If an error causes the websocket connection to fail {@link #onClose(WebSocket, int, String, boolean)} will be called additionally.
    - * This method will be called primarily because of IO or protocol errors.
    - * If the given exception is an RuntimeException that probably means that you encountered a bug.
    - * - * @param conn Can be null if there error does not belong to one specific websocket. For example if the servers port could not be bound. - * @param ex The exception causing this error - **/ - public abstract void onError( WebSocket conn, Exception ex ); - - /** - * Called when the server started up successfully. - * - * If any error occurred, onError is called instead. - */ - public abstract void onStart(); - - /** - * Callback for binary messages received from the remote host - * - * @see #onMessage(WebSocket, ByteBuffer) - * - * @param conn - * The WebSocket instance this event is occurring on. - * @param message - * The binary message that was received. - **/ - public void onMessage( WebSocket conn, ByteBuffer message ) { - } - - /** - * Send a text to all connected endpoints - * @param text the text to send to the endpoints - */ - public void broadcast(String text) { - broadcast( text, connections ); - } - - /** - * Send a byte array to all connected endpoints - * @param data the data to send to the endpoints - */ - public void broadcast(byte[] data) { - broadcast( data, connections ); - } - - /** - * Send a ByteBuffer to all connected endpoints - * @param data the data to send to the endpoints - */ - public void broadcast(ByteBuffer data) { - broadcast(data, connections); - } - - /** - * Send a byte array to a specific collection of websocket connections - * @param data the data to send to the endpoints - * @param clients a collection of endpoints to whom the text has to be send - */ - public void broadcast(byte[] data, Collection clients) { - if (data == null || clients == null) { - throw new IllegalArgumentException(); - } - broadcast(ByteBuffer.wrap(data), clients); - } - - /** - * Send a ByteBuffer to a specific collection of websocket connections - * @param data the data to send to the endpoints - * @param clients a collection of endpoints to whom the text has to be send - */ - public void broadcast(ByteBuffer data, Collection clients) { - if (data == null || clients == null) { - throw new IllegalArgumentException(); - } - doBroadcast(data, clients); - } - - /** - * Send a text to a specific collection of websocket connections - * @param text the text to send to the endpoints - * @param clients a collection of endpoints to whom the text has to be send - */ - public void broadcast(String text, Collection clients) { - if (text == null || clients == null) { - throw new IllegalArgumentException(); - } - doBroadcast(text, clients); - } - - /** - * Private method to cache all the frames to improve memory footprint and conversion time - * @param data the data to broadcast - * @param clients the clients to send the message to - */ - private void doBroadcast(Object data, Collection clients) { - String sData = null; - if (data instanceof String) { - sData = (String)data; - } - ByteBuffer bData = null; - if (data instanceof ByteBuffer) { - bData = (ByteBuffer)data; - } - if (sData == null && bData == null) { - return; - } - Map> draftFrames = new HashMap>(); - List clientCopy; - synchronized (clients) { - clientCopy = new ArrayList(clients); - } - for (WebSocket client : clientCopy) { - if (client != null) { - Draft draft = client.getDraft(); - fillFrames(draft, draftFrames, sData, bData); - try { - client.sendFrame(draftFrames.get(draft)); - } catch (WebsocketNotConnectedException e) { - //Ignore this exception in this case - } - } - } - } - - /** - * Fills the draftFrames with new data for the broadcast - * @param draft The draft to use - * @param draftFrames The list of frames per draft to fill - * @param sData the string data, can be null - * @param bData the byte buffer data, can be null - */ - private void fillFrames(Draft draft, Map> draftFrames, String sData, ByteBuffer bData) { - if( !draftFrames.containsKey( draft ) ) { - List frames = null; - if (sData != null) { - frames = draft.createFrames( sData, false ); - } - if (bData != null) { - frames = draft.createFrames( bData, false ); - } - if (frames != null) { - draftFrames.put(draft, frames); - } - } - } - - /** - * This class is used to process incoming data - */ - public class WebSocketWorker extends Thread { - - private BlockingQueue iqueue; - - public WebSocketWorker() { - iqueue = new LinkedBlockingQueue(); - setName( "WebSocketWorker-" + getId() ); - setUncaughtExceptionHandler( new UncaughtExceptionHandler() { - @Override - public void uncaughtException( Thread t, Throwable e ) { - log.error("Uncaught exception in thread {}: {}", t.getName(), e); - } - } ); - } - - public void put( WebSocketImpl ws ) throws InterruptedException { - iqueue.put( ws ); - } - - @Override - public void run() { - WebSocketImpl ws = null; - try { - while ( true ) { - ByteBuffer buf; - ws = iqueue.take(); - buf = ws.inQueue.poll(); - assert ( buf != null ); - doDecode(ws, buf); - ws = null; - } - } catch ( InterruptedException e ) { - Thread.currentThread().interrupt(); - } catch ( RuntimeException e ) { - handleFatal( ws, e ); - } - } - - /** - * call ws.decode on the byteBuffer - * @param ws the Websocket - * @param buf the buffer to decode to - * @throws InterruptedException thrown by pushBuffer - */ - private void doDecode(WebSocketImpl ws, ByteBuffer buf) throws InterruptedException { - try { - ws.decode( buf ); - } catch(Exception e){ - log.error("Error while reading from remote connection", e); - } - finally { - pushBuffer( buf ); - } - } - } + private static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); + + /** + * Logger instance + * + * @since 1.4.0 + */ + private final Logger log = LoggerFactory.getLogger(WebSocketServer.class); + + /** + * Holds the list of active WebSocket connections. "Active" means WebSocket handshake is complete + * and socket can be written to, or read from. + */ + private final Collection connections; + /** + * The port number that this WebSocket server should listen on. Default is + * WebSocketImpl.DEFAULT_PORT. + */ + private final InetSocketAddress address; + /** + * The socket channel for this WebSocket server. + */ + private ServerSocketChannel server; + /** + * The 'Selector' used to get event keys from the underlying socket. + */ + private Selector selector; + /** + * The Draft of the WebSocket protocol the Server is adhering to. + */ + private List drafts; + + private Thread selectorthread; + + private final AtomicBoolean isclosed = new AtomicBoolean(false); + + protected List decoders; + + private List iqueue; + private BlockingQueue buffers; + private int queueinvokes = 0; + private final AtomicInteger queuesize = new AtomicInteger(0); + + private WebSocketServerFactory wsf = new DefaultWebSocketServerFactory(); + + /** + * Attribute which allows you to configure the socket "backlog" parameter which determines how + * many client connections can be queued. + * + * @since 1.5.0 + */ + private int maxPendingConnections = -1; + + /** + * Creates a WebSocketServer that will attempt to listen on port WebSocketImpl.DEFAULT_PORT. + * + * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here + */ + public WebSocketServer() { + this(new InetSocketAddress(WebSocketImpl.DEFAULT_PORT), AVAILABLE_PROCESSORS, null); + } + + /** + * Creates a WebSocketServer that will attempt to bind/listen on the given address. + * + * @param address The address to listen to + * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here + */ + public WebSocketServer(InetSocketAddress address) { + this(address, AVAILABLE_PROCESSORS, null); + } + + /** + * @param address The address (host:port) this server should listen on. + * @param decodercount The number of {@link WebSocketWorker}s that will be used to process the + * incoming network data. By default this will be Runtime.getRuntime().availableProcessors() + * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here + */ + public WebSocketServer(InetSocketAddress address, int decodercount) { + this(address, decodercount, null); + } + + /** + * @param address The address (host:port) this server should listen on. + * @param drafts The versions of the WebSocket protocol that this server instance should comply + * to. Clients that use an other protocol version will be rejected. + * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here + */ + public WebSocketServer(InetSocketAddress address, List drafts) { + this(address, AVAILABLE_PROCESSORS, drafts); + } + + /** + * @param address The address (host:port) this server should listen on. + * @param decodercount The number of {@link WebSocketWorker}s that will be used to process the + * incoming network data. By default this will be Runtime.getRuntime().availableProcessors() + * @param drafts The versions of the WebSocket protocol that this server instance should + * comply to. Clients that use an other protocol version will be rejected. + * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here + */ + public WebSocketServer(InetSocketAddress address, int decodercount, List drafts) { + this(address, decodercount, drafts, new HashSet()); + } + + /** + * Creates a WebSocketServer that will attempt to bind/listen on the given address, and + * comply with Draft version draft. + * + * @param address The address (host:port) this server should listen on. + * @param decodercount The number of {@link WebSocketWorker}s that will be used to process + * the incoming network data. By default this will be + * Runtime.getRuntime().availableProcessors() + * @param drafts The versions of the WebSocket protocol that this server instance + * should comply to. Clients that use an other protocol version will + * be rejected. + * @param connectionscontainer Allows to specify a collection that will be used to store the + * websockets in.
    If you plan to often iterate through the + * currently connected websockets you may want to use a collection + * that does not require synchronization like a {@link + * CopyOnWriteArraySet}. In that case make sure that you overload + * {@link #removeConnection(WebSocket)} and {@link + * #addConnection(WebSocket)}.
    By default a {@link HashSet} will + * be used. + * @see #removeConnection(WebSocket) for more control over syncronized operation + * @see more about + * drafts + */ + public WebSocketServer(InetSocketAddress address, int decodercount, List drafts, + Collection connectionscontainer) { + if (address == null || decodercount < 1 || connectionscontainer == null) { + throw new IllegalArgumentException( + "address and connectionscontainer must not be null and you need at least 1 decoder"); + } + + if (drafts == null) { + this.drafts = Collections.emptyList(); + } else { + this.drafts = drafts; + } + + this.address = address; + this.connections = connectionscontainer; + setTcpNoDelay(false); + setReuseAddr(false); + iqueue = new LinkedList(); + + decoders = new ArrayList(decodercount); + buffers = new LinkedBlockingQueue(); + for (int i = 0; i < decodercount; i++) { + WebSocketWorker ex = new WebSocketWorker(); + decoders.add(ex); + } + } + + + /** + * Starts the server selectorthread that binds to the currently set port number and listeners for + * WebSocket connection requests. Creates a fixed thread pool with the size {@link + * WebSocketServer#AVAILABLE_PROCESSORS}
    May only be called once. + *

    + * Alternatively you can call {@link WebSocketServer#run()} directly. + * + * @throws IllegalStateException Starting an instance again + */ + public void start() { + if (selectorthread != null) { + throw new IllegalStateException(getClass().getName() + " can only be started once."); + } + new Thread(this).start(); + } + + /** + * Closes all connected clients sockets, then closes the underlying ServerSocketChannel, + * effectively killing the server socket selectorthread, freeing the port the server was bound to + * and stops all internal workerthreads. + *

    + * If this method is called before the server is started it will never start. + * + * @param timeout Specifies how many milliseconds the overall close handshaking may take + * altogether before the connections are closed without proper close + * handshaking.
    + * @throws InterruptedException Interrupt + */ + public void stop(int timeout) throws InterruptedException { + if (!isclosed.compareAndSet(false, + true)) { // this also makes sure that no further connections will be added to this.connections + return; + } + + List socketsToClose; + + // copy the connections in a list (prevent callback deadlocks) + synchronized (connections) { + socketsToClose = new ArrayList(connections); + } + + for (WebSocket ws : socketsToClose) { + ws.close(CloseFrame.GOING_AWAY); + } + + wsf.close(); + + synchronized (this) { + if (selectorthread != null && selector != null) { + selector.wakeup(); + selectorthread.join(timeout); + } + } + } + + public void stop() throws IOException, InterruptedException { + stop(0); + } + + /** + * Returns all currently connected clients. This collection does not allow any modification e.g. + * removing a client. + * + * @return A unmodifiable collection of all currently connected clients + * @since 1.3.8 + */ + public Collection getConnections() { + synchronized (connections) { + return Collections.unmodifiableCollection(new ArrayList(connections)); + } + } + + public InetSocketAddress getAddress() { + return this.address; + } + + /** + * Gets the port number that this server listens on. + * + * @return The port number. + */ + public int getPort() { + int port = getAddress().getPort(); + if (port == 0 && server != null) { + port = server.socket().getLocalPort(); + } + return port; + } + + /** + * Get the list of active drafts + * + * @return the available drafts for this server + */ + public List getDraft() { + return Collections.unmodifiableList(drafts); + } + + /** + * Set the requested maximum number of pending connections on the socket. The exact semantics are + * implementation specific. The value provided should be greater than 0. If it is less than or + * equal to 0, then an implementation specific default will be used. This option will be passed as + * "backlog" parameter to {@link ServerSocket#bind(SocketAddress, int)} + * + * @since 1.5.0 + */ + public void setMaxPendingConnections(int numberOfConnections) { + maxPendingConnections = numberOfConnections; + } + + /** + * Returns the currently configured maximum number of pending connections. + * + * @see #setMaxPendingConnections(int) + * @since 1.5.0 + */ + public int getMaxPendingConnections() { + return maxPendingConnections; + } + + // Runnable IMPLEMENTATION ///////////////////////////////////////////////// + public void run() { + if (!doEnsureSingleThread()) { + return; + } + if (!doSetupSelectorAndServerThread()) { + return; + } + try { + int iShutdownCount = 5; + int selectTimeout = 0; + while (!selectorthread.isInterrupted() && iShutdownCount != 0) { + SelectionKey key = null; + try { + if (isclosed.get()) { + selectTimeout = 5; + } + int keyCount = selector.select(selectTimeout); + if (keyCount == 0 && isclosed.get()) { + iShutdownCount--; + } + Set keys = selector.selectedKeys(); + Iterator i = keys.iterator(); + + while (i.hasNext()) { + key = i.next(); + + if (!key.isValid()) { + continue; + } + + if (key.isAcceptable()) { + doAccept(key, i); + continue; + } + + if (key.isReadable() && !doRead(key, i)) { + continue; + } + + if (key.isWritable()) { + doWrite(key); + } + } + doAdditionalRead(); + } catch (CancelledKeyException e) { + // an other thread may cancel the key + } catch (ClosedByInterruptException e) { + return; // do the same stuff as when InterruptedException is thrown + } catch (WrappedIOException ex) { + handleIOException(key, ex.getConnection(), ex.getIOException()); + } catch (IOException ex) { + handleIOException(key, null, ex); + } catch (InterruptedException e) { + // FIXME controlled shutdown (e.g. take care of buffermanagement) + Thread.currentThread().interrupt(); + } + } + } catch (RuntimeException e) { + // should hopefully never occur + handleFatal(null, e); + } finally { + doServerShutdown(); + } + } + + /** + * Do an additional read + * + * @throws InterruptedException thrown by taking a buffer + * @throws IOException if an error happened during read + */ + private void doAdditionalRead() throws InterruptedException, IOException { + WebSocketImpl conn; + while (!iqueue.isEmpty()) { + conn = iqueue.remove(0); + WrappedByteChannel c = ((WrappedByteChannel) conn.getChannel()); + ByteBuffer buf = takeBuffer(); + try { + if (SocketChannelIOHelper.readMore(buf, conn, c)) { + iqueue.add(conn); + } + if (buf.hasRemaining()) { + conn.inQueue.put(buf); + queue(conn); + } else { + pushBuffer(buf); + } + } catch (IOException e) { + pushBuffer(buf); + throw e; + } + } + } + + /** + * Execute a accept operation + * + * @param key the selectionkey to read off + * @param i the iterator for the selection keys + * @throws InterruptedException thrown by taking a buffer + * @throws IOException if an error happened during accept + */ + private void doAccept(SelectionKey key, Iterator i) + throws IOException, InterruptedException { + if (!onConnect(key)) { + key.cancel(); + return; + } + + SocketChannel channel = server.accept(); + if (channel == null) { + return; + } + channel.configureBlocking(false); + Socket socket = channel.socket(); + socket.setTcpNoDelay(isTcpNoDelay()); + socket.setKeepAlive(true); + WebSocketImpl w = wsf.createWebSocket(this, drafts); + w.setSelectionKey(channel.register(selector, SelectionKey.OP_READ, w)); + try { + w.setChannel(wsf.wrapChannel(channel, w.getSelectionKey())); + i.remove(); + allocateBuffers(w); + } catch (IOException ex) { + if (w.getSelectionKey() != null) { + w.getSelectionKey().cancel(); + } + + handleIOException(w.getSelectionKey(), null, ex); + } + } + + /** + * Execute a read operation + * + * @param key the selectionkey to read off + * @param i the iterator for the selection keys + * @return true, if the read was successful, or false if there was an error + * @throws InterruptedException thrown by taking a buffer + * @throws IOException if an error happened during read + */ + private boolean doRead(SelectionKey key, Iterator i) + throws InterruptedException, WrappedIOException { + WebSocketImpl conn = (WebSocketImpl) key.attachment(); + ByteBuffer buf = takeBuffer(); + if (conn.getChannel() == null) { + key.cancel(); + + handleIOException(key, conn, new IOException()); + return false; + } + try { + if (SocketChannelIOHelper.read(buf, conn, conn.getChannel())) { + if (buf.hasRemaining()) { + conn.inQueue.put(buf); + queue(conn); + i.remove(); + if (conn.getChannel() instanceof WrappedByteChannel && ((WrappedByteChannel) conn + .getChannel()).isNeedRead()) { + iqueue.add(conn); + } + } else { + pushBuffer(buf); + } + } else { + pushBuffer(buf); + } + } catch (IOException e) { + pushBuffer(buf); + throw new WrappedIOException(conn, e); + } + return true; + } + + /** + * Execute a write operation + * + * @param key the selectionkey to write on + * @throws IOException if an error happened during batch + */ + private void doWrite(SelectionKey key) throws WrappedIOException { + WebSocketImpl conn = (WebSocketImpl) key.attachment(); + try { + if (SocketChannelIOHelper.batch(conn, conn.getChannel())) { + if (key.isValid()) { + key.interestOps(SelectionKey.OP_READ); + } + } + } catch (IOException e) { + throw new WrappedIOException(conn, e); + } + } + + /** + * Setup the selector thread as well as basic server settings + * + * @return true, if everything was successful, false if some error happened + */ + private boolean doSetupSelectorAndServerThread() { + selectorthread.setName("WebSocketSelector-" + selectorthread.getId()); + try { + server = ServerSocketChannel.open(); + server.configureBlocking(false); + ServerSocket socket = server.socket(); + socket.setReceiveBufferSize(WebSocketImpl.RCVBUF); + socket.setReuseAddress(isReuseAddr()); + socket.bind(address, getMaxPendingConnections()); + selector = Selector.open(); + server.register(selector, server.validOps()); + startConnectionLostTimer(); + for (WebSocketWorker ex : decoders) { + ex.start(); + } + onStart(); + } catch (IOException ex) { + handleFatal(null, ex); + return false; + } + return true; + } + + /** + * The websocket server can only be started once + * + * @return true, if the server can be started, false if already a thread is running + */ + private boolean doEnsureSingleThread() { + synchronized (this) { + if (selectorthread != null) { + throw new IllegalStateException(getClass().getName() + " can only be started once."); + } + selectorthread = Thread.currentThread(); + if (isclosed.get()) { + return false; + } + } + return true; + } + + /** + * Clean up everything after a shutdown + */ + private void doServerShutdown() { + stopConnectionLostTimer(); + if (decoders != null) { + for (WebSocketWorker w : decoders) { + w.interrupt(); + } + } + if (selector != null) { + try { + selector.close(); + } catch (IOException e) { + log.error("IOException during selector.close", e); + onError(null, e); + } + } + if (server != null) { + try { + server.close(); + } catch (IOException e) { + log.error("IOException during server.close", e); + onError(null, e); + } + } + } + + protected void allocateBuffers(WebSocket c) throws InterruptedException { + if (queuesize.get() >= 2 * decoders.size() + 1) { + return; + } + queuesize.incrementAndGet(); + buffers.put(createBuffer()); + } + + protected void releaseBuffers(WebSocket c) throws InterruptedException { + // queuesize.decrementAndGet(); + // takeBuffer(); + } + + public ByteBuffer createBuffer() { + return ByteBuffer.allocate(WebSocketImpl.RCVBUF); + } + + protected void queue(WebSocketImpl ws) throws InterruptedException { + if (ws.getWorkerThread() == null) { + ws.setWorkerThread(decoders.get(queueinvokes % decoders.size())); + queueinvokes++; + } + ws.getWorkerThread().put(ws); + } + + private ByteBuffer takeBuffer() throws InterruptedException { + return buffers.take(); + } + + private void pushBuffer(ByteBuffer buf) throws InterruptedException { + if (buffers.size() > queuesize.intValue()) { + return; + } + buffers.put(buf); + } + + private void handleIOException(SelectionKey key, WebSocket conn, IOException ex) { + // onWebsocketError( conn, ex );// conn may be null here + if (key != null) { + key.cancel(); + } + if (conn != null) { + conn.closeConnection(CloseFrame.ABNORMAL_CLOSE, ex.getMessage()); + } else if (key != null) { + SelectableChannel channel = key.channel(); + if (channel != null && channel + .isOpen()) { // this could be the case if the IOException ex is a SSLException + try { + channel.close(); + } catch (IOException e) { + // there is nothing that must be done here + } + log.trace("Connection closed because of exception", ex); + } + } + } + + private void handleFatal(WebSocket conn, Exception e) { + log.error("Shutdown due to fatal error", e); + onError(conn, e); + //Shutting down WebSocketWorkers, see #222 + if (decoders != null) { + for (WebSocketWorker w : decoders) { + w.interrupt(); + } + } + if (selectorthread != null) { + selectorthread.interrupt(); + } + try { + stop(); + } catch (IOException e1) { + log.error("Error during shutdown", e1); + onError(null, e1); + } catch (InterruptedException e1) { + Thread.currentThread().interrupt(); + log.error("Interrupt during stop", e); + onError(null, e1); + } + } + + @Override + public final void onWebsocketMessage(WebSocket conn, String message) { + onMessage(conn, message); + } + + + @Override + public final void onWebsocketMessage(WebSocket conn, ByteBuffer blob) { + onMessage(conn, blob); + } + + @Override + public final void onWebsocketOpen(WebSocket conn, Handshakedata handshake) { + if (addConnection(conn)) { + onOpen(conn, (ClientHandshake) handshake); + } + } + + @Override + public final void onWebsocketClose(WebSocket conn, int code, String reason, boolean remote) { + selector.wakeup(); + try { + if (removeConnection(conn)) { + onClose(conn, code, reason, remote); + } + } finally { + try { + releaseBuffers(conn); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + } + + /** + * This method performs remove operations on the connection and therefore also gives control over + * whether the operation shall be synchronized + *

    + * {@link #WebSocketServer(InetSocketAddress, int, List, Collection)} allows to specify a + * collection which will be used to store current connections in.
    Depending on the type on the + * connection, modifications of that collection may have to be synchronized. + * + * @param ws The Websocket connection which should be removed + * @return Removing connection successful + */ + protected boolean removeConnection(WebSocket ws) { + boolean removed = false; + synchronized (connections) { + if (this.connections.contains(ws)) { + removed = this.connections.remove(ws); + } else { + //Don't throw an assert error if the ws is not in the list. e.g. when the other endpoint did not send any handshake. see #512 + log.trace( + "Removing connection which is not in the connections collection! Possible no handshake received! {}", + ws); + } + } + if (isclosed.get() && connections.isEmpty()) { + selectorthread.interrupt(); + } + return removed; + } + + /** + * @param ws the Websocket connection which should be added + * @return Adding connection successful + * @see #removeConnection(WebSocket) + */ + protected boolean addConnection(WebSocket ws) { + if (!isclosed.get()) { + synchronized (connections) { + return this.connections.add(ws); + } + } else { + // This case will happen when a new connection gets ready while the server is already stopping. + ws.close(CloseFrame.GOING_AWAY); + return true;// for consistency sake we will make sure that both onOpen will be called + } + } + + @Override + public final void onWebsocketError(WebSocket conn, Exception ex) { + onError(conn, ex); + } + + @Override + public final void onWriteDemand(WebSocket w) { + WebSocketImpl conn = (WebSocketImpl) w; + try { + conn.getSelectionKey().interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); + } catch (CancelledKeyException e) { + // the thread which cancels key is responsible for possible cleanup + conn.outQueue.clear(); + } + selector.wakeup(); + } + + @Override + public void onWebsocketCloseInitiated(WebSocket conn, int code, String reason) { + onCloseInitiated(conn, code, reason); + } + + @Override + public void onWebsocketClosing(WebSocket conn, int code, String reason, boolean remote) { + onClosing(conn, code, reason, remote); + + } + + public void onCloseInitiated(WebSocket conn, int code, String reason) { + } + + public void onClosing(WebSocket conn, int code, String reason, boolean remote) { + + } + + public final void setWebSocketFactory(WebSocketServerFactory wsf) { + if (this.wsf != null) { + this.wsf.close(); + } + this.wsf = wsf; + } + + public final WebSocketFactory getWebSocketFactory() { + return wsf; + } + + /** + * Returns whether a new connection shall be accepted or not.
    Therefore method is well suited + * to implement some kind of connection limitation.
    + * + * @param key the SelectionKey for the new connection + * @return Can this new connection be accepted + * @see #onOpen(WebSocket, ClientHandshake) + * @see #onWebsocketHandshakeReceivedAsServer(WebSocket, Draft, ClientHandshake) + **/ + protected boolean onConnect(SelectionKey key) { + return true; + } + + /** + * Getter to return the socket used by this specific connection + * + * @param conn The specific connection + * @return The socket used by this connection + */ + private Socket getSocket(WebSocket conn) { + WebSocketImpl impl = (WebSocketImpl) conn; + return ((SocketChannel) impl.getSelectionKey().channel()).socket(); + } + + @Override + public InetSocketAddress getLocalSocketAddress(WebSocket conn) { + return (InetSocketAddress) getSocket(conn).getLocalSocketAddress(); + } + + @Override + public InetSocketAddress getRemoteSocketAddress(WebSocket conn) { + return (InetSocketAddress) getSocket(conn).getRemoteSocketAddress(); + } + + /** + * Called after an opening handshake has been performed and the given websocket is ready to be + * written on. + * + * @param conn The WebSocket instance this event is occurring on. + * @param handshake The handshake of the websocket instance + */ + public abstract void onOpen(WebSocket conn, ClientHandshake handshake); + + /** + * Called after the websocket connection has been closed. + * + * @param conn The WebSocket instance this event is occurring on. + * @param code The codes can be looked up here: {@link CloseFrame} + * @param reason Additional information string + * @param remote Returns whether or not the closing of the connection was initiated by the remote + * host. + **/ + public abstract void onClose(WebSocket conn, int code, String reason, boolean remote); + + /** + * Callback for string messages received from the remote host + * + * @param conn The WebSocket instance this event is occurring on. + * @param message The UTF-8 decoded message that was received. + * @see #onMessage(WebSocket, ByteBuffer) + **/ + public abstract void onMessage(WebSocket conn, String message); + + /** + * Called when errors occurs. If an error causes the websocket connection to fail {@link + * #onClose(WebSocket, int, String, boolean)} will be called additionally.
    This method will be + * called primarily because of IO or protocol errors.
    If the given exception is an + * RuntimeException that probably means that you encountered a bug.
    + * + * @param conn Can be null if there error does not belong to one specific websocket. For example + * if the servers port could not be bound. + * @param ex The exception causing this error + **/ + public abstract void onError(WebSocket conn, Exception ex); + + /** + * Called when the server started up successfully. + *

    + * If any error occurred, onError is called instead. + */ + public abstract void onStart(); + + /** + * Callback for binary messages received from the remote host + * + * @param conn The WebSocket instance this event is occurring on. + * @param message The binary message that was received. + * @see #onMessage(WebSocket, ByteBuffer) + **/ + public void onMessage(WebSocket conn, ByteBuffer message) { + } + + /** + * Send a text to all connected endpoints + * + * @param text the text to send to the endpoints + */ + public void broadcast(String text) { + broadcast(text, connections); + } + + /** + * Send a byte array to all connected endpoints + * + * @param data the data to send to the endpoints + */ + public void broadcast(byte[] data) { + broadcast(data, connections); + } + + /** + * Send a ByteBuffer to all connected endpoints + * + * @param data the data to send to the endpoints + */ + public void broadcast(ByteBuffer data) { + broadcast(data, connections); + } + + /** + * Send a byte array to a specific collection of websocket connections + * + * @param data the data to send to the endpoints + * @param clients a collection of endpoints to whom the text has to be send + */ + public void broadcast(byte[] data, Collection clients) { + if (data == null || clients == null) { + throw new IllegalArgumentException(); + } + broadcast(ByteBuffer.wrap(data), clients); + } + + /** + * Send a ByteBuffer to a specific collection of websocket connections + * + * @param data the data to send to the endpoints + * @param clients a collection of endpoints to whom the text has to be send + */ + public void broadcast(ByteBuffer data, Collection clients) { + if (data == null || clients == null) { + throw new IllegalArgumentException(); + } + doBroadcast(data, clients); + } + + /** + * Send a text to a specific collection of websocket connections + * + * @param text the text to send to the endpoints + * @param clients a collection of endpoints to whom the text has to be send + */ + public void broadcast(String text, Collection clients) { + if (text == null || clients == null) { + throw new IllegalArgumentException(); + } + doBroadcast(text, clients); + } + + /** + * Private method to cache all the frames to improve memory footprint and conversion time + * + * @param data the data to broadcast + * @param clients the clients to send the message to + */ + private void doBroadcast(Object data, Collection clients) { + String sData = null; + if (data instanceof String) { + sData = (String) data; + } + ByteBuffer bData = null; + if (data instanceof ByteBuffer) { + bData = (ByteBuffer) data; + } + if (sData == null && bData == null) { + return; + } + Map> draftFrames = new HashMap>(); + List clientCopy; + synchronized (clients) { + clientCopy = new ArrayList(clients); + } + for (WebSocket client : clientCopy) { + if (client != null) { + Draft draft = client.getDraft(); + fillFrames(draft, draftFrames, sData, bData); + try { + client.sendFrame(draftFrames.get(draft)); + } catch (WebsocketNotConnectedException e) { + //Ignore this exception in this case + } + } + } + } + + /** + * Fills the draftFrames with new data for the broadcast + * + * @param draft The draft to use + * @param draftFrames The list of frames per draft to fill + * @param sData the string data, can be null + * @param bData the byte buffer data, can be null + */ + private void fillFrames(Draft draft, Map> draftFrames, String sData, + ByteBuffer bData) { + if (!draftFrames.containsKey(draft)) { + List frames = null; + if (sData != null) { + frames = draft.createFrames(sData, false); + } + if (bData != null) { + frames = draft.createFrames(bData, false); + } + if (frames != null) { + draftFrames.put(draft, frames); + } + } + } + + /** + * This class is used to process incoming data + */ + public class WebSocketWorker extends Thread { + + private BlockingQueue iqueue; + + public WebSocketWorker() { + iqueue = new LinkedBlockingQueue(); + setName("WebSocketWorker-" + getId()); + setUncaughtExceptionHandler(new UncaughtExceptionHandler() { + @Override + public void uncaughtException(Thread t, Throwable e) { + log.error("Uncaught exception in thread {}: {}", t.getName(), e); + } + }); + } + + public void put(WebSocketImpl ws) throws InterruptedException { + iqueue.put(ws); + } + + @Override + public void run() { + WebSocketImpl ws = null; + try { + while (true) { + ByteBuffer buf; + ws = iqueue.take(); + buf = ws.inQueue.poll(); + assert (buf != null); + doDecode(ws, buf); + ws = null; + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (RuntimeException e) { + handleFatal(ws, e); + } + } + + /** + * call ws.decode on the byteBuffer + * + * @param ws the Websocket + * @param buf the buffer to decode to + * @throws InterruptedException thrown by pushBuffer + */ + private void doDecode(WebSocketImpl ws, ByteBuffer buf) throws InterruptedException { + try { + ws.decode(buf); + } catch (Exception e) { + log.error("Error while reading from remote connection", e); + } finally { + pushBuffer(buf); + } + } + } } diff --git a/src/main/java/org/java_websocket/util/Base64.java b/src/main/java/org/java_websocket/util/Base64.java index e5c9f9d58..175016327 100644 --- a/src/main/java/org/java_websocket/util/Base64.java +++ b/src/main/java/org/java_websocket/util/Base64.java @@ -28,29 +28,30 @@ /** *

    Encodes and decodes to and from Base64 notation.

    *

    Homepage: http://iharder.net/base64.

    - * + * *

    Example:

    - * + * * String encoded = Base64.encode( myByteArray ); *
    * byte[] myByteArray = Base64.decode( encoded ); * - *

    The options parameter, which appears in a few places, is used to pass - * several pieces of information to the encoder. In the "higher level" methods such as - * encodeBytes( bytes, options ) the options parameter can be used to indicate such - * things as first gzipping the bytes before encoding them, not inserting linefeeds, - * and encoding using the URL-safe and Ordered dialects.

    + *

    The options parameter, which appears in a few places, is used to pass + * several pieces of information to the encoder. In the "higher level" methods such as encodeBytes( + * bytes, options ) the options parameter can be used to indicate such things as first gzipping the + * bytes before encoding them, not inserting linefeeds, and encoding using the URL-safe and Ordered + * dialects.

    * *

    Note, according to RFC3548, - * Section 2.1, implementations should not add line feeds unless explicitly told - * to do so. I've got Base64 set to this behavior now, although earlier versions - * broke lines by default.

    + * Section 2.1, implementations should not add line feeds unless explicitly told to do so. I've got + * Base64 set to this behavior now, although earlier versions broke lines by default.

    * - *

    The constants defined in Base64 can be OR-ed together to combine options, so you + *

    The constants defined in Base64 can be OR-ed together to combine options, so you * might make a call like this:

    * - * String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES ); - *

    to compress the data before encoding it and then making the output have newline characters.

    + * String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES + * ); + *

    to compress the data before encoding it and then making the output have newline + * characters.

    *

    Also...

    * String encoded = Base64.encodeBytes( crazyString.getBytes() ); * @@ -89,7 +90,7 @@ *
  • v2.3 - This is not a drop-in replacement! This is two years of comments * and bug fixes queued up and finally executed. Thanks to everyone who sent * me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else. - * Much bad coding was cleaned up including throwing exceptions where necessary + * Much bad coding was cleaned up including throwing exceptions where necessary * instead of returning null values or something similar. Here are some changes * that may affect you: *
      @@ -127,24 +128,24 @@ * Special thanks to Jim Kellerman at http://www.powerset.com/ * for contributing the new Base64 dialects. * - * + * *
    • v2.1 - Cleaned up javadoc comments and unused variables and methods. Added * some convenience methods for reading and writing to and from files.
    • *
    • v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems * with other encodings (like EBCDIC).
    • *
    • v2.0.1 - Fixed an error when decoding a single byte, that is, when the * encoded data was a single byte.
    • - *
    • v2.0 - I got rid of methods that used booleans to set options. + *
    • v2.0 - I got rid of methods that used booleans to set options. * Now everything is more consolidated and cleaner. The code now detects * when data that's being decoded is gzip-compressed and will decompress it * automatically. Generally things are cleaner. You'll probably have to * change some method calls that you were making to support the new * options format (ints that you "OR" together).
    • - *
    • v1.5.1 - Fixed bug when decompressing and decoding to a - * byte[] using decode( String s, boolean gzipCompressed ). - * Added the ability to "suspend" encoding in the Output Stream so - * you can turn on and off the encoding if you need to embed base64 - * data in an otherwise "normal" stream (like an XML file).
    • + *
    • v1.5.1 - Fixed bug when decompressing and decoding to a + * byte[] using decode( String s, boolean gzipCompressed ). + * Added the ability to "suspend" encoding in the Output Stream so + * you can turn on and off the encoding if you need to embed base64 + * data in an otherwise "normal" stream (like an XML file).
    • *
    • v1.5 - Output stream pases on flush() command but doesn't do anything itself. * This helps when using GZIP streams. * Added the ability to GZip-compress objects before encoding them.
    • @@ -168,870 +169,880 @@ * @author rob@iharder.net * @version 2.3.7 */ -public class Base64 -{ - -/* ******** P U B L I C F I E L D S ******** */ - - - /** No options specified. Value is zero. */ - public final static int NO_OPTIONS = 0; - - /** Specify encoding in first bit. Value is one. */ - public final static int ENCODE = 1; - - /** Specify that data should be gzip-compressed in second bit. Value is two. */ - public final static int GZIP = 2; - - /** Do break lines when encoding. Value is 8. */ - public final static int DO_BREAK_LINES = 8; - - /** - * Encode using Base64-like encoding that is URL- and Filename-safe as described - * in Section 4 of RFC3548: - * http://www.faqs.org/rfcs/rfc3548.html. - * It is important to note that data encoded this way is not officially valid Base64, - * or at the very least should not be called Base64 without also specifying that is - * was encoded using the URL- and Filename-safe dialect. - */ - public final static int URL_SAFE = 16; - - - /** - * Encode using the special "ordered" dialect of Base64 described here: - * http://www.faqs.org/qa/rfcc-1940.html. - */ - public final static int ORDERED = 32; - - -/* ******** P R I V A T E F I E L D S ******** */ - - - /** Maximum line length (76) of Base64 output. */ - private final static int MAX_LINE_LENGTH = 76; - - - /** The equals sign (=) as a byte. */ - private final static byte EQUALS_SIGN = (byte)'='; - - - /** The new line character (\n) as a byte. */ - private final static byte NEW_LINE = (byte)'\n'; - - - /** Preferred encoding. */ - private final static String PREFERRED_ENCODING = "US-ASCII"; - - - private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding - - -/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ - - /** The 64 valid Base64 values. */ - /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ - private final static byte[] _STANDARD_ALPHABET = { - (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', - (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', - (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', - (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', - (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', - (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', - (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', - (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', - (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', - (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' - }; - - - /** - * Translates a Base64 value to either its 6-bit reconstruction value - * or a negative number indicating some other meaning. - **/ - private final static byte[] _STANDARD_DECODABET = { - -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 - -5,-5, // Whitespace: Tab and Linefeed - -9,-9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 - -9,-9,-9,-9,-9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 - 62, // Plus sign at decimal 43 - -9,-9,-9, // Decimal 44 - 46 - 63, // Slash at decimal 47 - 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine - -9,-9,-9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9,-9,-9, // Decimal 62 - 64 - 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' - 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' - -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 - 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' - 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' - -9,-9,-9,-9,-9 // Decimal 123 - 127 - ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 - }; - - -/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ - - /** - * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: - * http://www.faqs.org/rfcs/rfc3548.html. - * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." - */ - private final static byte[] _URL_SAFE_ALPHABET = { - (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', - (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', - (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', - (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', - (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', - (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', - (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', - (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', - (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', - (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_' - }; - - /** - * Used in decoding URL- and Filename-safe dialects of Base64. - */ - private final static byte[] _URL_SAFE_DECODABET = { - -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 - -5,-5, // Whitespace: Tab and Linefeed - -9,-9, // Decimal 11 - 12 +public class Base64 { + + /* ******** P U B L I C F I E L D S ******** */ + + + /** + * No options specified. Value is zero. + */ + public final static int NO_OPTIONS = 0; + + /** + * Specify encoding in first bit. Value is one. + */ + public final static int ENCODE = 1; + + /** + * Specify that data should be gzip-compressed in second bit. Value is two. + */ + public final static int GZIP = 2; + + /** + * Do break lines when encoding. Value is 8. + */ + public final static int DO_BREAK_LINES = 8; + + /** + * Encode using Base64-like encoding that is URL- and Filename-safe as described in Section 4 of + * RFC3548: + * http://www.faqs.org/rfcs/rfc3548.html. + * It is important to note that data encoded this way is not officially valid Base64, or + * at the very least should not be called Base64 without also specifying that is was encoded using + * the URL- and Filename-safe dialect. + */ + public final static int URL_SAFE = 16; + + + /** + * Encode using the special "ordered" dialect of Base64 described here: + * http://www.faqs.org/qa/rfcc-1940.html. + */ + public final static int ORDERED = 32; + + + /* ******** P R I V A T E F I E L D S ******** */ + + + /** + * Maximum line length (76) of Base64 output. + */ + private final static int MAX_LINE_LENGTH = 76; + + + /** + * The equals sign (=) as a byte. + */ + private final static byte EQUALS_SIGN = (byte) '='; + + + /** + * The new line character (\n) as a byte. + */ + private final static byte NEW_LINE = (byte) '\n'; + + + /** + * Preferred encoding. + */ + private final static String PREFERRED_ENCODING = "US-ASCII"; + + + private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding + + + /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ + + /** + * The 64 valid Base64 values. + */ + /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ + private final static byte[] _STANDARD_ALPHABET = { + (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', + (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', + (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', + (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', + (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', + (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', + (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', + (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', + (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', + (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' + }; + + + /** + * Translates a Base64 value to either its 6-bit reconstruction value or a negative number + * indicating some other meaning. + **/ + private final static byte[] _STANDARD_DECODABET = { + -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 + -5, -5, // Whitespace: Tab and Linefeed + -9, -9, // Decimal 11 - 12 + -5, // Whitespace: Carriage Return + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 + -9, -9, -9, -9, -9, // Decimal 27 - 31 + -5, // Whitespace: Space + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 + 62, // Plus sign at decimal 43 + -9, -9, -9, // Decimal 44 - 46 + 63, // Slash at decimal 47 + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine + -9, -9, -9, // Decimal 58 - 60 + -1, // Equals sign at decimal 61 + -9, -9, -9, // Decimal 62 - 64 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' + -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' + -9, -9, -9, -9, -9 // Decimal 123 - 127 + , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 + }; + + + /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ + + /** + * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: + * http://www.faqs.org/rfcs/rfc3548.html. + * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." + */ + private final static byte[] _URL_SAFE_ALPHABET = { + (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', + (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', + (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', + (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', + (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', + (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', + (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', + (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', + (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', + (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_' + }; + + /** + * Used in decoding URL- and Filename-safe dialects of Base64. + */ + private final static byte[] _URL_SAFE_DECODABET = { + -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 + -5, -5, // Whitespace: Tab and Linefeed + -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 - -9,-9,-9,-9,-9, // Decimal 27 - 31 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 + -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 62, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 - 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine - -9,-9,-9, // Decimal 58 - 60 + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine + -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 - -9,-9,-9, // Decimal 62 - 64 - 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' - 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' - -9,-9,-9,-9, // Decimal 91 - 94 + -9, -9, -9, // Decimal 62 - 64 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' + -9, -9, -9, -9, // Decimal 91 - 94 63, // Underscore at decimal 95 -9, // Decimal 96 - 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' - 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' - -9,-9,-9,-9,-9 // Decimal 123 - 127 - ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 - }; + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' + -9, -9, -9, -9, -9 // Decimal 123 - 127 + , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 + }; -/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ + /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ - /** - * I don't get the point of this technique, but someone requested it, - * and it is described here: - * http://www.faqs.org/qa/rfcc-1940.html. - */ - private final static byte[] _ORDERED_ALPHABET = { - (byte)'-', - (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', - (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', - (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', - (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', - (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', - (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', - (byte)'_', - (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', - (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', - (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', - (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z' - }; - - /** - * Used in decoding the "ordered" dialect of Base64. - */ - private final static byte[] _ORDERED_DECODABET = { - -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 - -5,-5, // Whitespace: Tab and Linefeed - -9,-9, // Decimal 11 - 12 + /** + * I don't get the point of this technique, but someone requested it, and it is described here: + * http://www.faqs.org/qa/rfcc-1940.html. + */ + private final static byte[] _ORDERED_ALPHABET = { + (byte) '-', + (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', + (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', + (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', + (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', + (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', + (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', + (byte) '_', + (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', + (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', + (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', + (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z' + }; + + /** + * Used in decoding the "ordered" dialect of Base64. + */ + private final static byte[] _ORDERED_DECODABET = { + -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 + -5, -5, // Whitespace: Tab and Linefeed + -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 - -9,-9,-9,-9,-9, // Decimal 27 - 31 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 + -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 0, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 - 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine - -9,-9,-9, // Decimal 58 - 60 + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Numbers zero through nine + -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 - -9,-9,-9, // Decimal 62 - 64 - 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M' - 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z' - -9,-9,-9,-9, // Decimal 91 - 94 + -9, -9, -9, // Decimal 62 - 64 + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, // Letters 'A' through 'M' + 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, // Letters 'N' through 'Z' + -9, -9, -9, -9, // Decimal 91 - 94 37, // Underscore at decimal 95 -9, // Decimal 96 - 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm' - 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z' - -9,-9,-9,-9,-9 // Decimal 123 - 127 - ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 - }; - - -/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ + 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, // Letters 'a' through 'm' + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // Letters 'n' through 'z' + -9, -9, -9, -9, -9 // Decimal 123 - 127 + , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 + }; - /** - * Returns one of the _SOMETHING_ALPHABET byte arrays depending on - * the options specified. - * It's possible, though silly, to specify ORDERED and URLSAFE - * in which case one of them will be picked, though there is - * no guarantee as to which one will be picked. - */ - private final static byte[] getAlphabet( int options ) { - if ((options & URL_SAFE) == URL_SAFE) { - return _URL_SAFE_ALPHABET; - } else if ((options & ORDERED) == ORDERED) { - return _ORDERED_ALPHABET; - } else { - return _STANDARD_ALPHABET; - } - } // end getAlphabet + /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ - /** - * Returns one of the _SOMETHING_DECODABET byte arrays depending on - * the options specified. - * It's possible, though silly, to specify ORDERED and URL_SAFE - * in which case one of them will be picked, though there is - * no guarantee as to which one will be picked. - */ - private final static byte[] getDecodabet( int options ) { - if( (options & URL_SAFE) == URL_SAFE) { - return _URL_SAFE_DECODABET; - } else if ((options & ORDERED) == ORDERED) { - return _ORDERED_DECODABET; - } else { - return _STANDARD_DECODABET; + /** + * Returns one of the _SOMETHING_ALPHABET byte arrays depending on the options specified. It's + * possible, though silly, to specify ORDERED and URLSAFE in which case one of them will be + * picked, though there is no guarantee as to which one will be picked. + */ + private final static byte[] getAlphabet(int options) { + if ((options & URL_SAFE) == URL_SAFE) { + return _URL_SAFE_ALPHABET; + } else if ((options & ORDERED) == ORDERED) { + return _ORDERED_ALPHABET; + } else { + return _STANDARD_ALPHABET; + } + } // end getAlphabet + + + /** + * Returns one of the _SOMETHING_DECODABET byte arrays depending on the options specified. It's + * possible, though silly, to specify ORDERED and URL_SAFE in which case one of them will be + * picked, though there is no guarantee as to which one will be picked. + */ + private final static byte[] getDecodabet(int options) { + if ((options & URL_SAFE) == URL_SAFE) { + return _URL_SAFE_DECODABET; + } else if ((options & ORDERED) == ORDERED) { + return _ORDERED_DECODABET; + } else { + return _STANDARD_DECODABET; + } + } // end getAlphabet + + + /** + * Defeats instantiation. + */ + private Base64() { + } + + + + + /* ******** E N C O D I N G M E T H O D S ******** */ + + + /** + * Encodes up to the first three bytes of array threeBytes and returns a four-byte + * array in Base64 notation. The actual number of significant bytes in your array is given by + * numSigBytes. The array threeBytes needs only be as big as + * numSigBytes. + * Code can reuse a byte array by passing a four-byte array as b4. + * + * @param b4 A reusable byte array to reduce array instantiation + * @param threeBytes the array to convert + * @param numSigBytes the number of significant bytes in your array + * @return four byte array in Base64 notation. + * @since 1.5.1 + */ + private static byte[] encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes, int options) { + encode3to4(threeBytes, 0, numSigBytes, b4, 0, options); + return b4; + } // end encode3to4 + + + /** + *

      Encodes up to three bytes of the array source + * and writes the resulting four Base64 bytes to destination. The source and + * destination arrays can be manipulated anywhere along their length by specifying + * srcOffset and destOffset. + * This method does not check to make sure your arrays are large enough to accommodate + * srcOffset + 3 for the source array or destOffset + 4 for the + * destination array. The actual number of significant bytes in your array is given by + * numSigBytes.

      + *

      This is the lowest level of the encoding methods with + * all possible parameters.

      + * + * @param source the array to convert + * @param srcOffset the index where conversion begins + * @param numSigBytes the number of significant bytes in your array + * @param destination the array to hold the conversion + * @param destOffset the index where output will be put + * @return the destination array + * @since 1.3 + */ + private static byte[] encode3to4( + byte[] source, int srcOffset, int numSigBytes, + byte[] destination, int destOffset, int options) { + + byte[] ALPHABET = getAlphabet(options); + + // 1 2 3 + // 01234567890123456789012345678901 Bit position + // --------000000001111111122222222 Array position from threeBytes + // --------| || || || | Six bit groups to index ALPHABET + // >>18 >>12 >> 6 >> 0 Right shift necessary + // 0x3f 0x3f 0x3f Additional AND + + // Create buffer with zero-padding if there are only one or two + // significant bytes passed in the array. + // We have to shift left 24 in order to flush out the 1's that appear + // when Java treats a value as negative that is cast from a byte to an int. + int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) + | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) + | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); + + switch (numSigBytes) { + case 3: + destination[destOffset] = ALPHABET[(inBuff >>> 18)]; + destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; + destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; + destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f]; + return destination; + + case 2: + destination[destOffset] = ALPHABET[(inBuff >>> 18)]; + destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; + destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; + destination[destOffset + 3] = EQUALS_SIGN; + return destination; + + case 1: + destination[destOffset] = ALPHABET[(inBuff >>> 18)]; + destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; + destination[destOffset + 2] = EQUALS_SIGN; + destination[destOffset + 3] = EQUALS_SIGN; + return destination; + + default: + return destination; + } // end switch + } // end encode3to4 + + + /** + * Encodes a byte array into Base64 notation. Does not GZip-compress data. + * + * @param source The data to convert + * @return The data in Base64-encoded form + * @throws IllegalArgumentException if source array is null + * @since 1.4 + */ + public static String encodeBytes(byte[] source) { + // Since we're not going to have the GZIP encoding turned on, + // we're not going to have an java.io.IOException thrown, so + // we should not force the user to have to catch it. + String encoded = null; + try { + encoded = encodeBytes(source, 0, source.length, NO_OPTIONS); + } catch (java.io.IOException ex) { + assert false : ex.getMessage(); + } // end catch + assert encoded != null; + return encoded; + } // end encodeBytes + + + /** + * Encodes a byte array into Base64 notation. + *

      + * Example options:

      +   *   GZIP: gzip-compresses object before encoding it.
      +   *   DO_BREAK_LINES: break lines at 76 characters
      +   *     Note: Technically, this makes your encoding non-compliant.
      +   * 
      + *

      + * Example: encodeBytes( myData, Base64.GZIP ) or + *

      + * Example: encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES ) + * + * + *

      As of v 2.3, if there is an error with the GZIP stream, + * the method will throw an java.io.IOException. This is new to v2.3! In earlier versions, + * it just returned a null value, but in retrospect that's a pretty poor way to handle it.

      + * + * @param source The data to convert + * @param off Offset in array where conversion should begin + * @param len Length of data to convert + * @param options Specified options + * @return The Base64-encoded data as a String + * @throws java.io.IOException if there is an error + * @throws IllegalArgumentException if source array is null, if source array, offset, or length + * are invalid + * @see Base64#GZIP + * @see Base64#DO_BREAK_LINES + * @since 2.0 + */ + public static String encodeBytes(byte[] source, int off, int len, int options) + throws java.io.IOException { + byte[] encoded = encodeBytesToBytes(source, off, len, options); + + // Return value according to relevant encoding. + try { + return new String(encoded, PREFERRED_ENCODING); + } // end try + catch (java.io.UnsupportedEncodingException uue) { + return new String(encoded); + } // end catch + + } // end encodeBytes + + /** + * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns a byte array instead of + * instantiating a String. This is more efficient if you're working with I/O streams and have + * large data sets to encode. + * + * @param source The data to convert + * @param off Offset in array where conversion should begin + * @param len Length of data to convert + * @param options Specified options + * @return The Base64-encoded data as a String + * @throws java.io.IOException if there is an error + * @throws IllegalArgumentException if source array is null, if source array, offset, or length + * are invalid + * @see Base64#GZIP + * @see Base64#DO_BREAK_LINES + * @since 2.3.1 + */ + public static byte[] encodeBytesToBytes(byte[] source, int off, int len, int options) + throws java.io.IOException { + + if (source == null) { + throw new IllegalArgumentException("Cannot serialize a null array."); + } // end if: null + + if (off < 0) { + throw new IllegalArgumentException("Cannot have negative offset: " + off); + } // end if: off < 0 + + if (len < 0) { + throw new IllegalArgumentException("Cannot have length offset: " + len); + } // end if: len < 0 + + if (off + len > source.length) { + throw new IllegalArgumentException( + String + .format("Cannot have offset of %d and length of %d with array of length %d", off, len, + source.length)); + } // end if: off < 0 + + // Compress? + if ((options & GZIP) != 0) { + java.io.ByteArrayOutputStream baos = null; + java.util.zip.GZIPOutputStream gzos = null; + Base64.OutputStream b64os = null; + + try { + // GZip -> Base64 -> ByteArray + baos = new java.io.ByteArrayOutputStream(); + b64os = new Base64.OutputStream(baos, ENCODE | options); + gzos = new java.util.zip.GZIPOutputStream(b64os); + + gzos.write(source, off, len); + gzos.close(); + } // end try + catch (java.io.IOException e) { + // Catch it and then throw it immediately so that + // the finally{} block is called for cleanup. + throw e; + } // end catch + finally { + try { + if (gzos != null) { + gzos.close(); + } + } catch (Exception e) { } - } // end getAlphabet + try { + if (b64os != null) { + b64os.close(); + } + } catch (Exception e) { + } + try { + if (baos != null) { + baos.close(); + } + } catch (Exception e) { + } + } // end finally + return baos.toByteArray(); + } // end if: compress - - /** Defeats instantiation. */ - private Base64(){} - + // Else, don't compress. Better not to use streams at all then. + else { + boolean breakLines = (options & DO_BREAK_LINES) != 0; - - -/* ******** E N C O D I N G M E T H O D S ******** */ - - - /** - * Encodes up to the first three bytes of array threeBytes - * and returns a four-byte array in Base64 notation. - * The actual number of significant bytes in your array is - * given by numSigBytes. - * The array threeBytes needs only be as big as - * numSigBytes. - * Code can reuse a byte array by passing a four-byte array as b4. - * - * @param b4 A reusable byte array to reduce array instantiation - * @param threeBytes the array to convert - * @param numSigBytes the number of significant bytes in your array - * @return four byte array in Base64 notation. - * @since 1.5.1 - */ - private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) { - encode3to4( threeBytes, 0, numSigBytes, b4, 0, options ); - return b4; - } // end encode3to4 + //int len43 = len * 4 / 3; + //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 + // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding + // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines + // Try to determine more precisely how big the array needs to be. + // If we get it right, we don't have to do an array copy, and + // we save a bunch of memory. + int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0); // Bytes needed for actual encoding + if (breakLines) { + encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters + } + byte[] outBuff = new byte[encLen]; - - /** - *

      Encodes up to three bytes of the array source - * and writes the resulting four Base64 bytes to destination. - * The source and destination arrays can be manipulated - * anywhere along their length by specifying - * srcOffset and destOffset. - * This method does not check to make sure your arrays - * are large enough to accommodate srcOffset + 3 for - * the source array or destOffset + 4 for - * the destination array. - * The actual number of significant bytes in your array is - * given by numSigBytes.

      - *

      This is the lowest level of the encoding methods with - * all possible parameters.

      - * - * @param source the array to convert - * @param srcOffset the index where conversion begins - * @param numSigBytes the number of significant bytes in your array - * @param destination the array to hold the conversion - * @param destOffset the index where output will be put - * @return the destination array - * @since 1.3 - */ - private static byte[] encode3to4( - byte[] source, int srcOffset, int numSigBytes, - byte[] destination, int destOffset, int options ) { - - byte[] ALPHABET = getAlphabet( options ); - - // 1 2 3 - // 01234567890123456789012345678901 Bit position - // --------000000001111111122222222 Array position from threeBytes - // --------| || || || | Six bit groups to index ALPHABET - // >>18 >>12 >> 6 >> 0 Right shift necessary - // 0x3f 0x3f 0x3f Additional AND - - // Create buffer with zero-padding if there are only one or two - // significant bytes passed in the array. - // We have to shift left 24 in order to flush out the 1's that appear - // when Java treats a value as negative that is cast from a byte to an int. - int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) - | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) - | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); - - switch( numSigBytes ) - { - case 3: - destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; - destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; - destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; - destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; - return destination; - - case 2: - destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; - destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; - destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; - destination[ destOffset + 3 ] = EQUALS_SIGN; - return destination; - - case 1: - destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; - destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; - destination[ destOffset + 2 ] = EQUALS_SIGN; - destination[ destOffset + 3 ] = EQUALS_SIGN; - return destination; - - default: - return destination; - } // end switch - } // end encode3to4 + int d = 0; + int e = 0; + int len2 = len - 2; + int lineLength = 0; + for (; d < len2; d += 3, e += 4) { + encode3to4(source, d + off, 3, outBuff, e, options); + + lineLength += 4; + if (breakLines && lineLength >= MAX_LINE_LENGTH) { + outBuff[e + 4] = NEW_LINE; + e++; + lineLength = 0; + } // end if: end of line + } // en dfor: each piece of array + + if (d < len) { + encode3to4(source, d + off, len - d, outBuff, e, options); + e += 4; + } // end if: some padding needed + + // Only resize array if we didn't guess it right. + if (e <= outBuff.length - 1) { + // If breaking lines and the last byte falls right at + // the line length (76 bytes per line), there will be + // one extra byte, and the array will need to be resized. + // Not too bad of an estimate on array size, I'd say. + byte[] finalOut = new byte[e]; + System.arraycopy(outBuff, 0, finalOut, 0, e); + //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); + return finalOut; + } else { + //System.err.println("No need to resize array."); + return outBuff; + } + + } // end else: don't compress + + } // end encodeBytesToBytes + + + + + + /* ******** D E C O D I N G M E T H O D S ******** */ + + + /** + * Decodes four bytes from array source and writes the resulting bytes (up to three of + * them) to destination. The source and destination arrays can be manipulated anywhere + * along their length by specifying + * srcOffset and destOffset. + * This method does not check to make sure your arrays are large enough to accommodate + * srcOffset + 4 for the source array or destOffset + 3 for the + * destination array. This method returns the actual number of bytes that were + * converted from the Base64 encoding. + *

      This is the lowest level of the decoding methods with + * all possible parameters.

      + * + * @param source the array to convert + * @param srcOffset the index where conversion begins + * @param destination the array to hold the conversion + * @param destOffset the index where output will be put + * @param options alphabet type is pulled from this (standard, url-safe, ordered) + * @return the number of decoded bytes converted + * @throws IllegalArgumentException if source or destination arrays are null, if srcOffset or + * destOffset are invalid or there is not enough room in the + * array. + * @since 1.3 + */ + private static int decode4to3( + byte[] source, int srcOffset, + byte[] destination, int destOffset, int options) { + + // Lots of error checking and exception throwing + if (source == null) { + throw new IllegalArgumentException("Source array was null."); + } // end if + if (destination == null) { + throw new IllegalArgumentException("Destination array was null."); + } // end if + if (srcOffset < 0 || srcOffset + 3 >= source.length) { + throw new IllegalArgumentException(String.format( + "Source array with length %d cannot have offset of %d and still process four bytes.", + source.length, srcOffset)); + } // end if + if (destOffset < 0 || destOffset + 2 >= destination.length) { + throw new IllegalArgumentException(String.format( + "Destination array with length %d cannot have offset of %d and still store three bytes.", + destination.length, destOffset)); + } // end if + + byte[] DECODABET = getDecodabet(options); + + // Example: Dk== + if (source[srcOffset + 2] == EQUALS_SIGN) { + // Two ways to do the same thing. Don't know which way I like best. + //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) + // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); + int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) + | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12); + + destination[destOffset] = (byte) (outBuff >>> 16); + return 1; + } + + // Example: DkL= + else if (source[srcOffset + 3] == EQUALS_SIGN) { + // Two ways to do the same thing. Don't know which way I like best. + //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) + // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) + // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); + int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) + | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) + | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6); + + destination[destOffset] = (byte) (outBuff >>> 16); + destination[destOffset + 1] = (byte) (outBuff >>> 8); + return 2; + } + // Example: DkLE + else { + // Two ways to do the same thing. Don't know which way I like best. + //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) + // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) + // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) + // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); + int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) + | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) + | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6) + | ((DECODABET[source[srcOffset + 3]] & 0xFF)); + + destination[destOffset] = (byte) (outBuff >> 16); + destination[destOffset + 1] = (byte) (outBuff >> 8); + destination[destOffset + 2] = (byte) (outBuff); + + return 3; + } + } // end decodeToBytes + + + /** + * A {@link Base64.OutputStream} will write data to another + * java.io.OutputStream, given in the constructor, + * and encode/decode to/from Base64 notation on the fly. + * + * @see Base64 + * @since 1.3 + */ + public static class OutputStream extends java.io.FilterOutputStream { + + private boolean encode; + private int position; + private byte[] buffer; + private int bufferLength; + private int lineLength; + private boolean breakLines; + private byte[] b4; // Scratch used in a few places + private boolean suspendEncoding; + private int options; // Record for later + private byte[] decodabet; // Local copies to avoid extra method calls /** - * Encodes a byte array into Base64 notation. - * Does not GZip-compress data. - * - * @param source The data to convert - * @return The data in Base64-encoded form - * @throws IllegalArgumentException if source array is null - * @since 1.4 + * Constructs a {@link Base64.OutputStream} in ENCODE mode. + * + * @param out the java.io.OutputStream to which data will be written. + * @since 1.3 */ - public static String encodeBytes( byte[] source ) { - // Since we're not going to have the GZIP encoding turned on, - // we're not going to have an java.io.IOException thrown, so - // we should not force the user to have to catch it. - String encoded = null; - try { - encoded = encodeBytes(source, 0, source.length, NO_OPTIONS); - } catch (java.io.IOException ex) { - assert false : ex.getMessage(); - } // end catch - assert encoded != null; - return encoded; - } // end encodeBytes + public OutputStream(java.io.OutputStream out) { + this(out, ENCODE); + } // end constructor /** - * Encodes a byte array into Base64 notation. + * Constructs a {@link Base64.OutputStream} in either ENCODE or DECODE mode. *

      - * Example options:

      -     *   GZIP: gzip-compresses object before encoding it.
      -     *   DO_BREAK_LINES: break lines at 76 characters
      -     *     Note: Technically, this makes your encoding non-compliant.
      +     * Valid options:
      +     *   ENCODE or DECODE: Encode or Decode as data is read.
      +     *   DO_BREAK_LINES: don't break lines at 76 characters
      +     *     (only meaningful when encoding)
            * 
      *

      - * Example: encodeBytes( myData, Base64.GZIP ) or - *

      - * Example: encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES ) - * - * - *

      As of v 2.3, if there is an error with the GZIP stream, - * the method will throw an java.io.IOException. This is new to v2.3! - * In earlier versions, it just returned a null value, but - * in retrospect that's a pretty poor way to handle it.

      - * + * Example: new Base64.OutputStream( out, Base64.ENCODE ) * - * @param source The data to convert - * @param off Offset in array where conversion should begin - * @param len Length of data to convert - * @param options Specified options - * @return The Base64-encoded data as a String - * @see Base64#GZIP + * @param out the java.io.OutputStream to which data will be written. + * @param options Specified options. + * @see Base64#ENCODE * @see Base64#DO_BREAK_LINES - * @throws java.io.IOException if there is an error - * @throws IllegalArgumentException if source array is null, if source array, offset, or length are invalid - * @since 2.0 + * @since 1.3 */ - public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { - byte[] encoded = encodeBytesToBytes( source, off, len, options ); + public OutputStream(java.io.OutputStream out, int options) { + super(out); + this.breakLines = (options & DO_BREAK_LINES) != 0; + this.encode = (options & ENCODE) != 0; + this.bufferLength = encode ? 3 : 4; + this.buffer = new byte[bufferLength]; + this.position = 0; + this.lineLength = 0; + this.suspendEncoding = false; + this.b4 = new byte[4]; + this.options = options; + this.decodabet = getDecodabet(options); + } // end constructor - // Return value according to relevant encoding. - try { - return new String( encoded, PREFERRED_ENCODING ); - } // end try - catch (java.io.UnsupportedEncodingException uue) { - return new String( encoded ); - } // end catch - - } // end encodeBytes /** - * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns - * a byte array instead of instantiating a String. This is more efficient - * if you're working with I/O streams and have large data sets to encode. - * + * Writes the byte to the output stream after converting to/from Base64 notation. When encoding, + * bytes are buffered three at a time before the output stream actually gets a write() call. + * When decoding, bytes are buffered four at a time. * - * @param source The data to convert - * @param off Offset in array where conversion should begin - * @param len Length of data to convert - * @param options Specified options - * @return The Base64-encoded data as a String - * @see Base64#GZIP - * @see Base64#DO_BREAK_LINES - * @throws java.io.IOException if there is an error - * @throws IllegalArgumentException if source array is null, if source array, offset, or length are invalid - * @since 2.3.1 + * @param theByte the byte to write + * @since 1.3 */ - public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { - - if( source == null ){ - throw new IllegalArgumentException( "Cannot serialize a null array." ); - } // end if: null - - if( off < 0 ){ - throw new IllegalArgumentException( "Cannot have negative offset: " + off ); - } // end if: off < 0 - - if( len < 0 ){ - throw new IllegalArgumentException( "Cannot have length offset: " + len ); - } // end if: len < 0 - - if( off + len > source.length ){ - throw new IllegalArgumentException( - String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); - } // end if: off < 0 - - - - // Compress? - if( (options & GZIP) != 0 ) { - java.io.ByteArrayOutputStream baos = null; - java.util.zip.GZIPOutputStream gzos = null; - Base64.OutputStream b64os = null; - - try { - // GZip -> Base64 -> ByteArray - baos = new java.io.ByteArrayOutputStream(); - b64os = new Base64.OutputStream( baos, ENCODE | options ); - gzos = new java.util.zip.GZIPOutputStream( b64os ); - - gzos.write( source, off, len ); - gzos.close(); - } // end try - catch( java.io.IOException e ) { - // Catch it and then throw it immediately so that - // the finally{} block is called for cleanup. - throw e; - } // end catch - finally { - try{ if (gzos != null) gzos.close(); } catch( Exception e ){} - try{ if (b64os != null) b64os.close(); } catch( Exception e ){} - try{ if (baos != null) baos.close(); } catch( Exception e ){} - } // end finally - - return baos.toByteArray(); - } // end if: compress - - // Else, don't compress. Better not to use streams at all then. - else { - boolean breakLines = (options & DO_BREAK_LINES) != 0; - - //int len43 = len * 4 / 3; - //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 - // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding - // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines - // Try to determine more precisely how big the array needs to be. - // If we get it right, we don't have to do an array copy, and - // we save a bunch of memory. - int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding - if( breakLines ){ - encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters - } - byte[] outBuff = new byte[ encLen ]; - - - int d = 0; - int e = 0; - int len2 = len - 2; - int lineLength = 0; - for( ; d < len2; d+=3, e+=4 ) { - encode3to4( source, d+off, 3, outBuff, e, options ); - - lineLength += 4; - if( breakLines && lineLength >= MAX_LINE_LENGTH ) - { - outBuff[e+4] = NEW_LINE; - e++; - lineLength = 0; - } // end if: end of line - } // en dfor: each piece of array - - if( d < len ) { - encode3to4( source, d+off, len - d, outBuff, e, options ); - e += 4; - } // end if: some padding needed - - - // Only resize array if we didn't guess it right. - if( e <= outBuff.length - 1 ){ - // If breaking lines and the last byte falls right at - // the line length (76 bytes per line), there will be - // one extra byte, and the array will need to be resized. - // Not too bad of an estimate on array size, I'd say. - byte[] finalOut = new byte[e]; - System.arraycopy(outBuff,0, finalOut,0,e); - //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); - return finalOut; - } else { - //System.err.println("No need to resize array."); - return outBuff; - } - - } // end else: don't compress - - } // end encodeBytesToBytes - - - - - -/* ******** D E C O D I N G M E T H O D S ******** */ - - + @Override + public void write(int theByte) + throws java.io.IOException { + // Encoding suspended? + if (suspendEncoding) { + this.out.write(theByte); + return; + } // end if: suspended + + // Encode? + if (encode) { + buffer[position++] = (byte) theByte; + if (position >= bufferLength) { // Enough to encode. + + this.out.write(encode3to4(b4, buffer, bufferLength, options)); + + lineLength += 4; + if (breakLines && lineLength >= MAX_LINE_LENGTH) { + this.out.write(NEW_LINE); + lineLength = 0; + } // end if: end of line + + position = 0; + } // end if: enough to output + } // end if: encoding + + // Else, Decoding + else { + // Meaningful Base64 character? + if (decodabet[theByte & 0x7f] > WHITE_SPACE_ENC) { + buffer[position++] = (byte) theByte; + if (position >= bufferLength) { // Enough to output. + + int len = Base64.decode4to3(buffer, 0, b4, 0, options); + out.write(b4, 0, len); + position = 0; + } // end if: enough to output + } // end if: meaningful base64 character + else if (decodabet[theByte & 0x7f] != WHITE_SPACE_ENC) { + throw new java.io.IOException("Invalid character in Base64 data."); + } // end else: not white space either + } // end else: decoding + } // end write + /** - * Decodes four bytes from array source - * and writes the resulting bytes (up to three of them) - * to destination. - * The source and destination arrays can be manipulated - * anywhere along their length by specifying - * srcOffset and destOffset. - * This method does not check to make sure your arrays - * are large enough to accommodate srcOffset + 4 for - * the source array or destOffset + 3 for - * the destination array. - * This method returns the actual number of bytes that - * were converted from the Base64 encoding. - *

      This is the lowest level of the decoding methods with - * all possible parameters.

      - * + * Calls {@link #write(int)} repeatedly until len bytes are written. * - * @param source the array to convert - * @param srcOffset the index where conversion begins - * @param destination the array to hold the conversion - * @param destOffset the index where output will be put - * @param options alphabet type is pulled from this (standard, url-safe, ordered) - * @return the number of decoded bytes converted - * @throws IllegalArgumentException if source or destination arrays are null, if srcOffset or destOffset are invalid - * or there is not enough room in the array. + * @param theBytes array from which to read bytes + * @param off offset for array + * @param len max number of bytes to read into array * @since 1.3 */ - private static int decode4to3( - byte[] source, int srcOffset, - byte[] destination, int destOffset, int options ) { - - // Lots of error checking and exception throwing - if( source == null ){ - throw new IllegalArgumentException( "Source array was null." ); - } // end if - if( destination == null ){ - throw new IllegalArgumentException( "Destination array was null." ); - } // end if - if( srcOffset < 0 || srcOffset + 3 >= source.length ){ - throw new IllegalArgumentException( String.format( - "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) ); - } // end if - if( destOffset < 0 || destOffset +2 >= destination.length ){ - throw new IllegalArgumentException( String.format( - "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) ); - } // end if - - - byte[] DECODABET = getDecodabet( options ); - - // Example: Dk== - if( source[ srcOffset + 2] == EQUALS_SIGN ) { - // Two ways to do the same thing. Don't know which way I like best. - //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) - // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); - int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) - | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); - - destination[ destOffset ] = (byte)( outBuff >>> 16 ); - return 1; - } - - // Example: DkL= - else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { - // Two ways to do the same thing. Don't know which way I like best. - //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) - // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) - // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); - int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) - | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) - | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); - - destination[ destOffset ] = (byte)( outBuff >>> 16 ); - destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); - return 2; - } - - // Example: DkLE + @Override + public void write(byte[] theBytes, int off, int len) + throws java.io.IOException { + // Encoding suspended? + if (suspendEncoding) { + this.out.write(theBytes, off, len); + return; + } // end if: suspended + + for (int i = 0; i < len; i++) { + write(theBytes[off + i]); + } // end for: each byte written + + } // end write + + /** + * Method added by PHIL. [Thanks, PHIL. -Rob] This pads the buffer without closing the stream. + * + * @throws java.io.IOException if there's an error. + */ + public void flushBase64() throws java.io.IOException { + if (position > 0) { + if (encode) { + out.write(encode3to4(b4, buffer, position, options)); + position = 0; + } // end if: encoding else { - // Two ways to do the same thing. Don't know which way I like best. - //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) - // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) - // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) - // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); - int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) - | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) - | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) - | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); - - - destination[ destOffset ] = (byte)( outBuff >> 16 ); - destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); - destination[ destOffset + 2 ] = (byte)( outBuff ); - - return 3; - } - } // end decodeToBytes + throw new java.io.IOException("Base64 input not properly padded."); + } // end else: decoding + } // end if: buffer partially full + } // end flush - /** - * A {@link Base64.OutputStream} will write data to another - * java.io.OutputStream, given in the constructor, - * and encode/decode to/from Base64 notation on the fly. + * Flushes and closes (I think, in the superclass) the stream. * - * @see Base64 * @since 1.3 */ - public static class OutputStream extends java.io.FilterOutputStream { - - private boolean encode; - private int position; - private byte[] buffer; - private int bufferLength; - private int lineLength; - private boolean breakLines; - private byte[] b4; // Scratch used in a few places - private boolean suspendEncoding; - private int options; // Record for later - private byte[] decodabet; // Local copies to avoid extra method calls - - /** - * Constructs a {@link Base64.OutputStream} in ENCODE mode. - * - * @param out the java.io.OutputStream to which data will be written. - * @since 1.3 - */ - public OutputStream( java.io.OutputStream out ) { - this( out, ENCODE ); - } // end constructor - - - /** - * Constructs a {@link Base64.OutputStream} in - * either ENCODE or DECODE mode. - *

      - * Valid options:

      -         *   ENCODE or DECODE: Encode or Decode as data is read.
      -         *   DO_BREAK_LINES: don't break lines at 76 characters
      -         *     (only meaningful when encoding)
      -         * 
      - *

      - * Example: new Base64.OutputStream( out, Base64.ENCODE ) - * - * @param out the java.io.OutputStream to which data will be written. - * @param options Specified options. - * @see Base64#ENCODE - * @see Base64#DO_BREAK_LINES - * @since 1.3 - */ - public OutputStream( java.io.OutputStream out, int options ) { - super( out ); - this.breakLines = (options & DO_BREAK_LINES) != 0; - this.encode = (options & ENCODE) != 0; - this.bufferLength = encode ? 3 : 4; - this.buffer = new byte[ bufferLength ]; - this.position = 0; - this.lineLength = 0; - this.suspendEncoding = false; - this.b4 = new byte[4]; - this.options = options; - this.decodabet = getDecodabet(options); - } // end constructor - - - /** - * Writes the byte to the output stream after - * converting to/from Base64 notation. - * When encoding, bytes are buffered three - * at a time before the output stream actually - * gets a write() call. - * When decoding, bytes are buffered four - * at a time. - * - * @param theByte the byte to write - * @since 1.3 - */ - @Override - public void write(int theByte) - throws java.io.IOException { - // Encoding suspended? - if( suspendEncoding ) { - this.out.write( theByte ); - return; - } // end if: suspended - - // Encode? - if( encode ) { - buffer[ position++ ] = (byte)theByte; - if( position >= bufferLength ) { // Enough to encode. - - this.out.write( encode3to4( b4, buffer, bufferLength, options ) ); - - lineLength += 4; - if( breakLines && lineLength >= MAX_LINE_LENGTH ) { - this.out.write( NEW_LINE ); - lineLength = 0; - } // end if: end of line - - position = 0; - } // end if: enough to output - } // end if: encoding - - // Else, Decoding - else { - // Meaningful Base64 character? - if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) { - buffer[ position++ ] = (byte)theByte; - if( position >= bufferLength ) { // Enough to output. - - int len = Base64.decode4to3( buffer, 0, b4, 0, options ); - out.write( b4, 0, len ); - position = 0; - } // end if: enough to output - } // end if: meaningful base64 character - else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) { - throw new java.io.IOException( "Invalid character in Base64 data." ); - } // end else: not white space either - } // end else: decoding - } // end write - - /** - * Calls {@link #write(int)} repeatedly until len - * bytes are written. - * - * @param theBytes array from which to read bytes - * @param off offset for array - * @param len max number of bytes to read into array - * @since 1.3 - */ - @Override - public void write( byte[] theBytes, int off, int len ) - throws java.io.IOException { - // Encoding suspended? - if( suspendEncoding ) { - this.out.write( theBytes, off, len ); - return; - } // end if: suspended - - for( int i = 0; i < len; i++ ) { - write( theBytes[ off + i ] ); - } // end for: each byte written - - } // end write - /** - * Method added by PHIL. [Thanks, PHIL. -Rob] - * This pads the buffer without closing the stream. - * @throws java.io.IOException if there's an error. - */ - public void flushBase64() throws java.io.IOException { - if( position > 0 ) { - if( encode ) { - out.write( encode3to4( b4, buffer, position, options ) ); - position = 0; - } // end if: encoding - else { - throw new java.io.IOException( "Base64 input not properly padded." ); - } // end else: decoding - } // end if: buffer partially full - - } // end flush - - /** - * Flushes and closes (I think, in the superclass) the stream. - * - * @since 1.3 - */ - @Override - public void close() throws java.io.IOException { - // 1. Ensure that pending characters are written - flushBase64(); - - // 2. Actually close the stream - // Base class both flushes and closes. - super.close(); - - buffer = null; - out = null; - } // end close - } // end inner class OutputStream + @Override + public void close() throws java.io.IOException { + // 1. Ensure that pending characters are written + flushBase64(); + + // 2. Actually close the stream + // Base class both flushes and closes. + super.close(); + + buffer = null; + out = null; + } // end close + } // end inner class OutputStream } // end class Base64 diff --git a/src/main/java/org/java_websocket/util/ByteBufferUtils.java b/src/main/java/org/java_websocket/util/ByteBufferUtils.java index ec02831fe..e43447984 100644 --- a/src/main/java/org/java_websocket/util/ByteBufferUtils.java +++ b/src/main/java/org/java_websocket/util/ByteBufferUtils.java @@ -32,42 +32,42 @@ */ public class ByteBufferUtils { - /** - * Private constructor for static class - */ - private ByteBufferUtils() { - } + /** + * Private constructor for static class + */ + private ByteBufferUtils() { + } - /** - * Transfer from one ByteBuffer to another ByteBuffer - * - * @param source the ByteBuffer to copy from - * @param dest the ByteBuffer to copy to - * @return the number of transferred bytes - */ - public static int transferByteBuffer( ByteBuffer source, ByteBuffer dest ) { - if( source == null || dest == null ) { - throw new IllegalArgumentException(); - } - int fremain = source.remaining(); - int toremain = dest.remaining(); - if( fremain > toremain ) { - int limit = Math.min( fremain, toremain ); - source.limit( limit ); - dest.put( source ); - return limit; - } else { - dest.put( source ); - return fremain; - } - } + /** + * Transfer from one ByteBuffer to another ByteBuffer + * + * @param source the ByteBuffer to copy from + * @param dest the ByteBuffer to copy to + * @return the number of transferred bytes + */ + public static int transferByteBuffer(ByteBuffer source, ByteBuffer dest) { + if (source == null || dest == null) { + throw new IllegalArgumentException(); + } + int fremain = source.remaining(); + int toremain = dest.remaining(); + if (fremain > toremain) { + int limit = Math.min(fremain, toremain); + source.limit(limit); + dest.put(source); + return limit; + } else { + dest.put(source); + return fremain; + } + } - /** - * Get a ByteBuffer with zero capacity - * - * @return empty ByteBuffer - */ - public static ByteBuffer getEmptyByteBuffer() { - return ByteBuffer.allocate( 0 ); - } + /** + * Get a ByteBuffer with zero capacity + * + * @return empty ByteBuffer + */ + public static ByteBuffer getEmptyByteBuffer() { + return ByteBuffer.allocate(0); + } } diff --git a/src/main/java/org/java_websocket/util/Charsetfunctions.java b/src/main/java/org/java_websocket/util/Charsetfunctions.java index a131f5497..43cde55cc 100644 --- a/src/main/java/org/java_websocket/util/Charsetfunctions.java +++ b/src/main/java/org/java_websocket/util/Charsetfunctions.java @@ -38,119 +38,132 @@ public class Charsetfunctions { - /** - * Private constructor for real static class - */ - private Charsetfunctions() {} - - private static final CodingErrorAction codingErrorAction = CodingErrorAction.REPORT; - - /* - * @return UTF-8 encoding in bytes - */ - public static byte[] utf8Bytes( String s ) { - try { - return s.getBytes( "UTF8" ); - } catch ( UnsupportedEncodingException e ) { - throw new InvalidEncodingException( e ); - } - } - - /* - * @return ASCII encoding in bytes - */ - public static byte[] asciiBytes( String s ) { - try { - return s.getBytes( "ASCII" ); - } catch ( UnsupportedEncodingException e ) { - throw new InvalidEncodingException( e ); - } - } - - public static String stringAscii( byte[] bytes ) { - return stringAscii( bytes, 0, bytes.length ); - } - - public static String stringAscii( byte[] bytes, int offset, int length ) { - try { - return new String( bytes, offset, length, "ASCII" ); - } catch ( UnsupportedEncodingException e ) { - throw new InvalidEncodingException( e ); - } - } - - public static String stringUtf8( byte[] bytes ) throws InvalidDataException { - return stringUtf8( ByteBuffer.wrap( bytes ) ); - } - - public static String stringUtf8( ByteBuffer bytes ) throws InvalidDataException { - CharsetDecoder decode = Charset.forName( "UTF8" ).newDecoder(); - decode.onMalformedInput( codingErrorAction ); - decode.onUnmappableCharacter( codingErrorAction ); - String s; - try { - bytes.mark(); - s = decode.decode( bytes ).toString(); - bytes.reset(); - } catch ( CharacterCodingException e ) { - throw new InvalidDataException( CloseFrame.NO_UTF8, e ); - } - return s; - } - - /** - * Implementation of the "Flexible and Economical UTF-8 Decoder" algorithm - * by Björn Höhrmann (http://bjoern.hoehrmann.de/utf-8/decoder/dfa/) - */ - private static final int[] utf8d = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1f - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3f - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5f - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7f - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9f - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // a0..bf - 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // c0..df - 0xa, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // e0..ef - 0xb, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // f0..ff - 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 - 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 - 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 - 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8 - }; - - /** - * Check if the provided BytebBuffer contains a valid utf8 encoded string. - *

      - * Using the algorithm "Flexible and Economical UTF-8 Decoder" by Björn Höhrmann (http://bjoern.hoehrmann.de/utf-8/decoder/dfa/) - * - * @param data the ByteBuffer - * @param off offset (for performance reasons) - * @return does the ByteBuffer contain a valid utf8 encoded string - */ - public static boolean isValidUTF8( ByteBuffer data, int off ) { - int len = data.remaining(); - if( len < off ) { - return false; - } - int state = 0; - for( int i = off; i < len; ++i ) { - state = utf8d[256 + ( state << 4 ) + utf8d[( 0xff & data.get( i ) )]]; - if( state == 1 ) { - return false; - } - } - return true; - } - - /** - * Calling isValidUTF8 with offset 0 - * - * @param data the ByteBuffer - * @return does the ByteBuffer contain a valid utf8 encoded string - */ - public static boolean isValidUTF8( ByteBuffer data ) { - return isValidUTF8( data, 0 ); - } + /** + * Private constructor for real static class + */ + private Charsetfunctions() { + } + + private static final CodingErrorAction codingErrorAction = CodingErrorAction.REPORT; + + /* + * @return UTF-8 encoding in bytes + */ + public static byte[] utf8Bytes(String s) { + try { + return s.getBytes("UTF8"); + } catch (UnsupportedEncodingException e) { + throw new InvalidEncodingException(e); + } + } + + /* + * @return ASCII encoding in bytes + */ + public static byte[] asciiBytes(String s) { + try { + return s.getBytes("ASCII"); + } catch (UnsupportedEncodingException e) { + throw new InvalidEncodingException(e); + } + } + + public static String stringAscii(byte[] bytes) { + return stringAscii(bytes, 0, bytes.length); + } + + public static String stringAscii(byte[] bytes, int offset, int length) { + try { + return new String(bytes, offset, length, "ASCII"); + } catch (UnsupportedEncodingException e) { + throw new InvalidEncodingException(e); + } + } + + public static String stringUtf8(byte[] bytes) throws InvalidDataException { + return stringUtf8(ByteBuffer.wrap(bytes)); + } + + public static String stringUtf8(ByteBuffer bytes) throws InvalidDataException { + CharsetDecoder decode = Charset.forName("UTF8").newDecoder(); + decode.onMalformedInput(codingErrorAction); + decode.onUnmappableCharacter(codingErrorAction); + String s; + try { + bytes.mark(); + s = decode.decode(bytes).toString(); + bytes.reset(); + } catch (CharacterCodingException e) { + throw new InvalidDataException(CloseFrame.NO_UTF8, e); + } + return s; + } + + /** + * Implementation of the "Flexible and Economical UTF-8 Decoder" algorithm by Björn Höhrmann + * (http://bjoern.hoehrmann.de/utf-8/decoder/dfa/) + */ + private static final int[] utf8d = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, // 00..1f + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, // 20..3f + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, // 40..5f + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, // 60..7f + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, // 80..9f + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, // a0..bf + 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, // c0..df + 0xa, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // e0..ef + 0xb, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // f0..ff + 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, + 1, // s1..s2 + 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, + 1, // s3..s4 + 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, + 1, // s5..s6 + 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 + // s7..s8 + }; + + /** + * Check if the provided BytebBuffer contains a valid utf8 encoded string. + *

      + * Using the algorithm "Flexible and Economical UTF-8 Decoder" by Björn Höhrmann + * (http://bjoern.hoehrmann.de/utf-8/decoder/dfa/) + * + * @param data the ByteBuffer + * @param off offset (for performance reasons) + * @return does the ByteBuffer contain a valid utf8 encoded string + */ + public static boolean isValidUTF8(ByteBuffer data, int off) { + int len = data.remaining(); + if (len < off) { + return false; + } + int state = 0; + for (int i = off; i < len; ++i) { + state = utf8d[256 + (state << 4) + utf8d[(0xff & data.get(i))]]; + if (state == 1) { + return false; + } + } + return true; + } + + /** + * Calling isValidUTF8 with offset 0 + * + * @param data the ByteBuffer + * @return does the ByteBuffer contain a valid utf8 encoded string + */ + public static boolean isValidUTF8(ByteBuffer data) { + return isValidUTF8(data, 0); + } } diff --git a/src/main/java/org/java_websocket/util/NamedThreadFactory.java b/src/main/java/org/java_websocket/util/NamedThreadFactory.java index 8e1b5dde9..2a424fe1a 100644 --- a/src/main/java/org/java_websocket/util/NamedThreadFactory.java +++ b/src/main/java/org/java_websocket/util/NamedThreadFactory.java @@ -30,18 +30,19 @@ import java.util.concurrent.atomic.AtomicInteger; public class NamedThreadFactory implements ThreadFactory { - private final ThreadFactory defaultThreadFactory = Executors.defaultThreadFactory(); - private final AtomicInteger threadNumber = new AtomicInteger(1); - private final String threadPrefix; - public NamedThreadFactory(String threadPrefix) { - this.threadPrefix = threadPrefix; - } + private final ThreadFactory defaultThreadFactory = Executors.defaultThreadFactory(); + private final AtomicInteger threadNumber = new AtomicInteger(1); + private final String threadPrefix; - @Override - public Thread newThread(Runnable runnable) { - Thread thread = defaultThreadFactory.newThread(runnable); - thread.setName(threadPrefix + "-" + threadNumber); - return thread; - } + public NamedThreadFactory(String threadPrefix) { + this.threadPrefix = threadPrefix; + } + + @Override + public Thread newThread(Runnable runnable) { + Thread thread = defaultThreadFactory.newThread(runnable); + thread.setName(threadPrefix + "-" + threadNumber); + return thread; + } } diff --git a/src/test/java/org/java_websocket/AllTests.java b/src/test/java/org/java_websocket/AllTests.java index 9fae8d634..7285be993 100644 --- a/src/test/java/org/java_websocket/AllTests.java +++ b/src/test/java/org/java_websocket/AllTests.java @@ -31,18 +31,19 @@ @RunWith(Suite.class) @Suite.SuiteClasses({ - org.java_websocket.util.ByteBufferUtilsTest.class, - org.java_websocket.util.Base64Test.class, - org.java_websocket.client.AllClientTests.class, - org.java_websocket.drafts.AllDraftTests.class, - org.java_websocket.issues.AllIssueTests.class, - org.java_websocket.exceptions.AllExceptionsTests.class, - org.java_websocket.misc.AllMiscTests.class, - org.java_websocket.protocols.AllProtocolTests.class, - org.java_websocket.framing.AllFramingTests.class + org.java_websocket.util.ByteBufferUtilsTest.class, + org.java_websocket.util.Base64Test.class, + org.java_websocket.client.AllClientTests.class, + org.java_websocket.drafts.AllDraftTests.class, + org.java_websocket.issues.AllIssueTests.class, + org.java_websocket.exceptions.AllExceptionsTests.class, + org.java_websocket.misc.AllMiscTests.class, + org.java_websocket.protocols.AllProtocolTests.class, + org.java_websocket.framing.AllFramingTests.class }) /** * Start all tests */ public class AllTests { + } diff --git a/src/test/java/org/java_websocket/autobahn/AutobahnServerResultsTest.java b/src/test/java/org/java_websocket/autobahn/AutobahnServerResultsTest.java index db7bafde1..ecebd18cf 100644 --- a/src/test/java/org/java_websocket/autobahn/AutobahnServerResultsTest.java +++ b/src/test/java/org/java_websocket/autobahn/AutobahnServerResultsTest.java @@ -38,2432 +38,2736 @@ public class AutobahnServerResultsTest { - static JSONObject jsonObject = null; - - @BeforeClass - public static void getJSONObject() throws FileNotFoundException { - File file = new File( "reports/servers/index.json" ); - //File file = new File( "C:\\Python27\\Scripts\\reports\\servers\\index.json" ); - if( file.exists() ) { - String content = new Scanner( file ).useDelimiter( "\\Z" ).next(); - jsonObject = new JSONObject( content ); - jsonObject = jsonObject.getJSONObject( "TooTallNate Java-WebSocket" ); - } - Assume.assumeTrue( jsonObject != null ); - } - - @Test - public void test1_1_1() { - JSONObject testResult = jsonObject.getJSONObject( "1.1.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test1_1_2() { - JSONObject testResult = jsonObject.getJSONObject( "1.1.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test1_1_3() { - JSONObject testResult = jsonObject.getJSONObject( "1.1.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test1_1_4() { - JSONObject testResult = jsonObject.getJSONObject( "1.1.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test1_1_5() { - JSONObject testResult = jsonObject.getJSONObject( "1.1.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test1_1_6() { - JSONObject testResult = jsonObject.getJSONObject( "1.1.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 30 ); - } - - @Test - public void test1_1_7() { - JSONObject testResult = jsonObject.getJSONObject( "1.1.7" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 20 ); - } - - @Test - public void test1_1_8() { - JSONObject testResult = jsonObject.getJSONObject( "1.1.8" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 30 ); - } - - @Test - public void test1_2_1() { - JSONObject testResult = jsonObject.getJSONObject( "1.2.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test1_2_2() { - JSONObject testResult = jsonObject.getJSONObject( "1.2.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test1_2_3() { - JSONObject testResult = jsonObject.getJSONObject( "1.2.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test1_2_4() { - JSONObject testResult = jsonObject.getJSONObject( "1.2.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 20 ); - } - - @Test - public void test1_2_5() { - JSONObject testResult = jsonObject.getJSONObject( "1.2.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test1_2_6() { - JSONObject testResult = jsonObject.getJSONObject( "1.2.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 70 ); - } - @Test - public void test1_2_7() { - JSONObject testResult = jsonObject.getJSONObject( "1.2.7" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 70 ); - } - - @Test - public void test1_2_8() { - JSONObject testResult = jsonObject.getJSONObject( "1.2.8" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 60 ); - } - - @Test - public void test2_1() { - JSONObject testResult = jsonObject.getJSONObject( "2.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test2_2() { - JSONObject testResult = jsonObject.getJSONObject( "2.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test2_3() { - JSONObject testResult = jsonObject.getJSONObject( "2.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test2_4() { - JSONObject testResult = jsonObject.getJSONObject( "2.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test2_5() { - JSONObject testResult = jsonObject.getJSONObject( "2.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test2_6() { - JSONObject testResult = jsonObject.getJSONObject( "2.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 30 ); - } - - @Test - public void test2_7() { - JSONObject testResult = jsonObject.getJSONObject( "2.7" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test2_8() { - JSONObject testResult = jsonObject.getJSONObject( "2.8" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test2_9() { - JSONObject testResult = jsonObject.getJSONObject( "2.9" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test2_10() { - JSONObject testResult = jsonObject.getJSONObject( "2.10" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 60 ); - } - - @Test - public void test2_11() { - JSONObject testResult = jsonObject.getJSONObject( "2.11" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 50 ); - } - - @Test - public void test3_1() { - JSONObject testResult = jsonObject.getJSONObject( "3.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test3_2() { - JSONObject testResult = jsonObject.getJSONObject( "3.2" ); - assertEquals( "NON-STRICT", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test3_3() { - JSONObject testResult = jsonObject.getJSONObject( "3.3" ); - assertEquals( "NON-STRICT", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test3_4() { - JSONObject testResult = jsonObject.getJSONObject( "3.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 20 ); - } - - @Test - public void test3_5() { - JSONObject testResult = jsonObject.getJSONObject( "3.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test3_6() { - JSONObject testResult = jsonObject.getJSONObject( "3.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test3_7() { - JSONObject testResult = jsonObject.getJSONObject( "3.7" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test4_1_1() { - JSONObject testResult = jsonObject.getJSONObject( "4.1.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test4_1_2() { - JSONObject testResult = jsonObject.getJSONObject( "4.1.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test4_1_3() { - JSONObject testResult = jsonObject.getJSONObject( "4.1.3" ); - assertEquals( "NON-STRICT", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test4_1_4() { - JSONObject testResult = jsonObject.getJSONObject( "4.1.4" ); - assertEquals( "NON-STRICT", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test4_1_5() { - JSONObject testResult = jsonObject.getJSONObject( "4.1.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test4_2_1() { - JSONObject testResult = jsonObject.getJSONObject( "4.2.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test4_2_2() { - JSONObject testResult = jsonObject.getJSONObject( "4.2.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test4_2_3() { - JSONObject testResult = jsonObject.getJSONObject( "4.2.3" ); - assertEquals( "NON-STRICT", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test4_2_4() { - JSONObject testResult = jsonObject.getJSONObject( "4.2.4" ); - assertEquals( "NON-STRICT", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test4_2_5() { - JSONObject testResult = jsonObject.getJSONObject( "4.2.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 15 ); - } - - @Test - public void test5_1() { - JSONObject testResult = jsonObject.getJSONObject( "5.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test5_2() { - JSONObject testResult = jsonObject.getJSONObject( "5.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test5_3() { - JSONObject testResult = jsonObject.getJSONObject( "5.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test5_4() { - JSONObject testResult = jsonObject.getJSONObject( "5.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test5_5() { - JSONObject testResult = jsonObject.getJSONObject( "5.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 20 ); - } - - @Test - public void test5_6() { - JSONObject testResult = jsonObject.getJSONObject( "5.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 60 ); - } - - @Test - public void test5_7() { - JSONObject testResult = jsonObject.getJSONObject( "5.7" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 60 ); - } - - @Test - public void test5_8() { - JSONObject testResult = jsonObject.getJSONObject( "5.8" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 20 ); - } - - @Test - public void test5_9() { - JSONObject testResult = jsonObject.getJSONObject( "5.9" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test5_10() { - JSONObject testResult = jsonObject.getJSONObject( "5.10" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test5_11() { - JSONObject testResult = jsonObject.getJSONObject( "5.11" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 20 ); - } - - @Test - public void test5_12() { - JSONObject testResult = jsonObject.getJSONObject( "5.12" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test5_13() { - JSONObject testResult = jsonObject.getJSONObject( "5.13" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test5_14() { - JSONObject testResult = jsonObject.getJSONObject( "5.14" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test5_15() { - JSONObject testResult = jsonObject.getJSONObject( "5.15" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test5_16() { - JSONObject testResult = jsonObject.getJSONObject( "5.16" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test5_17() { - JSONObject testResult = jsonObject.getJSONObject( "5.17" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test5_18() { - JSONObject testResult = jsonObject.getJSONObject( "5.18" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test5_19() { - JSONObject testResult = jsonObject.getJSONObject( "5.19" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 1100 ); - } - - @Test - public void test5_20() { - JSONObject testResult = jsonObject.getJSONObject( "5.20" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 1100 ); - } - - @Test - public void test6_1_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.1.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_1_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.1.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_1_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.1.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_2_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.2.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_2_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.2.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_2_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.2.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_2_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.2.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_3_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.3.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_3_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.3.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_4_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.4.1" ); - assertEquals( "NON-STRICT", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 2100 ); - } - - @Test - public void test6_4_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.4.2" ); - assertEquals( "NON-STRICT", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 2100 ); - } - - @Test - public void test6_4_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.4.3" ); - assertEquals( "NON-STRICT", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 2100 ); - } - - @Test - public void test6_4_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.4.4" ); - assertEquals( "NON-STRICT", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 2100 ); - } - - @Test - public void test6_5_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.5.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_5_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.5.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_5_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.5.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_5_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.5.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_5_5() { - JSONObject testResult = jsonObject.getJSONObject( "6.5.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_6_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.6.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_6_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.6.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_6_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.6.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_6_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.6.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_6_5() { - JSONObject testResult = jsonObject.getJSONObject( "6.6.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_6_6() { - JSONObject testResult = jsonObject.getJSONObject( "6.6.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_6_7() { - JSONObject testResult = jsonObject.getJSONObject( "6.6.7" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_6_8() { - JSONObject testResult = jsonObject.getJSONObject( "6.6.8" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_6_9() { - JSONObject testResult = jsonObject.getJSONObject( "6.6.9" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_6_10() { - JSONObject testResult = jsonObject.getJSONObject( "6.6.10" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_6_11() { - JSONObject testResult = jsonObject.getJSONObject( "6.6.11" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_7_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.7.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_7_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.7.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_7_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.7.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_7_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.7.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_8_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.8.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_8_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.8.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_9_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.9.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_9_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.9.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_9_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.9.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_9_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.9.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_10_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.10.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_10_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.10.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_10_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.10.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_11_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.11.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_11_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.11.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_11_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.11.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_11_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.11.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_11_5() { - JSONObject testResult = jsonObject.getJSONObject( "6.11.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_12_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.12.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_12_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.12.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_12_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.12.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_12_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.12.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_12_5() { - JSONObject testResult = jsonObject.getJSONObject( "6.12.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_12_6() { - JSONObject testResult = jsonObject.getJSONObject( "6.12.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_12_7() { - JSONObject testResult = jsonObject.getJSONObject( "6.12.7" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_12_8() { - JSONObject testResult = jsonObject.getJSONObject( "6.12.8" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_13_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.13.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_13_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.13.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_13_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.13.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_13_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.13.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_13_5() { - JSONObject testResult = jsonObject.getJSONObject( "6.13.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_14_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.14.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_14_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.14.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_14_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.14.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_14_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.14.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_14_5() { - JSONObject testResult = jsonObject.getJSONObject( "6.14.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_14_6() { - JSONObject testResult = jsonObject.getJSONObject( "6.14.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_14_7() { - JSONObject testResult = jsonObject.getJSONObject( "6.14.7" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_14_8() { - JSONObject testResult = jsonObject.getJSONObject( "6.14.8" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_14_9() { - JSONObject testResult = jsonObject.getJSONObject( "6.14.9" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_14_10() { - JSONObject testResult = jsonObject.getJSONObject( "6.14.10" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_15_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.15.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_16_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.16.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_16_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.16.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_16_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.16.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_17_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.17.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_17_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.17.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_17_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.17.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_17_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.17.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_17_5() { - JSONObject testResult = jsonObject.getJSONObject( "6.17.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_18_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.18.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_18_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.18.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_18_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.18.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_18_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.18.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_18_5() { - JSONObject testResult = jsonObject.getJSONObject( "6.18.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_19_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.19.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_19_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.19.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_19_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.19.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_19_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.19.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_19_5() { - JSONObject testResult = jsonObject.getJSONObject( "6.19.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_20_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.20.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_20_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.20.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_20_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.20.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_20_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.20.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_20_5() { - JSONObject testResult = jsonObject.getJSONObject( "6.20.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_20_6() { - JSONObject testResult = jsonObject.getJSONObject( "6.20.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_20_7() { - JSONObject testResult = jsonObject.getJSONObject( "6.20.7" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_21_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.21.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_21_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.21.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_21_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.21.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_21_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.21.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_21_5() { - JSONObject testResult = jsonObject.getJSONObject( "6.21.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_21_6() { - JSONObject testResult = jsonObject.getJSONObject( "6.21.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_21_7() { - JSONObject testResult = jsonObject.getJSONObject( "6.21.7" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_21_8() { - JSONObject testResult = jsonObject.getJSONObject( "6.21.8" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_5() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_6() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_7() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.7" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_8() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.8" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_9() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.9" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_10() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.10" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_11() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.11" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_12() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.12" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_13() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.13" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_14() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.14" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_15() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.15" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_16() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.16" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_17() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.17" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_18() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.18" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_19() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.19" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_20() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.20" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_21() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.21" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_22() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.22" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_23() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.23" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_24() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.24" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_25() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.25" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_26() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.26" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_27() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.27" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_28() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.28" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_29() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.29" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_30() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.30" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_31() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.31" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_32() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.32" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_33() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.33" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_22_34() { - JSONObject testResult = jsonObject.getJSONObject( "6.22.34" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_23_1() { - JSONObject testResult = jsonObject.getJSONObject( "6.23.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_23_2() { - JSONObject testResult = jsonObject.getJSONObject( "6.23.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_23_3() { - JSONObject testResult = jsonObject.getJSONObject( "6.23.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_23_4() { - JSONObject testResult = jsonObject.getJSONObject( "6.23.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_23_5() { - JSONObject testResult = jsonObject.getJSONObject( "6.23.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_23_6() { - JSONObject testResult = jsonObject.getJSONObject( "6.23.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test6_23_7() { - JSONObject testResult = jsonObject.getJSONObject( "6.23.7" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_1_1() { - JSONObject testResult = jsonObject.getJSONObject( "7.1.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_1_2() { - JSONObject testResult = jsonObject.getJSONObject( "7.1.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_1_3() { - JSONObject testResult = jsonObject.getJSONObject( "7.1.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_1_4() { - JSONObject testResult = jsonObject.getJSONObject( "7.1.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_1_5() { - JSONObject testResult = jsonObject.getJSONObject( "7.1.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_1_6() { - JSONObject testResult = jsonObject.getJSONObject( "7.1.6" ); - assertEquals( "INFORMATIONAL", testResult.get( "behavior" ) ); - assertEquals( "INFORMATIONAL", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 50 ); - } - - @Test - public void test7_3_1() { - JSONObject testResult = jsonObject.getJSONObject( "7.3.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_3_2() { - JSONObject testResult = jsonObject.getJSONObject( "7.3.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_3_3() { - JSONObject testResult = jsonObject.getJSONObject( "7.3.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_3_4() { - JSONObject testResult = jsonObject.getJSONObject( "7.3.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_3_5() { - JSONObject testResult = jsonObject.getJSONObject( "7.3.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_3_6() { - JSONObject testResult = jsonObject.getJSONObject( "7.3.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_5_1() { - JSONObject testResult = jsonObject.getJSONObject( "7.5.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_7_1() { - JSONObject testResult = jsonObject.getJSONObject( "7.7.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_7_2() { - JSONObject testResult = jsonObject.getJSONObject( "7.7.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_7_3() { - JSONObject testResult = jsonObject.getJSONObject( "7.7.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_7_4() { - JSONObject testResult = jsonObject.getJSONObject( "7.7.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_7_5() { - JSONObject testResult = jsonObject.getJSONObject( "7.7.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_7_6() { - JSONObject testResult = jsonObject.getJSONObject( "7.7.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_7_7() { - JSONObject testResult = jsonObject.getJSONObject( "7.7.7" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_7_8() { - JSONObject testResult = jsonObject.getJSONObject( "7.7.8" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_7_9() { - JSONObject testResult = jsonObject.getJSONObject( "7.7.9" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_7_10() { - JSONObject testResult = jsonObject.getJSONObject( "7.7.10" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_7_11() { - JSONObject testResult = jsonObject.getJSONObject( "7.7.11" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_7_12() { - JSONObject testResult = jsonObject.getJSONObject( "7.7.12" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_7_13() { - JSONObject testResult = jsonObject.getJSONObject( "7.7.13" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_9_1() { - JSONObject testResult = jsonObject.getJSONObject( "7.9.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_9_2() { - JSONObject testResult = jsonObject.getJSONObject( "7.9.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_9_3() { - JSONObject testResult = jsonObject.getJSONObject( "7.9.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_9_4() { - JSONObject testResult = jsonObject.getJSONObject( "7.9.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_9_5() { - JSONObject testResult = jsonObject.getJSONObject( "7.9.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_9_7() { - JSONObject testResult = jsonObject.getJSONObject( "7.9.7" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_9_8() { - JSONObject testResult = jsonObject.getJSONObject( "7.9.8" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_9_9() { - JSONObject testResult = jsonObject.getJSONObject( "7.9.9" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_9_10() { - JSONObject testResult = jsonObject.getJSONObject( "7.9.10" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_9_11() { - JSONObject testResult = jsonObject.getJSONObject( "7.9.11" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_13_1() { - JSONObject testResult = jsonObject.getJSONObject( "7.13.1" ); - assertEquals( "INFORMATIONAL", testResult.get( "behavior" ) ); - assertEquals( "INFORMATIONAL", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test7_13_2() { - JSONObject testResult = jsonObject.getJSONObject( "7.13.2" ); - assertEquals( "INFORMATIONAL", testResult.get( "behavior" ) ); - assertEquals( "INFORMATIONAL", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test9_1_1() { - JSONObject testResult = jsonObject.getJSONObject( "9.1.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test9_1_2() { - JSONObject testResult = jsonObject.getJSONObject( "9.1.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 20 ); - } - - @Test - public void test9_1_3() { - JSONObject testResult = jsonObject.getJSONObject( "9.1.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 70 ); - } - - @Test - public void test9_1_4() { - JSONObject testResult = jsonObject.getJSONObject( "9.1.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 375 ); - } - - @Test - public void test9_1_5() { - JSONObject testResult = jsonObject.getJSONObject( "9.1.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 750 ); - } - - @Test - public void test9_1_6() { - JSONObject testResult = jsonObject.getJSONObject( "9.1.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 1000 ); - } - - @Test - public void test9_2_1() { - JSONObject testResult = jsonObject.getJSONObject( "9.2.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } - - @Test - public void test9_2_2() { - JSONObject testResult = jsonObject.getJSONObject( "9.2.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 20 ); - } - - @Test - public void test9_2_3() { - JSONObject testResult = jsonObject.getJSONObject( "9.2.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 70 ); - } - - @Test - public void test9_2_4() { - JSONObject testResult = jsonObject.getJSONObject( "9.2.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 250 ); - } - - @Test - public void test9_2_5() { - JSONObject testResult = jsonObject.getJSONObject( "9.2.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 350 ); - } - - @Test - public void test9_2_6() { - JSONObject testResult = jsonObject.getJSONObject( "9.2.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 800 ); - } - - @Test - public void test9_3_1() { - JSONObject testResult = jsonObject.getJSONObject( "9.3.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 2000 ); - } - - @Test - public void test9_3_2() { - JSONObject testResult = jsonObject.getJSONObject( "9.3.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 600 ); - } - - @Test - public void test9_3_3() { - JSONObject testResult = jsonObject.getJSONObject( "9.3.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 300 ); - } - - @Test - public void test9_3_4() { - JSONObject testResult = jsonObject.getJSONObject( "9.3.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 250 ); - } - - @Test - public void test9_3_5() { - JSONObject testResult = jsonObject.getJSONObject( "9.3.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 200 ); - } - - @Test - public void test9_3_6() { - JSONObject testResult = jsonObject.getJSONObject( "9.3.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 175 ); - } - @Test - public void test9_3_7() { - JSONObject testResult = jsonObject.getJSONObject( "9.3.7" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 175 ); - } - - - @Test - public void test9_3_8() { - JSONObject testResult = jsonObject.getJSONObject( "9.3.8" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 160 ); - } - - @Test - public void test9_3_9() { - JSONObject testResult = jsonObject.getJSONObject( "9.3.9" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 160 ); - } - - @Test - public void test9_4_1() { - JSONObject testResult = jsonObject.getJSONObject( "9.4.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 2300 ); - } - - @Test - public void test9_4_2() { - JSONObject testResult = jsonObject.getJSONObject( "9.4.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 700 ); - } - - @Test - public void test9_4_3() { - JSONObject testResult = jsonObject.getJSONObject( "9.4.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 350 ); - } - - @Test - public void test9_4_4() { - JSONObject testResult = jsonObject.getJSONObject( "9.4.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 175 ); - } - - @Test - public void test9_4_5() { - JSONObject testResult = jsonObject.getJSONObject( "9.4.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 150 ); - } - - @Test - public void test9_4_6() { - JSONObject testResult = jsonObject.getJSONObject( "9.4.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 100 ); - } - - @Test - public void test9_4_7() { - JSONObject testResult = jsonObject.getJSONObject( "9.4.7" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 125 ); - } - - @Test - public void test9_4_8() { - JSONObject testResult = jsonObject.getJSONObject( "9.4.8" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 125 ); - } - - @Test - public void test9_4_9() { - JSONObject testResult = jsonObject.getJSONObject( "9.4.9" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 125 ); - } - - @Test - public void test9_5_1() { - JSONObject testResult = jsonObject.getJSONObject( "9.5.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 3200 ); - } - - @Test - public void test9_5_2() { - JSONObject testResult = jsonObject.getJSONObject( "9.5.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 1300 ); - } - - @Test - public void test9_5_3() { - JSONObject testResult = jsonObject.getJSONObject( "9.5.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 700 ); - } - - @Test - public void test9_5_4() { - JSONObject testResult = jsonObject.getJSONObject( "9.5.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 450 ); - } - - @Test - public void test9_5_5() { - JSONObject testResult = jsonObject.getJSONObject( "9.5.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 250 ); - } - - @Test - public void test9_5_6() { - JSONObject testResult = jsonObject.getJSONObject( "9.5.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 150 ); - } - - @Test - public void test9_6_1() { - JSONObject testResult = jsonObject.getJSONObject( "9.6.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 3000 ); - } - - @Test - public void test9_6_2() { - JSONObject testResult = jsonObject.getJSONObject( "9.6.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 1500 ); - } - - @Test - public void test9_6_3() { - JSONObject testResult = jsonObject.getJSONObject( "9.6.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 750 ); - } - - @Test - public void test9_6_4() { - JSONObject testResult = jsonObject.getJSONObject( "9.6.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 450 ); - } - - @Test - public void test9_6_5() { - JSONObject testResult = jsonObject.getJSONObject( "9.6.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 250 ); - } - - @Test - public void test9_6_6() { - JSONObject testResult = jsonObject.getJSONObject( "9.6.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 200 ); - } - - @Test - public void test9_7_1() { - JSONObject testResult = jsonObject.getJSONObject( "9.7.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 500 ); - } - - @Test - public void test9_7_2() { - JSONObject testResult = jsonObject.getJSONObject( "9.7.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 400 ); - } - - @Test - public void test9_7_3() { - JSONObject testResult = jsonObject.getJSONObject( "9.7.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 400 ); - } - - @Test - public void test9_7_4() { - JSONObject testResult = jsonObject.getJSONObject( "9.7.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 400 ); - } - - @Test - public void test9_7_5() { - JSONObject testResult = jsonObject.getJSONObject( "9.7.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 550 ); - } - - @Test - public void test9_7_6() { - JSONObject testResult = jsonObject.getJSONObject( "9.7.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 850 ); - } - - @Test - public void test9_8_1() { - JSONObject testResult = jsonObject.getJSONObject( "9.8.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 300 ); - } - - @Test - public void test9_8_2() { - JSONObject testResult = jsonObject.getJSONObject( "9.8.2" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 320 ); - } - - @Test - public void test9_8_3() { - JSONObject testResult = jsonObject.getJSONObject( "9.8.3" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 400 ); - } - - @Test - public void test9_8_4() { - JSONObject testResult = jsonObject.getJSONObject( "9.8.4" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 400 ); - } - - @Test - public void test9_8_5() { - JSONObject testResult = jsonObject.getJSONObject( "9.8.5" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 470 ); - } - - @Test - public void test9_8_6() { - JSONObject testResult = jsonObject.getJSONObject( "9.8.6" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 770 ); - } - - @Test - public void test10_1_1() { - JSONObject testResult = jsonObject.getJSONObject( "10.1.1" ); - assertEquals( "OK", testResult.get( "behavior" ) ); - assertEquals( "OK", testResult.get( "behaviorClose" ) ); - Assume.assumeTrue("Duration: " + testResult.getInt( "duration" ), testResult.getInt( "duration" ) < 10 ); - } + static JSONObject jsonObject = null; + + @BeforeClass + public static void getJSONObject() throws FileNotFoundException { + File file = new File("reports/servers/index.json"); + //File file = new File( "C:\\Python27\\Scripts\\reports\\servers\\index.json" ); + if (file.exists()) { + String content = new Scanner(file).useDelimiter("\\Z").next(); + jsonObject = new JSONObject(content); + jsonObject = jsonObject.getJSONObject("TooTallNate Java-WebSocket"); + } + Assume.assumeTrue(jsonObject != null); + } + + @Test + public void test1_1_1() { + JSONObject testResult = jsonObject.getJSONObject("1.1.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test1_1_2() { + JSONObject testResult = jsonObject.getJSONObject("1.1.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test1_1_3() { + JSONObject testResult = jsonObject.getJSONObject("1.1.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test1_1_4() { + JSONObject testResult = jsonObject.getJSONObject("1.1.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test1_1_5() { + JSONObject testResult = jsonObject.getJSONObject("1.1.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test1_1_6() { + JSONObject testResult = jsonObject.getJSONObject("1.1.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 30); + } + + @Test + public void test1_1_7() { + JSONObject testResult = jsonObject.getJSONObject("1.1.7"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 20); + } + + @Test + public void test1_1_8() { + JSONObject testResult = jsonObject.getJSONObject("1.1.8"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 30); + } + + @Test + public void test1_2_1() { + JSONObject testResult = jsonObject.getJSONObject("1.2.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test1_2_2() { + JSONObject testResult = jsonObject.getJSONObject("1.2.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test1_2_3() { + JSONObject testResult = jsonObject.getJSONObject("1.2.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test1_2_4() { + JSONObject testResult = jsonObject.getJSONObject("1.2.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 20); + } + + @Test + public void test1_2_5() { + JSONObject testResult = jsonObject.getJSONObject("1.2.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test1_2_6() { + JSONObject testResult = jsonObject.getJSONObject("1.2.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 70); + } + + @Test + public void test1_2_7() { + JSONObject testResult = jsonObject.getJSONObject("1.2.7"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 70); + } + + @Test + public void test1_2_8() { + JSONObject testResult = jsonObject.getJSONObject("1.2.8"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 60); + } + + @Test + public void test2_1() { + JSONObject testResult = jsonObject.getJSONObject("2.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test2_2() { + JSONObject testResult = jsonObject.getJSONObject("2.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test2_3() { + JSONObject testResult = jsonObject.getJSONObject("2.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test2_4() { + JSONObject testResult = jsonObject.getJSONObject("2.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test2_5() { + JSONObject testResult = jsonObject.getJSONObject("2.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test2_6() { + JSONObject testResult = jsonObject.getJSONObject("2.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 30); + } + + @Test + public void test2_7() { + JSONObject testResult = jsonObject.getJSONObject("2.7"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test2_8() { + JSONObject testResult = jsonObject.getJSONObject("2.8"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test2_9() { + JSONObject testResult = jsonObject.getJSONObject("2.9"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test2_10() { + JSONObject testResult = jsonObject.getJSONObject("2.10"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 60); + } + + @Test + public void test2_11() { + JSONObject testResult = jsonObject.getJSONObject("2.11"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 50); + } + + @Test + public void test3_1() { + JSONObject testResult = jsonObject.getJSONObject("3.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test3_2() { + JSONObject testResult = jsonObject.getJSONObject("3.2"); + assertEquals("NON-STRICT", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test3_3() { + JSONObject testResult = jsonObject.getJSONObject("3.3"); + assertEquals("NON-STRICT", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test3_4() { + JSONObject testResult = jsonObject.getJSONObject("3.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 20); + } + + @Test + public void test3_5() { + JSONObject testResult = jsonObject.getJSONObject("3.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test3_6() { + JSONObject testResult = jsonObject.getJSONObject("3.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test3_7() { + JSONObject testResult = jsonObject.getJSONObject("3.7"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test4_1_1() { + JSONObject testResult = jsonObject.getJSONObject("4.1.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test4_1_2() { + JSONObject testResult = jsonObject.getJSONObject("4.1.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test4_1_3() { + JSONObject testResult = jsonObject.getJSONObject("4.1.3"); + assertEquals("NON-STRICT", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test4_1_4() { + JSONObject testResult = jsonObject.getJSONObject("4.1.4"); + assertEquals("NON-STRICT", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test4_1_5() { + JSONObject testResult = jsonObject.getJSONObject("4.1.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test4_2_1() { + JSONObject testResult = jsonObject.getJSONObject("4.2.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test4_2_2() { + JSONObject testResult = jsonObject.getJSONObject("4.2.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test4_2_3() { + JSONObject testResult = jsonObject.getJSONObject("4.2.3"); + assertEquals("NON-STRICT", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test4_2_4() { + JSONObject testResult = jsonObject.getJSONObject("4.2.4"); + assertEquals("NON-STRICT", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test4_2_5() { + JSONObject testResult = jsonObject.getJSONObject("4.2.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 15); + } + + @Test + public void test5_1() { + JSONObject testResult = jsonObject.getJSONObject("5.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test5_2() { + JSONObject testResult = jsonObject.getJSONObject("5.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test5_3() { + JSONObject testResult = jsonObject.getJSONObject("5.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test5_4() { + JSONObject testResult = jsonObject.getJSONObject("5.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test5_5() { + JSONObject testResult = jsonObject.getJSONObject("5.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 20); + } + + @Test + public void test5_6() { + JSONObject testResult = jsonObject.getJSONObject("5.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 60); + } + + @Test + public void test5_7() { + JSONObject testResult = jsonObject.getJSONObject("5.7"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 60); + } + + @Test + public void test5_8() { + JSONObject testResult = jsonObject.getJSONObject("5.8"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 20); + } + + @Test + public void test5_9() { + JSONObject testResult = jsonObject.getJSONObject("5.9"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test5_10() { + JSONObject testResult = jsonObject.getJSONObject("5.10"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test5_11() { + JSONObject testResult = jsonObject.getJSONObject("5.11"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 20); + } + + @Test + public void test5_12() { + JSONObject testResult = jsonObject.getJSONObject("5.12"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test5_13() { + JSONObject testResult = jsonObject.getJSONObject("5.13"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test5_14() { + JSONObject testResult = jsonObject.getJSONObject("5.14"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test5_15() { + JSONObject testResult = jsonObject.getJSONObject("5.15"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test5_16() { + JSONObject testResult = jsonObject.getJSONObject("5.16"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test5_17() { + JSONObject testResult = jsonObject.getJSONObject("5.17"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test5_18() { + JSONObject testResult = jsonObject.getJSONObject("5.18"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test5_19() { + JSONObject testResult = jsonObject.getJSONObject("5.19"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 1100); + } + + @Test + public void test5_20() { + JSONObject testResult = jsonObject.getJSONObject("5.20"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 1100); + } + + @Test + public void test6_1_1() { + JSONObject testResult = jsonObject.getJSONObject("6.1.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_1_2() { + JSONObject testResult = jsonObject.getJSONObject("6.1.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_1_3() { + JSONObject testResult = jsonObject.getJSONObject("6.1.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_2_1() { + JSONObject testResult = jsonObject.getJSONObject("6.2.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_2_2() { + JSONObject testResult = jsonObject.getJSONObject("6.2.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_2_3() { + JSONObject testResult = jsonObject.getJSONObject("6.2.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_2_4() { + JSONObject testResult = jsonObject.getJSONObject("6.2.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_3_1() { + JSONObject testResult = jsonObject.getJSONObject("6.3.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_3_2() { + JSONObject testResult = jsonObject.getJSONObject("6.3.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_4_1() { + JSONObject testResult = jsonObject.getJSONObject("6.4.1"); + assertEquals("NON-STRICT", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 2100); + } + + @Test + public void test6_4_2() { + JSONObject testResult = jsonObject.getJSONObject("6.4.2"); + assertEquals("NON-STRICT", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 2100); + } + + @Test + public void test6_4_3() { + JSONObject testResult = jsonObject.getJSONObject("6.4.3"); + assertEquals("NON-STRICT", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 2100); + } + + @Test + public void test6_4_4() { + JSONObject testResult = jsonObject.getJSONObject("6.4.4"); + assertEquals("NON-STRICT", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 2100); + } + + @Test + public void test6_5_1() { + JSONObject testResult = jsonObject.getJSONObject("6.5.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_5_2() { + JSONObject testResult = jsonObject.getJSONObject("6.5.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_5_3() { + JSONObject testResult = jsonObject.getJSONObject("6.5.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_5_4() { + JSONObject testResult = jsonObject.getJSONObject("6.5.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_5_5() { + JSONObject testResult = jsonObject.getJSONObject("6.5.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_6_1() { + JSONObject testResult = jsonObject.getJSONObject("6.6.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_6_2() { + JSONObject testResult = jsonObject.getJSONObject("6.6.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_6_3() { + JSONObject testResult = jsonObject.getJSONObject("6.6.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_6_4() { + JSONObject testResult = jsonObject.getJSONObject("6.6.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_6_5() { + JSONObject testResult = jsonObject.getJSONObject("6.6.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_6_6() { + JSONObject testResult = jsonObject.getJSONObject("6.6.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_6_7() { + JSONObject testResult = jsonObject.getJSONObject("6.6.7"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_6_8() { + JSONObject testResult = jsonObject.getJSONObject("6.6.8"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_6_9() { + JSONObject testResult = jsonObject.getJSONObject("6.6.9"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_6_10() { + JSONObject testResult = jsonObject.getJSONObject("6.6.10"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_6_11() { + JSONObject testResult = jsonObject.getJSONObject("6.6.11"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_7_1() { + JSONObject testResult = jsonObject.getJSONObject("6.7.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_7_2() { + JSONObject testResult = jsonObject.getJSONObject("6.7.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_7_3() { + JSONObject testResult = jsonObject.getJSONObject("6.7.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_7_4() { + JSONObject testResult = jsonObject.getJSONObject("6.7.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_8_1() { + JSONObject testResult = jsonObject.getJSONObject("6.8.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_8_2() { + JSONObject testResult = jsonObject.getJSONObject("6.8.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_9_1() { + JSONObject testResult = jsonObject.getJSONObject("6.9.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_9_2() { + JSONObject testResult = jsonObject.getJSONObject("6.9.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_9_3() { + JSONObject testResult = jsonObject.getJSONObject("6.9.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_9_4() { + JSONObject testResult = jsonObject.getJSONObject("6.9.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_10_1() { + JSONObject testResult = jsonObject.getJSONObject("6.10.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_10_2() { + JSONObject testResult = jsonObject.getJSONObject("6.10.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_10_3() { + JSONObject testResult = jsonObject.getJSONObject("6.10.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_11_1() { + JSONObject testResult = jsonObject.getJSONObject("6.11.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_11_2() { + JSONObject testResult = jsonObject.getJSONObject("6.11.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_11_3() { + JSONObject testResult = jsonObject.getJSONObject("6.11.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_11_4() { + JSONObject testResult = jsonObject.getJSONObject("6.11.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_11_5() { + JSONObject testResult = jsonObject.getJSONObject("6.11.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_12_1() { + JSONObject testResult = jsonObject.getJSONObject("6.12.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_12_2() { + JSONObject testResult = jsonObject.getJSONObject("6.12.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_12_3() { + JSONObject testResult = jsonObject.getJSONObject("6.12.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_12_4() { + JSONObject testResult = jsonObject.getJSONObject("6.12.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_12_5() { + JSONObject testResult = jsonObject.getJSONObject("6.12.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_12_6() { + JSONObject testResult = jsonObject.getJSONObject("6.12.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_12_7() { + JSONObject testResult = jsonObject.getJSONObject("6.12.7"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_12_8() { + JSONObject testResult = jsonObject.getJSONObject("6.12.8"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_13_1() { + JSONObject testResult = jsonObject.getJSONObject("6.13.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_13_2() { + JSONObject testResult = jsonObject.getJSONObject("6.13.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_13_3() { + JSONObject testResult = jsonObject.getJSONObject("6.13.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_13_4() { + JSONObject testResult = jsonObject.getJSONObject("6.13.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_13_5() { + JSONObject testResult = jsonObject.getJSONObject("6.13.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_14_1() { + JSONObject testResult = jsonObject.getJSONObject("6.14.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_14_2() { + JSONObject testResult = jsonObject.getJSONObject("6.14.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_14_3() { + JSONObject testResult = jsonObject.getJSONObject("6.14.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_14_4() { + JSONObject testResult = jsonObject.getJSONObject("6.14.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_14_5() { + JSONObject testResult = jsonObject.getJSONObject("6.14.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_14_6() { + JSONObject testResult = jsonObject.getJSONObject("6.14.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_14_7() { + JSONObject testResult = jsonObject.getJSONObject("6.14.7"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_14_8() { + JSONObject testResult = jsonObject.getJSONObject("6.14.8"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_14_9() { + JSONObject testResult = jsonObject.getJSONObject("6.14.9"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_14_10() { + JSONObject testResult = jsonObject.getJSONObject("6.14.10"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_15_1() { + JSONObject testResult = jsonObject.getJSONObject("6.15.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_16_1() { + JSONObject testResult = jsonObject.getJSONObject("6.16.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_16_2() { + JSONObject testResult = jsonObject.getJSONObject("6.16.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_16_3() { + JSONObject testResult = jsonObject.getJSONObject("6.16.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_17_1() { + JSONObject testResult = jsonObject.getJSONObject("6.17.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_17_2() { + JSONObject testResult = jsonObject.getJSONObject("6.17.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_17_3() { + JSONObject testResult = jsonObject.getJSONObject("6.17.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_17_4() { + JSONObject testResult = jsonObject.getJSONObject("6.17.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_17_5() { + JSONObject testResult = jsonObject.getJSONObject("6.17.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_18_1() { + JSONObject testResult = jsonObject.getJSONObject("6.18.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_18_2() { + JSONObject testResult = jsonObject.getJSONObject("6.18.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_18_3() { + JSONObject testResult = jsonObject.getJSONObject("6.18.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_18_4() { + JSONObject testResult = jsonObject.getJSONObject("6.18.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_18_5() { + JSONObject testResult = jsonObject.getJSONObject("6.18.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_19_1() { + JSONObject testResult = jsonObject.getJSONObject("6.19.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_19_2() { + JSONObject testResult = jsonObject.getJSONObject("6.19.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_19_3() { + JSONObject testResult = jsonObject.getJSONObject("6.19.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_19_4() { + JSONObject testResult = jsonObject.getJSONObject("6.19.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_19_5() { + JSONObject testResult = jsonObject.getJSONObject("6.19.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_20_1() { + JSONObject testResult = jsonObject.getJSONObject("6.20.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_20_2() { + JSONObject testResult = jsonObject.getJSONObject("6.20.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_20_3() { + JSONObject testResult = jsonObject.getJSONObject("6.20.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_20_4() { + JSONObject testResult = jsonObject.getJSONObject("6.20.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_20_5() { + JSONObject testResult = jsonObject.getJSONObject("6.20.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_20_6() { + JSONObject testResult = jsonObject.getJSONObject("6.20.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_20_7() { + JSONObject testResult = jsonObject.getJSONObject("6.20.7"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_21_1() { + JSONObject testResult = jsonObject.getJSONObject("6.21.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_21_2() { + JSONObject testResult = jsonObject.getJSONObject("6.21.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_21_3() { + JSONObject testResult = jsonObject.getJSONObject("6.21.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_21_4() { + JSONObject testResult = jsonObject.getJSONObject("6.21.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_21_5() { + JSONObject testResult = jsonObject.getJSONObject("6.21.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_21_6() { + JSONObject testResult = jsonObject.getJSONObject("6.21.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_21_7() { + JSONObject testResult = jsonObject.getJSONObject("6.21.7"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_21_8() { + JSONObject testResult = jsonObject.getJSONObject("6.21.8"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_1() { + JSONObject testResult = jsonObject.getJSONObject("6.22.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_2() { + JSONObject testResult = jsonObject.getJSONObject("6.22.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_3() { + JSONObject testResult = jsonObject.getJSONObject("6.22.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_4() { + JSONObject testResult = jsonObject.getJSONObject("6.22.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_5() { + JSONObject testResult = jsonObject.getJSONObject("6.22.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_6() { + JSONObject testResult = jsonObject.getJSONObject("6.22.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_7() { + JSONObject testResult = jsonObject.getJSONObject("6.22.7"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_8() { + JSONObject testResult = jsonObject.getJSONObject("6.22.8"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_9() { + JSONObject testResult = jsonObject.getJSONObject("6.22.9"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_10() { + JSONObject testResult = jsonObject.getJSONObject("6.22.10"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_11() { + JSONObject testResult = jsonObject.getJSONObject("6.22.11"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_12() { + JSONObject testResult = jsonObject.getJSONObject("6.22.12"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_13() { + JSONObject testResult = jsonObject.getJSONObject("6.22.13"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_14() { + JSONObject testResult = jsonObject.getJSONObject("6.22.14"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_15() { + JSONObject testResult = jsonObject.getJSONObject("6.22.15"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_16() { + JSONObject testResult = jsonObject.getJSONObject("6.22.16"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_17() { + JSONObject testResult = jsonObject.getJSONObject("6.22.17"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_18() { + JSONObject testResult = jsonObject.getJSONObject("6.22.18"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_19() { + JSONObject testResult = jsonObject.getJSONObject("6.22.19"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_20() { + JSONObject testResult = jsonObject.getJSONObject("6.22.20"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_21() { + JSONObject testResult = jsonObject.getJSONObject("6.22.21"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_22() { + JSONObject testResult = jsonObject.getJSONObject("6.22.22"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_23() { + JSONObject testResult = jsonObject.getJSONObject("6.22.23"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_24() { + JSONObject testResult = jsonObject.getJSONObject("6.22.24"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_25() { + JSONObject testResult = jsonObject.getJSONObject("6.22.25"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_26() { + JSONObject testResult = jsonObject.getJSONObject("6.22.26"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_27() { + JSONObject testResult = jsonObject.getJSONObject("6.22.27"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_28() { + JSONObject testResult = jsonObject.getJSONObject("6.22.28"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_29() { + JSONObject testResult = jsonObject.getJSONObject("6.22.29"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_30() { + JSONObject testResult = jsonObject.getJSONObject("6.22.30"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_31() { + JSONObject testResult = jsonObject.getJSONObject("6.22.31"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_32() { + JSONObject testResult = jsonObject.getJSONObject("6.22.32"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_33() { + JSONObject testResult = jsonObject.getJSONObject("6.22.33"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_22_34() { + JSONObject testResult = jsonObject.getJSONObject("6.22.34"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_23_1() { + JSONObject testResult = jsonObject.getJSONObject("6.23.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_23_2() { + JSONObject testResult = jsonObject.getJSONObject("6.23.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_23_3() { + JSONObject testResult = jsonObject.getJSONObject("6.23.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_23_4() { + JSONObject testResult = jsonObject.getJSONObject("6.23.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_23_5() { + JSONObject testResult = jsonObject.getJSONObject("6.23.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_23_6() { + JSONObject testResult = jsonObject.getJSONObject("6.23.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test6_23_7() { + JSONObject testResult = jsonObject.getJSONObject("6.23.7"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_1_1() { + JSONObject testResult = jsonObject.getJSONObject("7.1.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_1_2() { + JSONObject testResult = jsonObject.getJSONObject("7.1.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_1_3() { + JSONObject testResult = jsonObject.getJSONObject("7.1.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_1_4() { + JSONObject testResult = jsonObject.getJSONObject("7.1.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_1_5() { + JSONObject testResult = jsonObject.getJSONObject("7.1.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_1_6() { + JSONObject testResult = jsonObject.getJSONObject("7.1.6"); + assertEquals("INFORMATIONAL", testResult.get("behavior")); + assertEquals("INFORMATIONAL", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 50); + } + + @Test + public void test7_3_1() { + JSONObject testResult = jsonObject.getJSONObject("7.3.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_3_2() { + JSONObject testResult = jsonObject.getJSONObject("7.3.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_3_3() { + JSONObject testResult = jsonObject.getJSONObject("7.3.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_3_4() { + JSONObject testResult = jsonObject.getJSONObject("7.3.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_3_5() { + JSONObject testResult = jsonObject.getJSONObject("7.3.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_3_6() { + JSONObject testResult = jsonObject.getJSONObject("7.3.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_5_1() { + JSONObject testResult = jsonObject.getJSONObject("7.5.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_7_1() { + JSONObject testResult = jsonObject.getJSONObject("7.7.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_7_2() { + JSONObject testResult = jsonObject.getJSONObject("7.7.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_7_3() { + JSONObject testResult = jsonObject.getJSONObject("7.7.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_7_4() { + JSONObject testResult = jsonObject.getJSONObject("7.7.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_7_5() { + JSONObject testResult = jsonObject.getJSONObject("7.7.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_7_6() { + JSONObject testResult = jsonObject.getJSONObject("7.7.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_7_7() { + JSONObject testResult = jsonObject.getJSONObject("7.7.7"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_7_8() { + JSONObject testResult = jsonObject.getJSONObject("7.7.8"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_7_9() { + JSONObject testResult = jsonObject.getJSONObject("7.7.9"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_7_10() { + JSONObject testResult = jsonObject.getJSONObject("7.7.10"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_7_11() { + JSONObject testResult = jsonObject.getJSONObject("7.7.11"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_7_12() { + JSONObject testResult = jsonObject.getJSONObject("7.7.12"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_7_13() { + JSONObject testResult = jsonObject.getJSONObject("7.7.13"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_9_1() { + JSONObject testResult = jsonObject.getJSONObject("7.9.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_9_2() { + JSONObject testResult = jsonObject.getJSONObject("7.9.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_9_3() { + JSONObject testResult = jsonObject.getJSONObject("7.9.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_9_4() { + JSONObject testResult = jsonObject.getJSONObject("7.9.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_9_5() { + JSONObject testResult = jsonObject.getJSONObject("7.9.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_9_7() { + JSONObject testResult = jsonObject.getJSONObject("7.9.7"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_9_8() { + JSONObject testResult = jsonObject.getJSONObject("7.9.8"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_9_9() { + JSONObject testResult = jsonObject.getJSONObject("7.9.9"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_9_10() { + JSONObject testResult = jsonObject.getJSONObject("7.9.10"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_9_11() { + JSONObject testResult = jsonObject.getJSONObject("7.9.11"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_13_1() { + JSONObject testResult = jsonObject.getJSONObject("7.13.1"); + assertEquals("INFORMATIONAL", testResult.get("behavior")); + assertEquals("INFORMATIONAL", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test7_13_2() { + JSONObject testResult = jsonObject.getJSONObject("7.13.2"); + assertEquals("INFORMATIONAL", testResult.get("behavior")); + assertEquals("INFORMATIONAL", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test9_1_1() { + JSONObject testResult = jsonObject.getJSONObject("9.1.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test9_1_2() { + JSONObject testResult = jsonObject.getJSONObject("9.1.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 20); + } + + @Test + public void test9_1_3() { + JSONObject testResult = jsonObject.getJSONObject("9.1.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 70); + } + + @Test + public void test9_1_4() { + JSONObject testResult = jsonObject.getJSONObject("9.1.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 375); + } + + @Test + public void test9_1_5() { + JSONObject testResult = jsonObject.getJSONObject("9.1.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 750); + } + + @Test + public void test9_1_6() { + JSONObject testResult = jsonObject.getJSONObject("9.1.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 1000); + } + + @Test + public void test9_2_1() { + JSONObject testResult = jsonObject.getJSONObject("9.2.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } + + @Test + public void test9_2_2() { + JSONObject testResult = jsonObject.getJSONObject("9.2.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 20); + } + + @Test + public void test9_2_3() { + JSONObject testResult = jsonObject.getJSONObject("9.2.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 70); + } + + @Test + public void test9_2_4() { + JSONObject testResult = jsonObject.getJSONObject("9.2.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 250); + } + + @Test + public void test9_2_5() { + JSONObject testResult = jsonObject.getJSONObject("9.2.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 350); + } + + @Test + public void test9_2_6() { + JSONObject testResult = jsonObject.getJSONObject("9.2.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 800); + } + + @Test + public void test9_3_1() { + JSONObject testResult = jsonObject.getJSONObject("9.3.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 2000); + } + + @Test + public void test9_3_2() { + JSONObject testResult = jsonObject.getJSONObject("9.3.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 600); + } + + @Test + public void test9_3_3() { + JSONObject testResult = jsonObject.getJSONObject("9.3.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 300); + } + + @Test + public void test9_3_4() { + JSONObject testResult = jsonObject.getJSONObject("9.3.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 250); + } + + @Test + public void test9_3_5() { + JSONObject testResult = jsonObject.getJSONObject("9.3.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 200); + } + + @Test + public void test9_3_6() { + JSONObject testResult = jsonObject.getJSONObject("9.3.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 175); + } + + @Test + public void test9_3_7() { + JSONObject testResult = jsonObject.getJSONObject("9.3.7"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 175); + } + + + @Test + public void test9_3_8() { + JSONObject testResult = jsonObject.getJSONObject("9.3.8"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 160); + } + + @Test + public void test9_3_9() { + JSONObject testResult = jsonObject.getJSONObject("9.3.9"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 160); + } + + @Test + public void test9_4_1() { + JSONObject testResult = jsonObject.getJSONObject("9.4.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 2300); + } + + @Test + public void test9_4_2() { + JSONObject testResult = jsonObject.getJSONObject("9.4.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 700); + } + + @Test + public void test9_4_3() { + JSONObject testResult = jsonObject.getJSONObject("9.4.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 350); + } + + @Test + public void test9_4_4() { + JSONObject testResult = jsonObject.getJSONObject("9.4.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 175); + } + + @Test + public void test9_4_5() { + JSONObject testResult = jsonObject.getJSONObject("9.4.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 150); + } + + @Test + public void test9_4_6() { + JSONObject testResult = jsonObject.getJSONObject("9.4.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 100); + } + + @Test + public void test9_4_7() { + JSONObject testResult = jsonObject.getJSONObject("9.4.7"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 125); + } + + @Test + public void test9_4_8() { + JSONObject testResult = jsonObject.getJSONObject("9.4.8"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 125); + } + + @Test + public void test9_4_9() { + JSONObject testResult = jsonObject.getJSONObject("9.4.9"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 125); + } + + @Test + public void test9_5_1() { + JSONObject testResult = jsonObject.getJSONObject("9.5.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 3200); + } + + @Test + public void test9_5_2() { + JSONObject testResult = jsonObject.getJSONObject("9.5.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 1300); + } + + @Test + public void test9_5_3() { + JSONObject testResult = jsonObject.getJSONObject("9.5.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 700); + } + + @Test + public void test9_5_4() { + JSONObject testResult = jsonObject.getJSONObject("9.5.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 450); + } + + @Test + public void test9_5_5() { + JSONObject testResult = jsonObject.getJSONObject("9.5.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 250); + } + + @Test + public void test9_5_6() { + JSONObject testResult = jsonObject.getJSONObject("9.5.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 150); + } + + @Test + public void test9_6_1() { + JSONObject testResult = jsonObject.getJSONObject("9.6.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 3000); + } + + @Test + public void test9_6_2() { + JSONObject testResult = jsonObject.getJSONObject("9.6.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 1500); + } + + @Test + public void test9_6_3() { + JSONObject testResult = jsonObject.getJSONObject("9.6.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 750); + } + + @Test + public void test9_6_4() { + JSONObject testResult = jsonObject.getJSONObject("9.6.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 450); + } + + @Test + public void test9_6_5() { + JSONObject testResult = jsonObject.getJSONObject("9.6.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 250); + } + + @Test + public void test9_6_6() { + JSONObject testResult = jsonObject.getJSONObject("9.6.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 200); + } + + @Test + public void test9_7_1() { + JSONObject testResult = jsonObject.getJSONObject("9.7.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 500); + } + + @Test + public void test9_7_2() { + JSONObject testResult = jsonObject.getJSONObject("9.7.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 400); + } + + @Test + public void test9_7_3() { + JSONObject testResult = jsonObject.getJSONObject("9.7.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 400); + } + + @Test + public void test9_7_4() { + JSONObject testResult = jsonObject.getJSONObject("9.7.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 400); + } + + @Test + public void test9_7_5() { + JSONObject testResult = jsonObject.getJSONObject("9.7.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 550); + } + + @Test + public void test9_7_6() { + JSONObject testResult = jsonObject.getJSONObject("9.7.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 850); + } + + @Test + public void test9_8_1() { + JSONObject testResult = jsonObject.getJSONObject("9.8.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 300); + } + + @Test + public void test9_8_2() { + JSONObject testResult = jsonObject.getJSONObject("9.8.2"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 320); + } + + @Test + public void test9_8_3() { + JSONObject testResult = jsonObject.getJSONObject("9.8.3"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 400); + } + + @Test + public void test9_8_4() { + JSONObject testResult = jsonObject.getJSONObject("9.8.4"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 400); + } + + @Test + public void test9_8_5() { + JSONObject testResult = jsonObject.getJSONObject("9.8.5"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 470); + } + + @Test + public void test9_8_6() { + JSONObject testResult = jsonObject.getJSONObject("9.8.6"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 770); + } + + @Test + public void test10_1_1() { + JSONObject testResult = jsonObject.getJSONObject("10.1.1"); + assertEquals("OK", testResult.get("behavior")); + assertEquals("OK", testResult.get("behaviorClose")); + Assume.assumeTrue("Duration: " + testResult.getInt("duration"), + testResult.getInt("duration") < 10); + } } diff --git a/src/test/java/org/java_websocket/client/AllClientTests.java b/src/test/java/org/java_websocket/client/AllClientTests.java index 9be07eefe..70006f0ac 100644 --- a/src/test/java/org/java_websocket/client/AllClientTests.java +++ b/src/test/java/org/java_websocket/client/AllClientTests.java @@ -31,12 +31,13 @@ @RunWith(Suite.class) @Suite.SuiteClasses({ - org.java_websocket.client.AttachmentTest.class, - org.java_websocket.client.SchemaCheckTest.class, - org.java_websocket.client.HeadersTest.class + org.java_websocket.client.AttachmentTest.class, + org.java_websocket.client.SchemaCheckTest.class, + org.java_websocket.client.HeadersTest.class }) /** * Start all tests for the client */ public class AllClientTests { + } diff --git a/src/test/java/org/java_websocket/client/AttachmentTest.java b/src/test/java/org/java_websocket/client/AttachmentTest.java index fcccca865..068b239d3 100644 --- a/src/test/java/org/java_websocket/client/AttachmentTest.java +++ b/src/test/java/org/java_websocket/client/AttachmentTest.java @@ -36,59 +36,59 @@ public class AttachmentTest { - @Test - public void testDefaultValue() throws URISyntaxException { - WebSocketClient client = new WebSocketClient(new URI( "ws://localhost")) { - @Override - public void onOpen( ServerHandshake handshakedata ) { + @Test + public void testDefaultValue() throws URISyntaxException { + WebSocketClient client = new WebSocketClient(new URI("ws://localhost")) { + @Override + public void onOpen(ServerHandshake handshakedata) { - } + } - @Override - public void onMessage( String message ) { + @Override + public void onMessage(String message) { - } + } - @Override - public void onClose( int code, String reason, boolean remote ) { + @Override + public void onClose(int code, String reason, boolean remote) { - } + } - @Override - public void onError( Exception ex ) { + @Override + public void onError(Exception ex) { - } - }; - assertNull(client.getAttachment()); - } + } + }; + assertNull(client.getAttachment()); + } - @Test - public void testSetter() throws URISyntaxException { - WebSocketClient client = new WebSocketClient(new URI( "ws://localhost")) { - @Override - public void onOpen( ServerHandshake handshakedata ) { + @Test + public void testSetter() throws URISyntaxException { + WebSocketClient client = new WebSocketClient(new URI("ws://localhost")) { + @Override + public void onOpen(ServerHandshake handshakedata) { - } + } - @Override - public void onMessage( String message ) { + @Override + public void onMessage(String message) { - } + } - @Override - public void onClose( int code, String reason, boolean remote ) { + @Override + public void onClose(int code, String reason, boolean remote) { - } + } - @Override - public void onError( Exception ex ) { + @Override + public void onError(Exception ex) { - } - }; - assertNull(client.getAttachment()); - client.setAttachment( client ); - assertEquals( client.getAttachment(), client ); - client.setAttachment( null ); - assertNull(client.getAttachment()); - } + } + }; + assertNull(client.getAttachment()); + client.setAttachment(client); + assertEquals(client.getAttachment(), client); + client.setAttachment(null); + assertNull(client.getAttachment()); + } } diff --git a/src/test/java/org/java_websocket/client/HeadersTest.java b/src/test/java/org/java_websocket/client/HeadersTest.java index 962e3ae15..e5d7426e9 100644 --- a/src/test/java/org/java_websocket/client/HeadersTest.java +++ b/src/test/java/org/java_websocket/client/HeadersTest.java @@ -38,96 +38,96 @@ public class HeadersTest { - @Test - public void testHttpHeaders() throws URISyntaxException { - Map httpHeaders = new HashMap(); - httpHeaders.put("Cache-Control", "only-if-cached"); - httpHeaders.put("Keep-Alive", "1000"); + @Test + public void testHttpHeaders() throws URISyntaxException { + Map httpHeaders = new HashMap(); + httpHeaders.put("Cache-Control", "only-if-cached"); + httpHeaders.put("Keep-Alive", "1000"); - WebSocketClient client = new WebSocketClient(new URI( "ws://localhost"), httpHeaders) { - @Override - public void onOpen( ServerHandshake handshakedata ) { + WebSocketClient client = new WebSocketClient(new URI("ws://localhost"), httpHeaders) { + @Override + public void onOpen(ServerHandshake handshakedata) { - } + } - @Override - public void onMessage( String message ) { + @Override + public void onMessage(String message) { - } + } - @Override - public void onClose( int code, String reason, boolean remote ) { + @Override + public void onClose(int code, String reason, boolean remote) { - } + } - @Override - public void onError( Exception ex ) { + @Override + public void onError(Exception ex) { - } - }; - - assertEquals("only-if-cached", client.removeHeader("Cache-Control")); - assertEquals("1000", client.removeHeader("Keep-Alive")); - } + } + }; - @Test - public void test_Add_RemoveHeaders() throws URISyntaxException { - Map httpHeaders = null; - WebSocketClient client = new WebSocketClient(new URI( "ws://localhost"), httpHeaders) { - @Override - public void onOpen( ServerHandshake handshakedata ) { + assertEquals("only-if-cached", client.removeHeader("Cache-Control")); + assertEquals("1000", client.removeHeader("Keep-Alive")); + } - } + @Test + public void test_Add_RemoveHeaders() throws URISyntaxException { + Map httpHeaders = null; + WebSocketClient client = new WebSocketClient(new URI("ws://localhost"), httpHeaders) { + @Override + public void onOpen(ServerHandshake handshakedata) { - @Override - public void onMessage( String message ) { + } - } + @Override + public void onMessage(String message) { - @Override - public void onClose( int code, String reason, boolean remote ) { + } - } + @Override + public void onClose(int code, String reason, boolean remote) { - @Override - public void onError( Exception ex ) { + } - } - }; - client.addHeader("Cache-Control", "only-if-cached"); - assertEquals("only-if-cached", client.removeHeader("Cache-Control")); - assertNull(client.removeHeader("Cache-Control")); + @Override + public void onError(Exception ex) { - client.addHeader("Cache-Control", "only-if-cached"); - client.clearHeaders(); - assertNull(client.removeHeader("Cache-Control")); - } + } + }; + client.addHeader("Cache-Control", "only-if-cached"); + assertEquals("only-if-cached", client.removeHeader("Cache-Control")); + assertNull(client.removeHeader("Cache-Control")); - @Test - public void testGetURI() throws URISyntaxException { - WebSocketClient client = new WebSocketClient(new URI( "ws://localhost")) { - @Override - public void onOpen( ServerHandshake handshakedata ) { + client.addHeader("Cache-Control", "only-if-cached"); + client.clearHeaders(); + assertNull(client.removeHeader("Cache-Control")); + } - } + @Test + public void testGetURI() throws URISyntaxException { + WebSocketClient client = new WebSocketClient(new URI("ws://localhost")) { + @Override + public void onOpen(ServerHandshake handshakedata) { - @Override - public void onMessage( String message ) { + } - } + @Override + public void onMessage(String message) { - @Override - public void onClose( int code, String reason, boolean remote ) { + } - } + @Override + public void onClose(int code, String reason, boolean remote) { - @Override - public void onError( Exception ex ) { + } - } - }; - String actualURI = client.getURI().getScheme() + "://" + client.getURI().getHost(); - - assertEquals("ws://localhost", actualURI); - } + @Override + public void onError(Exception ex) { + + } + }; + String actualURI = client.getURI().getScheme() + "://" + client.getURI().getHost(); + + assertEquals("ws://localhost", actualURI); + } } diff --git a/src/test/java/org/java_websocket/client/SchemaCheckTest.java b/src/test/java/org/java_websocket/client/SchemaCheckTest.java index fd829cfc4..141b27f43 100644 --- a/src/test/java/org/java_websocket/client/SchemaCheckTest.java +++ b/src/test/java/org/java_websocket/client/SchemaCheckTest.java @@ -13,15 +13,15 @@ public class SchemaCheckTest { @Test public void testSchemaCheck() throws URISyntaxException { - final String []invalidCase = { - "http://localhost:80", - "http://localhost:81", - "http://localhost", - "https://localhost:443", - "https://localhost:444", - "https://localhost", - "any://localhost", - "any://localhost:82", + final String[] invalidCase = { + "http://localhost:80", + "http://localhost:81", + "http://localhost", + "https://localhost:443", + "https://localhost:444", + "https://localhost", + "any://localhost", + "any://localhost:82", }; final Exception[] exs = new Exception[invalidCase.length]; for (int i = 0; i < invalidCase.length; i++) { @@ -51,7 +51,7 @@ public void onError(Exception ex) { for (Exception exception : exs) { assertTrue(exception instanceof IllegalArgumentException); } - final String []validCase = { + final String[] validCase = { "ws://localhost", "ws://localhost:80", "ws://localhost:81", diff --git a/src/test/java/org/java_websocket/drafts/AllDraftTests.java b/src/test/java/org/java_websocket/drafts/AllDraftTests.java index c26179d8a..39d2fa3fc 100644 --- a/src/test/java/org/java_websocket/drafts/AllDraftTests.java +++ b/src/test/java/org/java_websocket/drafts/AllDraftTests.java @@ -24,16 +24,18 @@ */ package org.java_websocket.drafts; + import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ - org.java_websocket.drafts.Draft_6455Test.class + org.java_websocket.drafts.Draft_6455Test.class }) /** * Start all tests for drafts */ public class AllDraftTests { + } diff --git a/src/test/java/org/java_websocket/drafts/Draft_6455Test.java b/src/test/java/org/java_websocket/drafts/Draft_6455Test.java index 1f8959767..a297b9bc9 100644 --- a/src/test/java/org/java_websocket/drafts/Draft_6455Test.java +++ b/src/test/java/org/java_websocket/drafts/Draft_6455Test.java @@ -49,486 +49,526 @@ public class Draft_6455Test { - HandshakeImpl1Client handshakedataProtocolExtension; - HandshakeImpl1Client handshakedataProtocol; - HandshakeImpl1Client handshakedataExtension; - HandshakeImpl1Client handshakedata; - - public Draft_6455Test() { - handshakedataProtocolExtension = new HandshakeImpl1Client(); - handshakedataProtocolExtension.put( "Upgrade", "websocket" ); - handshakedataProtocolExtension.put( "Connection", "Upgrade" ); - handshakedataProtocolExtension.put( "Sec-WebSocket-Version", "13" ); - handshakedataProtocolExtension.put( "Sec-WebSocket-Extension", "permessage-deflate" ); - handshakedataProtocolExtension.put( "Sec-WebSocket-Protocol", "chat, test" ); - handshakedataProtocol = new HandshakeImpl1Client(); - handshakedataProtocol.put( "Upgrade", "websocket" ); - handshakedataProtocol.put( "Connection", "Upgrade" ); - handshakedataProtocol.put( "Sec-WebSocket-Version", "13" ); - handshakedataProtocol.put( "Sec-WebSocket-Protocol", "chat, test" ); - handshakedataExtension = new HandshakeImpl1Client(); - handshakedataExtension.put( "Upgrade", "websocket" ); - handshakedataExtension.put( "Connection", "Upgrade" ); - handshakedataExtension.put( "Sec-WebSocket-Version", "13" ); - handshakedataExtension.put( "Sec-WebSocket-Extension", "permessage-deflate" ); - handshakedata = new HandshakeImpl1Client(); - handshakedata.put( "Upgrade", "websocket" ); - handshakedata.put( "Connection", "Upgrade" ); - handshakedata.put( "Sec-WebSocket-Version", "13" ); - } - - @Test - public void testConstructor() throws Exception { - try { - Draft_6455 draft_6455 = new Draft_6455( null, null ); - fail( "IllegalArgumentException expected" ); - } catch ( IllegalArgumentException e ) { - //Fine - } - try { - Draft_6455 draft_6455 = new Draft_6455( Collections.emptyList(), null ); - fail( "IllegalArgumentException expected" ); - } catch ( IllegalArgumentException e ) { - //Fine - } - try { - Draft_6455 draft_6455 = new Draft_6455( null, Collections.emptyList() ); - fail( "IllegalArgumentException expected" ); - } catch ( IllegalArgumentException e ) { - //Fine - } - try { - Draft_6455 draft_6455 = new Draft_6455( Collections.emptyList(), Collections.emptyList(), -1 ); - fail( "IllegalArgumentException expected" ); - } catch ( IllegalArgumentException e ) { - //Fine - } - try { - Draft_6455 draft_6455 = new Draft_6455( Collections.emptyList(), Collections.emptyList(), 0 ); - fail( "IllegalArgumentException expected" ); - } catch ( IllegalArgumentException e ) { - //Fine - } - Draft_6455 draft_6455 = new Draft_6455( Collections.emptyList(), Collections.emptyList() ); - assertEquals( 1, draft_6455.getKnownExtensions().size() ); - assertEquals( 0, draft_6455.getKnownProtocols().size() ); - } - - @Test - public void testGetExtension() throws Exception { - Draft_6455 draft_6455 = new Draft_6455(); - assertNotNull( draft_6455.getExtension() ); - assert ( draft_6455.getExtension() instanceof DefaultExtension ); - } - - @Test - public void testGetKnownExtensions() throws Exception { - Draft_6455 draft_6455 = new Draft_6455(); - assertEquals( 1, draft_6455.getKnownExtensions().size() ); - draft_6455 = new Draft_6455( new DefaultExtension() ); - assertEquals( 1, draft_6455.getKnownExtensions().size() ); - draft_6455 = new Draft_6455( new TestExtension() ); - assertEquals( 2, draft_6455.getKnownExtensions().size() ); - } - - @Test - public void testGetProtocol() throws Exception { - Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), Collections.emptyList()); - assertNull( draft_6455.getProtocol() ); - draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ); - assertNull( draft_6455.getProtocol() ); - draft_6455 = new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ); - assertNull( draft_6455.getProtocol() ); - draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ); - assertNotNull( draft_6455.getProtocol() ); - } - - @Test - public void testGetKnownProtocols() throws Exception { - Draft_6455 draft_6455 = new Draft_6455(); - assertEquals( 1, draft_6455.getKnownProtocols().size() ); - draft_6455 = new Draft_6455( Collections.emptyList(), Collections.emptyList() ); - assertEquals( 0, draft_6455.getKnownProtocols().size() ); - draft_6455 = new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ); - assertEquals( 1, draft_6455.getKnownProtocols().size() ); - ArrayList protocols = new ArrayList(); - protocols.add( new Protocol( "chat" ) ); - protocols.add( new Protocol( "test" ) ); - draft_6455 = new Draft_6455( Collections.emptyList(), protocols ); - assertEquals( 2, draft_6455.getKnownProtocols().size() ); - } - - @Test - public void testCopyInstance() throws Exception { - Draft_6455 draft_6455 = new Draft_6455( Collections.singletonList( new TestExtension() ), Collections.singletonList( new Protocol( "chat" ) ) ); - Draft_6455 draftCopy = ( Draft_6455 ) draft_6455.copyInstance(); - draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ); - assertNotEquals( draft_6455, draftCopy ); - assertEquals( draft_6455.getKnownProtocols(), draftCopy.getKnownProtocols() ); - assertEquals( draft_6455.getKnownExtensions(), draftCopy.getKnownExtensions() ); - assertNotEquals( draft_6455.getProtocol(), draftCopy.getProtocol() ); - assertNotEquals( draft_6455.getExtension(), draftCopy.getExtension() ); - } - - @Test - public void testReset() throws Exception { - Draft_6455 draft_6455 = new Draft_6455( Collections.singletonList( new TestExtension() ), 100 ); - draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ); - List extensionList = new ArrayList( draft_6455.getKnownExtensions() ); - List protocolList = new ArrayList( draft_6455.getKnownProtocols() ); - draft_6455.reset(); - //Protocol and extension should be reset - assertEquals( new DefaultExtension(), draft_6455.getExtension() ); - assertNull( draft_6455.getProtocol() ); - assertEquals( extensionList, draft_6455.getKnownExtensions() ); - assertEquals( protocolList, draft_6455.getKnownProtocols() ); - } - - @Test - public void testGetCloseHandshakeType() throws Exception { - Draft_6455 draft_6455 = new Draft_6455(); - assertEquals( CloseHandshakeType.TWOWAY, draft_6455.getCloseHandshakeType() ); - } - - @Test - public void testToString() throws Exception { - Draft_6455 draft_6455 = new Draft_6455(); - assertEquals( "Draft_6455 extension: DefaultExtension max frame size: 2147483647", draft_6455.toString() ); - draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ); - assertEquals( "Draft_6455 extension: DefaultExtension protocol: max frame size: 2147483647", draft_6455.toString() ); - draft_6455 = new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ); - assertEquals( "Draft_6455 extension: DefaultExtension max frame size: 2147483647", draft_6455.toString() ); - draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ); - assertEquals( "Draft_6455 extension: DefaultExtension protocol: chat max frame size: 2147483647", draft_6455.toString() ); - draft_6455 = new Draft_6455( Collections.singletonList( new TestExtension() ), Collections.singletonList( new Protocol( "chat" ) ) ); - assertEquals( "Draft_6455 extension: DefaultExtension max frame size: 2147483647", draft_6455.toString() ); - draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ); - assertEquals( "Draft_6455 extension: TestExtension protocol: chat max frame size: 2147483647", draft_6455.toString() ); - draft_6455 = new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ,10); - assertEquals( "Draft_6455 extension: DefaultExtension max frame size: 10", draft_6455.toString() ); - draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ); - assertEquals( "Draft_6455 extension: DefaultExtension protocol: chat max frame size: 10", draft_6455.toString() ); - } - - @Test - public void testEquals() throws Exception { - Draft draft0 = new Draft_6455(); - Draft draft1 = draft0.copyInstance(); - assertEquals( draft0, draft1 ); - Draft draft2 = new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ); - Draft draft3 = draft2.copyInstance(); - assertEquals( draft2, draft3 ); - assertEquals( draft0, draft2 ); - //unequal for draft2 due to a provided protocol - draft2.acceptHandshakeAsServer( handshakedataProtocolExtension ); - draft1.acceptHandshakeAsServer( handshakedataProtocolExtension ); - assertNotEquals( draft2, draft3 ); - assertNotEquals( draft0, draft2 ); - assertNotEquals( draft0, draft1 ); - draft2 = draft2.copyInstance(); - draft1 = draft1.copyInstance(); - //unequal for draft draft2 due to a provided protocol - draft2.acceptHandshakeAsServer( handshakedataProtocol ); - draft1.acceptHandshakeAsServer( handshakedataProtocol ); - assertNotEquals( draft2, draft3 ); - assertNotEquals( draft0, draft2 ); - assertNotEquals( draft0, draft1 ); - draft2 = draft2.copyInstance(); - draft1 = draft1.copyInstance(); - //unequal for draft draft0 due to a provided protocol (no protocol) - draft2.acceptHandshakeAsServer( handshakedataExtension ); - draft1.acceptHandshakeAsServer( handshakedataExtension ); - assertEquals( draft2, draft3 ); - assertEquals( draft0, draft2 ); - assertNotEquals( draft0, draft1 ); - draft2 = draft2.copyInstance(); - draft1 = draft1.copyInstance(); - //unequal for draft draft0 due to a provided protocol (no protocol) - draft2.acceptHandshakeAsServer( handshakedata ); - draft1.acceptHandshakeAsServer( handshakedata ); - assertEquals( draft2, draft3 ); - assertEquals( draft0, draft2 ); - assertNotEquals( draft0, draft1 ); - } - - @Test - public void testHashCode() throws Exception { - Draft draft0 = new Draft_6455(); - Draft draft1 = draft0.copyInstance(); - Draft draft2 = new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ); - Draft draft3 = draft2.copyInstance(); - assertEquals( draft2.hashCode(), draft3.hashCode() ); - assertEquals( draft0.hashCode(), draft2.hashCode() ); - assertEquals( draft0.hashCode(), draft1.hashCode() ); - //Hashcode changes for draft2 due to a provided protocol - draft2.acceptHandshakeAsServer( handshakedataProtocolExtension ); - draft1.acceptHandshakeAsServer( handshakedataProtocolExtension ); - assertNotEquals( draft2.hashCode(), draft3.hashCode() ); - assertNotEquals( draft0.hashCode(), draft2.hashCode() ); - assertEquals( draft0.hashCode(), draft1.hashCode() ); - draft2 = draft2.copyInstance(); - draft1 = draft1.copyInstance(); - //Hashcode changes for draft draft2 due to a provided protocol - draft2.acceptHandshakeAsServer( handshakedataProtocol ); - draft1.acceptHandshakeAsServer( handshakedataProtocol ); - assertNotEquals( draft2.hashCode(), draft3.hashCode() ); - assertNotEquals( draft0.hashCode(), draft2.hashCode() ); - assertEquals( draft0.hashCode(), draft1.hashCode() ); - draft2 = draft2.copyInstance(); - draft1 = draft1.copyInstance(); - //Hashcode changes for draft draft0 due to a provided protocol (no protocol) - draft2.acceptHandshakeAsServer( handshakedataExtension ); - draft1.acceptHandshakeAsServer( handshakedataExtension ); - assertEquals( draft2.hashCode(), draft3.hashCode() ); - assertEquals( draft0.hashCode(), draft2.hashCode() ); - // THIS IS A DIFFERENCE BETWEEN equals and hashcode since the hashcode of an empty string = 0 - assertEquals( draft0.hashCode(), draft1.hashCode() ); - draft2 = draft2.copyInstance(); - draft1 = draft1.copyInstance(); - //Hashcode changes for draft draft0 due to a provided protocol (no protocol) - draft2.acceptHandshakeAsServer( handshakedata ); - draft1.acceptHandshakeAsServer( handshakedata ); - assertEquals( draft2.hashCode(), draft3.hashCode() ); - assertEquals( draft0.hashCode(), draft2.hashCode() ); - // THIS IS A DIFFERENCE BETWEEN equals and hashcode since the hashcode of an empty string = 0 - assertEquals( draft0.hashCode(), draft1.hashCode() ); - } - - @Test - public void acceptHandshakeAsServer() throws Exception { - Draft_6455 draft_6455 = new Draft_6455(); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedata ) ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocol ) ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataExtension ) ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ) ); - draft_6455 = new Draft_6455( new TestExtension() ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedata ) ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocol ) ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataExtension ) ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ) ); - draft_6455 = new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ); - assertEquals( HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsServer( handshakedata ) ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocol ) ); - assertEquals( HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataExtension ) ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ) ); - ArrayList protocols = new ArrayList(); - protocols.add( new Protocol( "chat" ) ); - protocols.add( new Protocol( "" ) ); - draft_6455 = new Draft_6455( Collections.emptyList(), protocols ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedata ) ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocol ) ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataExtension ) ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ) ); - } - - @Test - public void acceptHandshakeAsClient() throws Exception { - HandshakeImpl1Server response = new HandshakeImpl1Server(); - HandshakeImpl1Client request = new HandshakeImpl1Client(); - Draft_6455 draft_6455 = new Draft_6455(); - response.put( "Upgrade", "websocket" ); - assertEquals( HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient( request, response ) ); - response.put( "Connection", "upgrade" ); - assertEquals( HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient( request, response ) ); - response.put( "Sec-WebSocket-Version", "13" ); - assertEquals( HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient( request, response ) ); - request.put( "Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==" ); - assertEquals( HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient( request, response ) ); - response.put( "Sec-WebSocket-Accept", "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=" ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient( request, response ) ); - response.put( "Sec-WebSocket-Protocol", "chat" ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient( request, response ) ); - draft_6455 = new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient( request, response ) ); - ArrayList protocols = new ArrayList(); - protocols.add( new Protocol( "" ) ); - protocols.add( new Protocol( "chat" ) ); - draft_6455 = new Draft_6455( Collections.emptyList(), protocols ); - assertEquals( HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient( request, response ) ); - draft_6455 =new Draft_6455(Collections.emptyList(), Collections.emptyList()); - assertEquals( HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient( request, response ) ); - protocols.clear(); - protocols.add( new Protocol( "chat3" ) ); - protocols.add( new Protocol( "3chat" ) ); - draft_6455 = new Draft_6455( Collections.emptyList(), protocols ); - assertEquals( HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient( request, response ) ); - } - - @Test - public void postProcessHandshakeRequestAsClient() throws Exception { - Draft_6455 draft_6455 = new Draft_6455(); - HandshakeImpl1Client request = new HandshakeImpl1Client(); - draft_6455.postProcessHandshakeRequestAsClient( request ); - assertEquals( "websocket", request.getFieldValue( "Upgrade" ) ); - assertEquals( "Upgrade", request.getFieldValue( "Connection" ) ); - assertEquals( "13", request.getFieldValue( "Sec-WebSocket-Version" ) ); - assertTrue( request.hasFieldValue( "Sec-WebSocket-Key" ) ); - assertTrue( !request.hasFieldValue( "Sec-WebSocket-Extensions" ) ); - assertTrue( !request.hasFieldValue( "Sec-WebSocket-Protocol" ) ); - ArrayList protocols = new ArrayList(); - protocols.add( new Protocol( "chat" ) ); - draft_6455 = new Draft_6455( Collections.emptyList(), protocols ); - request = new HandshakeImpl1Client(); - draft_6455.postProcessHandshakeRequestAsClient( request ); - assertTrue( !request.hasFieldValue( "Sec-WebSocket-Extensions" ) ); - assertEquals( "chat", request.getFieldValue( "Sec-WebSocket-Protocol" ) ); - protocols.add( new Protocol( "chat2" ) ); - draft_6455 = new Draft_6455( Collections.emptyList(), protocols ); - request = new HandshakeImpl1Client(); - draft_6455.postProcessHandshakeRequestAsClient( request ); - assertTrue( !request.hasFieldValue( "Sec-WebSocket-Extensions" ) ); - assertEquals( "chat, chat2", request.getFieldValue( "Sec-WebSocket-Protocol" ) ); - protocols.clear(); - protocols.add( new Protocol( "" ) ); - draft_6455 = new Draft_6455( Collections.emptyList(), protocols ); - request = new HandshakeImpl1Client(); - draft_6455.postProcessHandshakeRequestAsClient( request ); - assertTrue( !request.hasFieldValue( "Sec-WebSocket-Extensions" ) ); - assertTrue( !request.hasFieldValue( "Sec-WebSocket-Protocol" ) ); - } - - @Test - public void postProcessHandshakeResponseAsServer() throws Exception { - Draft_6455 draft_6455 = new Draft_6455(); - HandshakeImpl1Server response = new HandshakeImpl1Server(); - HandshakeImpl1Client request = new HandshakeImpl1Client(); - request.put( "Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==" ); - request.put( "Connection", "upgrade" ); - draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue( response.hasFieldValue( "Date" ) ); - assertTrue( response.hasFieldValue( "Sec-WebSocket-Accept" ) ); - assertEquals( "Web Socket Protocol Handshake", response.getHttpStatusMessage() ); - assertEquals( "TooTallNate Java-WebSocket", response.getFieldValue( "Server" ) ); - assertEquals( "upgrade", response.getFieldValue( "Connection" ) ); - assertEquals( "websocket", response.getFieldValue( "Upgrade" ) ); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Protocol" ) ); - response = new HandshakeImpl1Server(); - draft_6455.acceptHandshakeAsServer( handshakedata ); - draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Protocol" ) ); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Extensions" ) ); - response = new HandshakeImpl1Server(); - draft_6455.acceptHandshakeAsServer( handshakedataProtocol ); - draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Protocol" ) ); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Extensions" ) ); - response = new HandshakeImpl1Server(); - draft_6455.acceptHandshakeAsServer( handshakedataExtension ); - draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Protocol" ) ); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Extensions" ) ); - response = new HandshakeImpl1Server(); - draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ); - draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Protocol" ) ); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Extensions" ) ); - response = new HandshakeImpl1Server(); - draft_6455 = new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol("chat") ) ); - draft_6455.acceptHandshakeAsServer( handshakedataProtocol ); - draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertEquals( "chat", response.getFieldValue( "Sec-WebSocket-Protocol" ) ); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Extensions" ) ); - response = new HandshakeImpl1Server(); - draft_6455.reset(); - draft_6455.acceptHandshakeAsServer( handshakedataExtension ); - draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Protocol" ) ); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Extensions" ) ); - response = new HandshakeImpl1Server(); - draft_6455.reset(); - draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ); - draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertEquals( "chat", response.getFieldValue( "Sec-WebSocket-Protocol" ) ); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Extensions" ) ); - ArrayList protocols = new ArrayList(); - protocols.add( new Protocol( "test" ) ); - protocols.add( new Protocol( "chat" ) ); - draft_6455 = new Draft_6455( Collections.emptyList(), protocols ); - draft_6455.acceptHandshakeAsServer( handshakedataProtocol ); - draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertEquals( "test", response.getFieldValue( "Sec-WebSocket-Protocol" ) ); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Extensions" ) ); - response = new HandshakeImpl1Server(); - draft_6455.reset(); - draft_6455.acceptHandshakeAsServer( handshakedataExtension ); - draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Protocol" ) ); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Extensions" ) ); - response = new HandshakeImpl1Server(); - draft_6455.reset(); - draft_6455.acceptHandshakeAsServer( handshakedataProtocolExtension ); - draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertEquals( "test", response.getFieldValue( "Sec-WebSocket-Protocol" ) ); - assertTrue( !response.hasFieldValue( "Sec-WebSocket-Extensions" ) ); - - // issue #1053 : check the exception - missing Sec-WebSocket-Key - response = new HandshakeImpl1Server(); - request = new HandshakeImpl1Client(); - draft_6455.reset(); - request.put( "Connection", "upgrade" ); - - try { - draft_6455.postProcessHandshakeResponseAsServer(request, response); - fail( "InvalidHandshakeException should be thrown" ); - } catch ( InvalidHandshakeException e ) { - - } - } - - - @Test - public void createFramesBinary() throws Exception { - Draft_6455 draft_6455 = new Draft_6455(); - BinaryFrame curframe = new BinaryFrame(); - ByteBuffer test0 = ByteBuffer.wrap( "Test0".getBytes() ); - curframe.setPayload( test0 ); - curframe.setTransferemasked( false ); - List createdFrame = draft_6455.createFrames( test0, false ); - assertEquals( 1, createdFrame.size() ); - assertEquals( curframe, createdFrame.get( 0 ) ); - curframe = new BinaryFrame(); - ByteBuffer test1 = ByteBuffer.wrap( "Test1".getBytes() ); - curframe.setPayload( test1 ); - curframe.setTransferemasked( true ); - createdFrame = draft_6455.createFrames( test1, true ); - assertEquals( 1, createdFrame.size() ); - assertEquals( curframe, createdFrame.get( 0 ) ); - } - - @Test - public void createFramesText() throws Exception { - Draft_6455 draft_6455 = new Draft_6455(); - TextFrame curframe = new TextFrame(); - curframe.setPayload( ByteBuffer.wrap( Charsetfunctions.utf8Bytes( "Test0" ) ) ); - curframe.setTransferemasked( false ); - List createdFrame = draft_6455.createFrames( "Test0", false ); - assertEquals( 1, createdFrame.size() ); - assertEquals( curframe, createdFrame.get( 0 ) ); - curframe = new TextFrame(); - curframe.setPayload( ByteBuffer.wrap( Charsetfunctions.utf8Bytes( "Test0" ) ) ); - curframe.setTransferemasked( true ); - createdFrame = draft_6455.createFrames( "Test0", true ); - assertEquals( 1, createdFrame.size() ); - assertEquals( curframe, createdFrame.get( 0 ) ); - } - - - private class TestExtension extends DefaultExtension { - @Override - public int hashCode() { - return getClass().hashCode(); - } - - @Override - public IExtension copyInstance() { - return new TestExtension(); - } - - @Override - public boolean equals( Object o ) { - if( this == o ) return true; - if( o == null ) return false; - return getClass() == o.getClass(); - } - } + HandshakeImpl1Client handshakedataProtocolExtension; + HandshakeImpl1Client handshakedataProtocol; + HandshakeImpl1Client handshakedataExtension; + HandshakeImpl1Client handshakedata; + + public Draft_6455Test() { + handshakedataProtocolExtension = new HandshakeImpl1Client(); + handshakedataProtocolExtension.put("Upgrade", "websocket"); + handshakedataProtocolExtension.put("Connection", "Upgrade"); + handshakedataProtocolExtension.put("Sec-WebSocket-Version", "13"); + handshakedataProtocolExtension.put("Sec-WebSocket-Extension", "permessage-deflate"); + handshakedataProtocolExtension.put("Sec-WebSocket-Protocol", "chat, test"); + handshakedataProtocol = new HandshakeImpl1Client(); + handshakedataProtocol.put("Upgrade", "websocket"); + handshakedataProtocol.put("Connection", "Upgrade"); + handshakedataProtocol.put("Sec-WebSocket-Version", "13"); + handshakedataProtocol.put("Sec-WebSocket-Protocol", "chat, test"); + handshakedataExtension = new HandshakeImpl1Client(); + handshakedataExtension.put("Upgrade", "websocket"); + handshakedataExtension.put("Connection", "Upgrade"); + handshakedataExtension.put("Sec-WebSocket-Version", "13"); + handshakedataExtension.put("Sec-WebSocket-Extension", "permessage-deflate"); + handshakedata = new HandshakeImpl1Client(); + handshakedata.put("Upgrade", "websocket"); + handshakedata.put("Connection", "Upgrade"); + handshakedata.put("Sec-WebSocket-Version", "13"); + } + + @Test + public void testConstructor() throws Exception { + try { + Draft_6455 draft_6455 = new Draft_6455(null, null); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException e) { + //Fine + } + try { + Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), null); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException e) { + //Fine + } + try { + Draft_6455 draft_6455 = new Draft_6455(null, Collections.emptyList()); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException e) { + //Fine + } + try { + Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList(), -1); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException e) { + //Fine + } + try { + Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList(), 0); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException e) { + //Fine + } + Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList()); + assertEquals(1, draft_6455.getKnownExtensions().size()); + assertEquals(0, draft_6455.getKnownProtocols().size()); + } + + @Test + public void testGetExtension() throws Exception { + Draft_6455 draft_6455 = new Draft_6455(); + assertNotNull(draft_6455.getExtension()); + assert (draft_6455.getExtension() instanceof DefaultExtension); + } + + @Test + public void testGetKnownExtensions() throws Exception { + Draft_6455 draft_6455 = new Draft_6455(); + assertEquals(1, draft_6455.getKnownExtensions().size()); + draft_6455 = new Draft_6455(new DefaultExtension()); + assertEquals(1, draft_6455.getKnownExtensions().size()); + draft_6455 = new Draft_6455(new TestExtension()); + assertEquals(2, draft_6455.getKnownExtensions().size()); + } + + @Test + public void testGetProtocol() throws Exception { + Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList()); + assertNull(draft_6455.getProtocol()); + draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); + assertNull(draft_6455.getProtocol()); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); + assertNull(draft_6455.getProtocol()); + draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); + assertNotNull(draft_6455.getProtocol()); + } + + @Test + public void testGetKnownProtocols() throws Exception { + Draft_6455 draft_6455 = new Draft_6455(); + assertEquals(1, draft_6455.getKnownProtocols().size()); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList()); + assertEquals(0, draft_6455.getKnownProtocols().size()); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); + assertEquals(1, draft_6455.getKnownProtocols().size()); + ArrayList protocols = new ArrayList(); + protocols.add(new Protocol("chat")); + protocols.add(new Protocol("test")); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + assertEquals(2, draft_6455.getKnownProtocols().size()); + } + + @Test + public void testCopyInstance() throws Exception { + Draft_6455 draft_6455 = new Draft_6455( + Collections.singletonList(new TestExtension()), + Collections.singletonList(new Protocol("chat"))); + Draft_6455 draftCopy = (Draft_6455) draft_6455.copyInstance(); + draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); + assertNotEquals(draft_6455, draftCopy); + assertEquals(draft_6455.getKnownProtocols(), draftCopy.getKnownProtocols()); + assertEquals(draft_6455.getKnownExtensions(), draftCopy.getKnownExtensions()); + assertNotEquals(draft_6455.getProtocol(), draftCopy.getProtocol()); + assertNotEquals(draft_6455.getExtension(), draftCopy.getExtension()); + } + + @Test + public void testReset() throws Exception { + Draft_6455 draft_6455 = new Draft_6455( + Collections.singletonList(new TestExtension()), 100); + draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); + List extensionList = new ArrayList(draft_6455.getKnownExtensions()); + List protocolList = new ArrayList(draft_6455.getKnownProtocols()); + draft_6455.reset(); + //Protocol and extension should be reset + assertEquals(new DefaultExtension(), draft_6455.getExtension()); + assertNull(draft_6455.getProtocol()); + assertEquals(extensionList, draft_6455.getKnownExtensions()); + assertEquals(protocolList, draft_6455.getKnownProtocols()); + } + + @Test + public void testGetCloseHandshakeType() throws Exception { + Draft_6455 draft_6455 = new Draft_6455(); + assertEquals(CloseHandshakeType.TWOWAY, draft_6455.getCloseHandshakeType()); + } + + @Test + public void testToString() throws Exception { + Draft_6455 draft_6455 = new Draft_6455(); + assertEquals("Draft_6455 extension: DefaultExtension max frame size: 2147483647", + draft_6455.toString()); + draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); + assertEquals("Draft_6455 extension: DefaultExtension protocol: max frame size: 2147483647", + draft_6455.toString()); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); + assertEquals("Draft_6455 extension: DefaultExtension max frame size: 2147483647", + draft_6455.toString()); + draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); + assertEquals("Draft_6455 extension: DefaultExtension protocol: chat max frame size: 2147483647", + draft_6455.toString()); + draft_6455 = new Draft_6455(Collections.singletonList(new TestExtension()), + Collections.singletonList(new Protocol("chat"))); + assertEquals("Draft_6455 extension: DefaultExtension max frame size: 2147483647", + draft_6455.toString()); + draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); + assertEquals("Draft_6455 extension: TestExtension protocol: chat max frame size: 2147483647", + draft_6455.toString()); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")), 10); + assertEquals("Draft_6455 extension: DefaultExtension max frame size: 10", + draft_6455.toString()); + draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); + assertEquals("Draft_6455 extension: DefaultExtension protocol: chat max frame size: 10", + draft_6455.toString()); + } + + @Test + public void testEquals() throws Exception { + Draft draft0 = new Draft_6455(); + Draft draft1 = draft0.copyInstance(); + assertEquals(draft0, draft1); + Draft draft2 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); + Draft draft3 = draft2.copyInstance(); + assertEquals(draft2, draft3); + assertEquals(draft0, draft2); + //unequal for draft2 due to a provided protocol + draft2.acceptHandshakeAsServer(handshakedataProtocolExtension); + draft1.acceptHandshakeAsServer(handshakedataProtocolExtension); + assertNotEquals(draft2, draft3); + assertNotEquals(draft0, draft2); + assertNotEquals(draft0, draft1); + draft2 = draft2.copyInstance(); + draft1 = draft1.copyInstance(); + //unequal for draft draft2 due to a provided protocol + draft2.acceptHandshakeAsServer(handshakedataProtocol); + draft1.acceptHandshakeAsServer(handshakedataProtocol); + assertNotEquals(draft2, draft3); + assertNotEquals(draft0, draft2); + assertNotEquals(draft0, draft1); + draft2 = draft2.copyInstance(); + draft1 = draft1.copyInstance(); + //unequal for draft draft0 due to a provided protocol (no protocol) + draft2.acceptHandshakeAsServer(handshakedataExtension); + draft1.acceptHandshakeAsServer(handshakedataExtension); + assertEquals(draft2, draft3); + assertEquals(draft0, draft2); + assertNotEquals(draft0, draft1); + draft2 = draft2.copyInstance(); + draft1 = draft1.copyInstance(); + //unequal for draft draft0 due to a provided protocol (no protocol) + draft2.acceptHandshakeAsServer(handshakedata); + draft1.acceptHandshakeAsServer(handshakedata); + assertEquals(draft2, draft3); + assertEquals(draft0, draft2); + assertNotEquals(draft0, draft1); + } + + @Test + public void testHashCode() throws Exception { + Draft draft0 = new Draft_6455(); + Draft draft1 = draft0.copyInstance(); + Draft draft2 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); + Draft draft3 = draft2.copyInstance(); + assertEquals(draft2.hashCode(), draft3.hashCode()); + assertEquals(draft0.hashCode(), draft2.hashCode()); + assertEquals(draft0.hashCode(), draft1.hashCode()); + //Hashcode changes for draft2 due to a provided protocol + draft2.acceptHandshakeAsServer(handshakedataProtocolExtension); + draft1.acceptHandshakeAsServer(handshakedataProtocolExtension); + assertNotEquals(draft2.hashCode(), draft3.hashCode()); + assertNotEquals(draft0.hashCode(), draft2.hashCode()); + assertEquals(draft0.hashCode(), draft1.hashCode()); + draft2 = draft2.copyInstance(); + draft1 = draft1.copyInstance(); + //Hashcode changes for draft draft2 due to a provided protocol + draft2.acceptHandshakeAsServer(handshakedataProtocol); + draft1.acceptHandshakeAsServer(handshakedataProtocol); + assertNotEquals(draft2.hashCode(), draft3.hashCode()); + assertNotEquals(draft0.hashCode(), draft2.hashCode()); + assertEquals(draft0.hashCode(), draft1.hashCode()); + draft2 = draft2.copyInstance(); + draft1 = draft1.copyInstance(); + //Hashcode changes for draft draft0 due to a provided protocol (no protocol) + draft2.acceptHandshakeAsServer(handshakedataExtension); + draft1.acceptHandshakeAsServer(handshakedataExtension); + assertEquals(draft2.hashCode(), draft3.hashCode()); + assertEquals(draft0.hashCode(), draft2.hashCode()); + // THIS IS A DIFFERENCE BETWEEN equals and hashcode since the hashcode of an empty string = 0 + assertEquals(draft0.hashCode(), draft1.hashCode()); + draft2 = draft2.copyInstance(); + draft1 = draft1.copyInstance(); + //Hashcode changes for draft draft0 due to a provided protocol (no protocol) + draft2.acceptHandshakeAsServer(handshakedata); + draft1.acceptHandshakeAsServer(handshakedata); + assertEquals(draft2.hashCode(), draft3.hashCode()); + assertEquals(draft0.hashCode(), draft2.hashCode()); + // THIS IS A DIFFERENCE BETWEEN equals and hashcode since the hashcode of an empty string = 0 + assertEquals(draft0.hashCode(), draft1.hashCode()); + } + + @Test + public void acceptHandshakeAsServer() throws Exception { + Draft_6455 draft_6455 = new Draft_6455(); + assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer(handshakedata)); + assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer(handshakedataProtocol)); + assertEquals(HandshakeState.MATCHED, + draft_6455.acceptHandshakeAsServer(handshakedataExtension)); + assertEquals(HandshakeState.MATCHED, + draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension)); + draft_6455 = new Draft_6455(new TestExtension()); + assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer(handshakedata)); + assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer(handshakedataProtocol)); + assertEquals(HandshakeState.MATCHED, + draft_6455.acceptHandshakeAsServer(handshakedataExtension)); + assertEquals(HandshakeState.MATCHED, + draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension)); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); + assertEquals(HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsServer(handshakedata)); + assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer(handshakedataProtocol)); + assertEquals(HandshakeState.NOT_MATCHED, + draft_6455.acceptHandshakeAsServer(handshakedataExtension)); + assertEquals(HandshakeState.MATCHED, + draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension)); + ArrayList protocols = new ArrayList(); + protocols.add(new Protocol("chat")); + protocols.add(new Protocol("")); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer(handshakedata)); + assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer(handshakedataProtocol)); + assertEquals(HandshakeState.MATCHED, + draft_6455.acceptHandshakeAsServer(handshakedataExtension)); + assertEquals(HandshakeState.MATCHED, + draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension)); + } + + @Test + public void acceptHandshakeAsClient() throws Exception { + HandshakeImpl1Server response = new HandshakeImpl1Server(); + HandshakeImpl1Client request = new HandshakeImpl1Client(); + Draft_6455 draft_6455 = new Draft_6455(); + response.put("Upgrade", "websocket"); + assertEquals(HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); + response.put("Connection", "upgrade"); + assertEquals(HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); + response.put("Sec-WebSocket-Version", "13"); + assertEquals(HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); + request.put("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="); + assertEquals(HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); + response.put("Sec-WebSocket-Accept", "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="); + assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); + response.put("Sec-WebSocket-Protocol", "chat"); + assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); + assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); + ArrayList protocols = new ArrayList(); + protocols.add(new Protocol("")); + protocols.add(new Protocol("chat")); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList()); + assertEquals(HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); + protocols.clear(); + protocols.add(new Protocol("chat3")); + protocols.add(new Protocol("3chat")); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + assertEquals(HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); + } + + @Test + public void postProcessHandshakeRequestAsClient() throws Exception { + Draft_6455 draft_6455 = new Draft_6455(); + HandshakeImpl1Client request = new HandshakeImpl1Client(); + draft_6455.postProcessHandshakeRequestAsClient(request); + assertEquals("websocket", request.getFieldValue("Upgrade")); + assertEquals("Upgrade", request.getFieldValue("Connection")); + assertEquals("13", request.getFieldValue("Sec-WebSocket-Version")); + assertTrue(request.hasFieldValue("Sec-WebSocket-Key")); + assertTrue(!request.hasFieldValue("Sec-WebSocket-Extensions")); + assertTrue(!request.hasFieldValue("Sec-WebSocket-Protocol")); + ArrayList protocols = new ArrayList(); + protocols.add(new Protocol("chat")); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + request = new HandshakeImpl1Client(); + draft_6455.postProcessHandshakeRequestAsClient(request); + assertTrue(!request.hasFieldValue("Sec-WebSocket-Extensions")); + assertEquals("chat", request.getFieldValue("Sec-WebSocket-Protocol")); + protocols.add(new Protocol("chat2")); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + request = new HandshakeImpl1Client(); + draft_6455.postProcessHandshakeRequestAsClient(request); + assertTrue(!request.hasFieldValue("Sec-WebSocket-Extensions")); + assertEquals("chat, chat2", request.getFieldValue("Sec-WebSocket-Protocol")); + protocols.clear(); + protocols.add(new Protocol("")); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + request = new HandshakeImpl1Client(); + draft_6455.postProcessHandshakeRequestAsClient(request); + assertTrue(!request.hasFieldValue("Sec-WebSocket-Extensions")); + assertTrue(!request.hasFieldValue("Sec-WebSocket-Protocol")); + } + + @Test + public void postProcessHandshakeResponseAsServer() throws Exception { + Draft_6455 draft_6455 = new Draft_6455(); + HandshakeImpl1Server response = new HandshakeImpl1Server(); + HandshakeImpl1Client request = new HandshakeImpl1Client(); + request.put("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="); + request.put("Connection", "upgrade"); + draft_6455.postProcessHandshakeResponseAsServer(request, response); + assertTrue(response.hasFieldValue("Date")); + assertTrue(response.hasFieldValue("Sec-WebSocket-Accept")); + assertEquals("Web Socket Protocol Handshake", response.getHttpStatusMessage()); + assertEquals("TooTallNate Java-WebSocket", response.getFieldValue("Server")); + assertEquals("upgrade", response.getFieldValue("Connection")); + assertEquals("websocket", response.getFieldValue("Upgrade")); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); + response = new HandshakeImpl1Server(); + draft_6455.acceptHandshakeAsServer(handshakedata); + draft_6455.postProcessHandshakeResponseAsServer(request, response); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + response = new HandshakeImpl1Server(); + draft_6455.acceptHandshakeAsServer(handshakedataProtocol); + draft_6455.postProcessHandshakeResponseAsServer(request, response); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + response = new HandshakeImpl1Server(); + draft_6455.acceptHandshakeAsServer(handshakedataExtension); + draft_6455.postProcessHandshakeResponseAsServer(request, response); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + response = new HandshakeImpl1Server(); + draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); + draft_6455.postProcessHandshakeResponseAsServer(request, response); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + response = new HandshakeImpl1Server(); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); + draft_6455.acceptHandshakeAsServer(handshakedataProtocol); + draft_6455.postProcessHandshakeResponseAsServer(request, response); + assertEquals("chat", response.getFieldValue("Sec-WebSocket-Protocol")); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + response = new HandshakeImpl1Server(); + draft_6455.reset(); + draft_6455.acceptHandshakeAsServer(handshakedataExtension); + draft_6455.postProcessHandshakeResponseAsServer(request, response); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + response = new HandshakeImpl1Server(); + draft_6455.reset(); + draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); + draft_6455.postProcessHandshakeResponseAsServer(request, response); + assertEquals("chat", response.getFieldValue("Sec-WebSocket-Protocol")); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + ArrayList protocols = new ArrayList(); + protocols.add(new Protocol("test")); + protocols.add(new Protocol("chat")); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455.acceptHandshakeAsServer(handshakedataProtocol); + draft_6455.postProcessHandshakeResponseAsServer(request, response); + assertEquals("test", response.getFieldValue("Sec-WebSocket-Protocol")); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + response = new HandshakeImpl1Server(); + draft_6455.reset(); + draft_6455.acceptHandshakeAsServer(handshakedataExtension); + draft_6455.postProcessHandshakeResponseAsServer(request, response); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + response = new HandshakeImpl1Server(); + draft_6455.reset(); + draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); + draft_6455.postProcessHandshakeResponseAsServer(request, response); + assertEquals("test", response.getFieldValue("Sec-WebSocket-Protocol")); + assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + + // issue #1053 : check the exception - missing Sec-WebSocket-Key + response = new HandshakeImpl1Server(); + request = new HandshakeImpl1Client(); + draft_6455.reset(); + request.put("Connection", "upgrade"); + + try { + draft_6455.postProcessHandshakeResponseAsServer(request, response); + fail("InvalidHandshakeException should be thrown"); + } catch (InvalidHandshakeException e) { + + } + } + + + @Test + public void createFramesBinary() throws Exception { + Draft_6455 draft_6455 = new Draft_6455(); + BinaryFrame curframe = new BinaryFrame(); + ByteBuffer test0 = ByteBuffer.wrap("Test0".getBytes()); + curframe.setPayload(test0); + curframe.setTransferemasked(false); + List createdFrame = draft_6455.createFrames(test0, false); + assertEquals(1, createdFrame.size()); + assertEquals(curframe, createdFrame.get(0)); + curframe = new BinaryFrame(); + ByteBuffer test1 = ByteBuffer.wrap("Test1".getBytes()); + curframe.setPayload(test1); + curframe.setTransferemasked(true); + createdFrame = draft_6455.createFrames(test1, true); + assertEquals(1, createdFrame.size()); + assertEquals(curframe, createdFrame.get(0)); + } + + @Test + public void createFramesText() throws Exception { + Draft_6455 draft_6455 = new Draft_6455(); + TextFrame curframe = new TextFrame(); + curframe.setPayload(ByteBuffer.wrap(Charsetfunctions.utf8Bytes("Test0"))); + curframe.setTransferemasked(false); + List createdFrame = draft_6455.createFrames("Test0", false); + assertEquals(1, createdFrame.size()); + assertEquals(curframe, createdFrame.get(0)); + curframe = new TextFrame(); + curframe.setPayload(ByteBuffer.wrap(Charsetfunctions.utf8Bytes("Test0"))); + curframe.setTransferemasked(true); + createdFrame = draft_6455.createFrames("Test0", true); + assertEquals(1, createdFrame.size()); + assertEquals(curframe, createdFrame.get(0)); + } + + + private class TestExtension extends DefaultExtension { + + @Override + public int hashCode() { + return getClass().hashCode(); + } + + @Override + public IExtension copyInstance() { + return new TestExtension(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null) { + return false; + } + return getClass() == o.getClass(); + } + } } diff --git a/src/test/java/org/java_websocket/example/AutobahnClientTest.java b/src/test/java/org/java_websocket/example/AutobahnClientTest.java index 2707d7a2f..1d90685f5 100644 --- a/src/test/java/org/java_websocket/example/AutobahnClientTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnClientTest.java @@ -42,139 +42,143 @@ public class AutobahnClientTest extends WebSocketClient { - public AutobahnClientTest( Draft d , URI uri ) { - super( uri, d ); - } - /** - * @param args - */ - public static void main( String[] args ) { - System.out.println( "Testutility to profile/test this implementation using the Autobahn suit.\n" ); - System.out.println( "Type 'r ' to run a testcase. Example: r 1" ); - System.out.println( "Type 'r ' to run a testcase. Example: r 1 295" ); - System.out.println( "Type 'u' to update the test results." ); - System.out.println( "Type 'ex' to terminate the program." ); - System.out.println( "During sequences of cases the debugoutput will be turned of." ); - - System.out.println( "You can now enter in your commands:" ); - - try { - BufferedReader sysin = new BufferedReader( new InputStreamReader( System.in ) ); - - /*First of the thinks a programmer might want to change*/ - Draft d = new Draft_6455(); - String clientname = "tootallnate/websocket"; - - String protocol = "ws"; - String host = "localhost"; - int port = 9003; - - String serverlocation = protocol + "://" + host + ":" + port; - String line = ""; - AutobahnClientTest e; - URI uri = null; - String perviousline = ""; - String nextline = null; - Integer start = null; - Integer end = null; - - while ( !line.contains( "ex" ) ) { - try { - if( nextline != null ) { - line = nextline; - nextline = null; - } else { - System.out.print( ">" ); - line = sysin.readLine(); - } - if( line.equals( "l" ) ) { - line = perviousline; - } - String[] spl = line.split( " " ); - if( line.startsWith( "r" ) ) { - if( spl.length == 3 ) { - start = new Integer( spl[ 1 ] ); - end = new Integer( spl[ 2 ] ); - } - if( start != null && end != null ) { - if( start > end ) { - start = null; - end = null; - } else { - nextline = "r " + start; - start++; - if( spl.length == 3 ) - continue; - } - } - uri = URI.create( serverlocation + "/runCase?case=" + spl[ 1 ] + "&agent=" + clientname ); - - } else if( line.startsWith( "u" ) ) { - uri = URI.create( serverlocation + "/updateReports?agent=" + clientname ); - } else if( line.startsWith( "d" ) ) { - try { - d = (Draft) Class.forName( "Draft_" + spl[ 1 ] ).getConstructor().newInstance(); - } catch ( Exception ex ) { - System.out.println( "Could not change draft" + ex ); - } - } - if( uri == null ) { - System.out.println( "Do not understand the input." ); - continue; - } - System.out.println( "//////////////////////Exec: " + uri.getQuery() ); - e = new AutobahnClientTest( d, uri ); - Thread t = new Thread( e ); - t.start(); - try { - t.join(); - - } catch ( InterruptedException e1 ) { - e1.printStackTrace(); - } finally { - e.close(); - } - } catch ( ArrayIndexOutOfBoundsException e1 ) { - System.out.println( "Bad Input r 1, u 1, d 10, ex" ); - } catch ( IllegalArgumentException e2 ) { - e2.printStackTrace(); - } - - } - } catch ( ArrayIndexOutOfBoundsException e ) { - System.out.println( "Missing server uri" ); - } catch ( IllegalArgumentException e ) { - e.printStackTrace(); - System.out.println( "URI should look like ws://localhost:8887 or wss://echo.websocket.org" ); - } catch ( IOException e ) { - e.printStackTrace(); // for System.in reader - } - System.exit( 0 ); - } - - @Override - public void onMessage( String message ) { - send( message ); - } - - @Override - public void onMessage( ByteBuffer blob ) { - getConnection().send( blob ); - } - - @Override - public void onError( Exception ex ) { - System.out.println( "Error: " ); - ex.printStackTrace(); - } - - @Override - public void onOpen( ServerHandshake handshake ) { - } - - @Override - public void onClose( int code, String reason, boolean remote ) { - System.out.println( "Closed: " + code + " " + reason ); - } + public AutobahnClientTest(Draft d, URI uri) { + super(uri, d); + } + + /** + * @param args + */ + public static void main(String[] args) { + System.out + .println("Testutility to profile/test this implementation using the Autobahn suit.\n"); + System.out.println("Type 'r ' to run a testcase. Example: r 1"); + System.out.println( + "Type 'r ' to run a testcase. Example: r 1 295"); + System.out.println("Type 'u' to update the test results."); + System.out.println("Type 'ex' to terminate the program."); + System.out.println("During sequences of cases the debugoutput will be turned of."); + + System.out.println("You can now enter in your commands:"); + + try { + BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in)); + + /*First of the thinks a programmer might want to change*/ + Draft d = new Draft_6455(); + String clientname = "tootallnate/websocket"; + + String protocol = "ws"; + String host = "localhost"; + int port = 9003; + + String serverlocation = protocol + "://" + host + ":" + port; + String line = ""; + AutobahnClientTest e; + URI uri = null; + String perviousline = ""; + String nextline = null; + Integer start = null; + Integer end = null; + + while (!line.contains("ex")) { + try { + if (nextline != null) { + line = nextline; + nextline = null; + } else { + System.out.print(">"); + line = sysin.readLine(); + } + if (line.equals("l")) { + line = perviousline; + } + String[] spl = line.split(" "); + if (line.startsWith("r")) { + if (spl.length == 3) { + start = new Integer(spl[1]); + end = new Integer(spl[2]); + } + if (start != null && end != null) { + if (start > end) { + start = null; + end = null; + } else { + nextline = "r " + start; + start++; + if (spl.length == 3) { + continue; + } + } + } + uri = URI.create(serverlocation + "/runCase?case=" + spl[1] + "&agent=" + clientname); + + } else if (line.startsWith("u")) { + uri = URI.create(serverlocation + "/updateReports?agent=" + clientname); + } else if (line.startsWith("d")) { + try { + d = (Draft) Class.forName("Draft_" + spl[1]).getConstructor().newInstance(); + } catch (Exception ex) { + System.out.println("Could not change draft" + ex); + } + } + if (uri == null) { + System.out.println("Do not understand the input."); + continue; + } + System.out.println("//////////////////////Exec: " + uri.getQuery()); + e = new AutobahnClientTest(d, uri); + Thread t = new Thread(e); + t.start(); + try { + t.join(); + + } catch (InterruptedException e1) { + e1.printStackTrace(); + } finally { + e.close(); + } + } catch (ArrayIndexOutOfBoundsException e1) { + System.out.println("Bad Input r 1, u 1, d 10, ex"); + } catch (IllegalArgumentException e2) { + e2.printStackTrace(); + } + + } + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println("Missing server uri"); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + System.out.println("URI should look like ws://localhost:8887 or wss://echo.websocket.org"); + } catch (IOException e) { + e.printStackTrace(); // for System.in reader + } + System.exit(0); + } + + @Override + public void onMessage(String message) { + send(message); + } + + @Override + public void onMessage(ByteBuffer blob) { + getConnection().send(blob); + } + + @Override + public void onError(Exception ex) { + System.out.println("Error: "); + ex.printStackTrace(); + } + + @Override + public void onOpen(ServerHandshake handshake) { + } + + @Override + public void onClose(int code, String reason, boolean remote) { + System.out.println("Closed: " + code + " " + reason); + } } diff --git a/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java b/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java index 290b3f8d3..d5938eeab 100644 --- a/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java @@ -49,83 +49,85 @@ import java.util.Collections; public class AutobahnSSLServerTest extends WebSocketServer { - private static int counter = 0; - - public AutobahnSSLServerTest(int port, Draft d ) throws UnknownHostException { - super( new InetSocketAddress( port ), Collections.singletonList( d ) ); - } - - public AutobahnSSLServerTest(InetSocketAddress address, Draft d ) { - super( address, Collections.singletonList( d ) ); - } - - @Override - public void onOpen( WebSocket conn, ClientHandshake handshake ) { - counter++; - System.out.println( "///////////Opened connection number" + counter ); - } - - @Override - public void onClose( WebSocket conn, int code, String reason, boolean remote ) { - System.out.println( "closed" ); - } - - @Override - public void onError( WebSocket conn, Exception ex ) { - System.out.println( "Error:" ); - ex.printStackTrace(); - } - - @Override - public void onStart() { - System.out.println( "Server started!" ); - } - - @Override - public void onMessage( WebSocket conn, String message ) { - conn.send( message ); - } - - @Override - public void onMessage( WebSocket conn, ByteBuffer blob ) { - conn.send( blob ); - } - - public static void main( String[] args ) throws UnknownHostException { - int port; - try { - port = new Integer( args[0] ); - } catch ( Exception e ) { - System.out.println( "No port specified. Defaulting to 9003" ); - port = 9003; - } - AutobahnSSLServerTest test = new AutobahnSSLServerTest( port, new Draft_6455() ); - try { - // load up the key store - String STORETYPE = "JKS"; - String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks").toString(); - String STOREPASSWORD = "storepassword"; - String KEYPASSWORD = "keypassword"; - - KeyStore ks = KeyStore.getInstance(STORETYPE); - File kf = new File(KEYSTORE); - ks.load(new FileInputStream(kf), STOREPASSWORD.toCharArray()); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, KEYPASSWORD.toCharArray()); - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ks); - - SSLContext sslContext = null; - sslContext = SSLContext.getInstance("TLS"); - sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - test.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext)); - } catch (Exception e) { - e.printStackTrace(); - } - test.setConnectionLostTimeout( 0 ); - test.start(); - } + + private static int counter = 0; + + public AutobahnSSLServerTest(int port, Draft d) throws UnknownHostException { + super(new InetSocketAddress(port), Collections.singletonList(d)); + } + + public AutobahnSSLServerTest(InetSocketAddress address, Draft d) { + super(address, Collections.singletonList(d)); + } + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + counter++; + System.out.println("///////////Opened connection number" + counter); + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + System.out.println("closed"); + } + + @Override + public void onError(WebSocket conn, Exception ex) { + System.out.println("Error:"); + ex.printStackTrace(); + } + + @Override + public void onStart() { + System.out.println("Server started!"); + } + + @Override + public void onMessage(WebSocket conn, String message) { + conn.send(message); + } + + @Override + public void onMessage(WebSocket conn, ByteBuffer blob) { + conn.send(blob); + } + + public static void main(String[] args) throws UnknownHostException { + int port; + try { + port = new Integer(args[0]); + } catch (Exception e) { + System.out.println("No port specified. Defaulting to 9003"); + port = 9003; + } + AutobahnSSLServerTest test = new AutobahnSSLServerTest(port, new Draft_6455()); + try { + // load up the key store + String STORETYPE = "JKS"; + String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks") + .toString(); + String STOREPASSWORD = "storepassword"; + String KEYPASSWORD = "keypassword"; + + KeyStore ks = KeyStore.getInstance(STORETYPE); + File kf = new File(KEYSTORE); + ks.load(new FileInputStream(kf), STOREPASSWORD.toCharArray()); + + KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); + kmf.init(ks, KEYPASSWORD.toCharArray()); + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(ks); + + SSLContext sslContext = null; + sslContext = SSLContext.getInstance("TLS"); + sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + + test.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext)); + } catch (Exception e) { + e.printStackTrace(); + } + test.setConnectionLostTimeout(0); + test.start(); + } } diff --git a/src/test/java/org/java_websocket/example/AutobahnServerTest.java b/src/test/java/org/java_websocket/example/AutobahnServerTest.java index 20bd13e9c..77995eb96 100644 --- a/src/test/java/org/java_websocket/example/AutobahnServerTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnServerTest.java @@ -39,72 +39,73 @@ public class AutobahnServerTest extends WebSocketServer { - private static int openCounter = 0; - private static int closeCounter = 0; - private int limit = Integer.MAX_VALUE; + private static int openCounter = 0; + private static int closeCounter = 0; + private int limit = Integer.MAX_VALUE; - public AutobahnServerTest(int port, int limit, Draft d) throws UnknownHostException { - super( new InetSocketAddress( port ), Collections.singletonList( d ) ); - this.limit = limit; - } + public AutobahnServerTest(int port, int limit, Draft d) throws UnknownHostException { + super(new InetSocketAddress(port), Collections.singletonList(d)); + this.limit = limit; + } - public AutobahnServerTest( InetSocketAddress address, Draft d ) { - super( address, Collections.singletonList( d ) ); - } + public AutobahnServerTest(InetSocketAddress address, Draft d) { + super(address, Collections.singletonList(d)); + } - @Override - public void onOpen( WebSocket conn, ClientHandshake handshake ) { - openCounter++; - System.out.println( "///////////Opened connection number" + openCounter); - } + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + openCounter++; + System.out.println("///////////Opened connection number" + openCounter); + } - @Override - public void onClose( WebSocket conn, int code, String reason, boolean remote ) { - closeCounter++; - System.out.println( "closed" ); - if (closeCounter >= limit) { - System.exit(0); - } - } + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + closeCounter++; + System.out.println("closed"); + if (closeCounter >= limit) { + System.exit(0); + } + } - @Override - public void onError( WebSocket conn, Exception ex ) { - System.out.println( "Error:" ); - ex.printStackTrace(); - } + @Override + public void onError(WebSocket conn, Exception ex) { + System.out.println("Error:"); + ex.printStackTrace(); + } - @Override - public void onStart() { - System.out.println( "Server started!" ); - } + @Override + public void onStart() { + System.out.println("Server started!"); + } - @Override - public void onMessage( WebSocket conn, String message ) { - conn.send( message ); - } + @Override + public void onMessage(WebSocket conn, String message) { + conn.send(message); + } - @Override - public void onMessage( WebSocket conn, ByteBuffer blob ) { - conn.send( blob ); - } + @Override + public void onMessage(WebSocket conn, ByteBuffer blob) { + conn.send(blob); + } - public static void main( String[] args ) throws UnknownHostException { - int port, limit; - try { - port = new Integer( args[0] ); - } catch ( Exception e ) { - System.out.println( "No port specified. Defaulting to 9003" ); - port = 9003; - } - try { - limit = new Integer( args[1] ); - } catch ( Exception e ) { - System.out.println( "No limit specified. Defaulting to MaxInteger" ); - limit = Integer.MAX_VALUE; - } - AutobahnServerTest test = new AutobahnServerTest( port, limit, new Draft_6455( new PerMessageDeflateExtension()) ); - test.setConnectionLostTimeout( 0 ); - test.start(); - } + public static void main(String[] args) throws UnknownHostException { + int port, limit; + try { + port = new Integer(args[0]); + } catch (Exception e) { + System.out.println("No port specified. Defaulting to 9003"); + port = 9003; + } + try { + limit = new Integer(args[1]); + } catch (Exception e) { + System.out.println("No limit specified. Defaulting to MaxInteger"); + limit = Integer.MAX_VALUE; + } + AutobahnServerTest test = new AutobahnServerTest(port, limit, + new Draft_6455(new PerMessageDeflateExtension())); + test.setConnectionLostTimeout(0); + test.start(); + } } diff --git a/src/test/java/org/java_websocket/exceptions/AllExceptionsTests.java b/src/test/java/org/java_websocket/exceptions/AllExceptionsTests.java index b50ef409a..f0e121a8d 100644 --- a/src/test/java/org/java_websocket/exceptions/AllExceptionsTests.java +++ b/src/test/java/org/java_websocket/exceptions/AllExceptionsTests.java @@ -32,18 +32,19 @@ @RunWith(Suite.class) @Suite.SuiteClasses({ - org.java_websocket.exceptions.IncompleteExceptionTest.class, - org.java_websocket.exceptions.IncompleteHandshakeExceptionTest.class, - org.java_websocket.exceptions.InvalidDataExceptionTest.class, - org.java_websocket.exceptions.InvalidEncodingExceptionTest.class, - org.java_websocket.exceptions.InvalidFrameExceptionTest.class, - org.java_websocket.exceptions.InvalidHandshakeExceptionTest.class, - org.java_websocket.exceptions.LimitExceededExceptionTest.class, - org.java_websocket.exceptions.NotSendableExceptionTest.class, - org.java_websocket.exceptions.WebsocketNotConnectedExceptionTest.class + org.java_websocket.exceptions.IncompleteExceptionTest.class, + org.java_websocket.exceptions.IncompleteHandshakeExceptionTest.class, + org.java_websocket.exceptions.InvalidDataExceptionTest.class, + org.java_websocket.exceptions.InvalidEncodingExceptionTest.class, + org.java_websocket.exceptions.InvalidFrameExceptionTest.class, + org.java_websocket.exceptions.InvalidHandshakeExceptionTest.class, + org.java_websocket.exceptions.LimitExceededExceptionTest.class, + org.java_websocket.exceptions.NotSendableExceptionTest.class, + org.java_websocket.exceptions.WebsocketNotConnectedExceptionTest.class }) /** * Start all tests for the exceptions */ public class AllExceptionsTests { + } diff --git a/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java b/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java index 4a643fb13..439531d3b 100644 --- a/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java @@ -37,9 +37,9 @@ */ public class IncompleteExceptionTest { - @Test - public void testConstructor() { - IncompleteException incompleteException = new IncompleteException(42); - assertEquals("The argument should be set", 42, incompleteException.getPreferredSize()); - } + @Test + public void testConstructor() { + IncompleteException incompleteException = new IncompleteException(42); + assertEquals("The argument should be set", 42, incompleteException.getPreferredSize()); + } } diff --git a/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java b/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java index a0bf81048..30352a24f 100644 --- a/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java @@ -34,11 +34,12 @@ */ public class IncompleteHandshakeExceptionTest { - @Test - public void testConstructor() { - IncompleteHandshakeException incompleteHandshakeException = new IncompleteHandshakeException(42); - assertEquals("The argument should be set", 42, incompleteHandshakeException.getPreferredSize()); - incompleteHandshakeException = new IncompleteHandshakeException(); - assertEquals("The default has to be 0", 0, incompleteHandshakeException.getPreferredSize()); - } + @Test + public void testConstructor() { + IncompleteHandshakeException incompleteHandshakeException = new IncompleteHandshakeException( + 42); + assertEquals("The argument should be set", 42, incompleteHandshakeException.getPreferredSize()); + incompleteHandshakeException = new IncompleteHandshakeException(); + assertEquals("The default has to be 0", 0, incompleteHandshakeException.getPreferredSize()); + } } diff --git a/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java index 04e7693b3..45bf81e5f 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java @@ -35,20 +35,22 @@ */ public class InvalidDataExceptionTest { - @Test - public void testConstructor() { - InvalidDataException invalidDataException = new InvalidDataException(42); - assertEquals("The close code has to be the argument", 42, invalidDataException.getCloseCode()); - invalidDataException = new InvalidDataException(42, "Message"); - assertEquals("The close code has to be the argument", 42, invalidDataException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", invalidDataException.getMessage()); - Exception e = new Exception(); - invalidDataException = new InvalidDataException(42, "Message", e); - assertEquals("The close code has to be the argument", 42, invalidDataException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", invalidDataException.getMessage()); - assertEquals("The throwable has to be the argument", e, invalidDataException.getCause()); - invalidDataException = new InvalidDataException(42, e); - assertEquals("The close code has to be the argument", 42, invalidDataException.getCloseCode()); - assertEquals("The throwable has to be the argument", e, invalidDataException.getCause()); - } + @Test + public void testConstructor() { + InvalidDataException invalidDataException = new InvalidDataException(42); + assertEquals("The close code has to be the argument", 42, invalidDataException.getCloseCode()); + invalidDataException = new InvalidDataException(42, "Message"); + assertEquals("The close code has to be the argument", 42, invalidDataException.getCloseCode()); + assertEquals("The message has to be the argument", "Message", + invalidDataException.getMessage()); + Exception e = new Exception(); + invalidDataException = new InvalidDataException(42, "Message", e); + assertEquals("The close code has to be the argument", 42, invalidDataException.getCloseCode()); + assertEquals("The message has to be the argument", "Message", + invalidDataException.getMessage()); + assertEquals("The throwable has to be the argument", e, invalidDataException.getCause()); + invalidDataException = new InvalidDataException(42, e); + assertEquals("The close code has to be the argument", 42, invalidDataException.getCloseCode()); + assertEquals("The throwable has to be the argument", e, invalidDataException.getCause()); + } } diff --git a/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java index 903c81ee7..144b4a4da 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java @@ -37,16 +37,18 @@ */ public class InvalidEncodingExceptionTest { - @Test - public void testConstructor() { - UnsupportedEncodingException unsupportedEncodingException = new UnsupportedEncodingException(); - InvalidEncodingException invalidEncodingException = new InvalidEncodingException(unsupportedEncodingException); - assertEquals("The argument has to be the provided exception", unsupportedEncodingException, invalidEncodingException.getEncodingException()); - try { - invalidEncodingException = new InvalidEncodingException(null); - fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException e) { - //Null is not allowed - } + @Test + public void testConstructor() { + UnsupportedEncodingException unsupportedEncodingException = new UnsupportedEncodingException(); + InvalidEncodingException invalidEncodingException = new InvalidEncodingException( + unsupportedEncodingException); + assertEquals("The argument has to be the provided exception", unsupportedEncodingException, + invalidEncodingException.getEncodingException()); + try { + invalidEncodingException = new InvalidEncodingException(null); + fail("IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException e) { + //Null is not allowed } + } } diff --git a/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java index f6e26878c..5337e333b 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java @@ -35,26 +35,33 @@ */ public class InvalidFrameExceptionTest { - @Test - public void testConstructor() { - InvalidFrameException invalidFrameException = new InvalidFrameException(); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, invalidFrameException.getCloseCode()); - invalidFrameException = new InvalidFrameException("Message"); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, invalidFrameException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", invalidFrameException.getMessage()); - Exception e = new Exception(); - invalidFrameException = new InvalidFrameException("Message", e); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, invalidFrameException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", invalidFrameException.getMessage()); - assertEquals("The throwable has to be the argument", e, invalidFrameException.getCause()); - invalidFrameException = new InvalidFrameException(e); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, invalidFrameException.getCloseCode()); - assertEquals("The throwable has to be the argument", e, invalidFrameException.getCause()); - } + @Test + public void testConstructor() { + InvalidFrameException invalidFrameException = new InvalidFrameException(); + assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, + invalidFrameException.getCloseCode()); + invalidFrameException = new InvalidFrameException("Message"); + assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, + invalidFrameException.getCloseCode()); + assertEquals("The message has to be the argument", "Message", + invalidFrameException.getMessage()); + Exception e = new Exception(); + invalidFrameException = new InvalidFrameException("Message", e); + assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, + invalidFrameException.getCloseCode()); + assertEquals("The message has to be the argument", "Message", + invalidFrameException.getMessage()); + assertEquals("The throwable has to be the argument", e, invalidFrameException.getCause()); + invalidFrameException = new InvalidFrameException(e); + assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, + invalidFrameException.getCloseCode()); + assertEquals("The throwable has to be the argument", e, invalidFrameException.getCause()); + } - @Test - public void testExtends() { - InvalidFrameException invalidFrameException = new InvalidFrameException(); - assertEquals("InvalidFrameException must extend InvalidDataException", true, invalidFrameException instanceof InvalidDataException); - } + @Test + public void testExtends() { + InvalidFrameException invalidFrameException = new InvalidFrameException(); + assertEquals("InvalidFrameException must extend InvalidDataException", true, + invalidFrameException instanceof InvalidDataException); + } } diff --git a/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java index 9e15e699f..3832e77b5 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java @@ -35,27 +35,34 @@ */ public class InvalidHandshakeExceptionTest { - @Test - public void testConstructor() { - InvalidHandshakeException invalidHandshakeException = new InvalidHandshakeException(); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, invalidHandshakeException.getCloseCode()); - invalidHandshakeException = new InvalidHandshakeException("Message"); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, invalidHandshakeException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", invalidHandshakeException.getMessage()); - Exception e = new Exception(); - invalidHandshakeException = new InvalidHandshakeException("Message", e); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, invalidHandshakeException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", invalidHandshakeException.getMessage()); - assertEquals("The throwable has to be the argument", e, invalidHandshakeException.getCause()); - invalidHandshakeException = new InvalidHandshakeException(e); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, invalidHandshakeException.getCloseCode()); - assertEquals("The throwable has to be the argument", e, invalidHandshakeException.getCause()); + @Test + public void testConstructor() { + InvalidHandshakeException invalidHandshakeException = new InvalidHandshakeException(); + assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, + invalidHandshakeException.getCloseCode()); + invalidHandshakeException = new InvalidHandshakeException("Message"); + assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, + invalidHandshakeException.getCloseCode()); + assertEquals("The message has to be the argument", "Message", + invalidHandshakeException.getMessage()); + Exception e = new Exception(); + invalidHandshakeException = new InvalidHandshakeException("Message", e); + assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, + invalidHandshakeException.getCloseCode()); + assertEquals("The message has to be the argument", "Message", + invalidHandshakeException.getMessage()); + assertEquals("The throwable has to be the argument", e, invalidHandshakeException.getCause()); + invalidHandshakeException = new InvalidHandshakeException(e); + assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, + invalidHandshakeException.getCloseCode()); + assertEquals("The throwable has to be the argument", e, invalidHandshakeException.getCause()); - } + } - @Test - public void testExtends() { - InvalidHandshakeException invalidHandshakeException = new InvalidHandshakeException(); - assertEquals("InvalidHandshakeException must extend InvalidDataException", true, invalidHandshakeException instanceof InvalidDataException); - } + @Test + public void testExtends() { + InvalidHandshakeException invalidHandshakeException = new InvalidHandshakeException(); + assertEquals("InvalidHandshakeException must extend InvalidDataException", true, + invalidHandshakeException instanceof InvalidDataException); + } } diff --git a/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java b/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java index b8bde9f09..a5ef5c4a8 100644 --- a/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java @@ -39,19 +39,23 @@ */ public class LimitExceededExceptionTest { - @Test - public void testConstructor() { - LimitExceededException limitExceededException = new LimitExceededException(); - assertEquals("The close code has to be TOOBIG", CloseFrame.TOOBIG, limitExceededException.getCloseCode()); - assertEquals("The message has to be empty", null, limitExceededException.getMessage()); - limitExceededException = new LimitExceededException("Message"); - assertEquals("The close code has to be TOOBIG", CloseFrame.TOOBIG, limitExceededException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", limitExceededException.getMessage()); - } + @Test + public void testConstructor() { + LimitExceededException limitExceededException = new LimitExceededException(); + assertEquals("The close code has to be TOOBIG", CloseFrame.TOOBIG, + limitExceededException.getCloseCode()); + assertEquals("The message has to be empty", null, limitExceededException.getMessage()); + limitExceededException = new LimitExceededException("Message"); + assertEquals("The close code has to be TOOBIG", CloseFrame.TOOBIG, + limitExceededException.getCloseCode()); + assertEquals("The message has to be the argument", "Message", + limitExceededException.getMessage()); + } - @Test - public void testExtends() { - LimitExceededException limitExceededException = new LimitExceededException(); - assertEquals("LimitExceededException must extend InvalidDataException", true, limitExceededException instanceof InvalidDataException); - } + @Test + public void testExtends() { + LimitExceededException limitExceededException = new LimitExceededException(); + assertEquals("LimitExceededException must extend InvalidDataException", true, + limitExceededException instanceof InvalidDataException); + } } diff --git a/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java b/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java index e674eab01..4d5087129 100644 --- a/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java @@ -35,15 +35,17 @@ */ public class NotSendableExceptionTest { - @Test - public void testConstructor() { - NotSendableException notSendableException = new NotSendableException("Message"); - assertEquals("The message has to be the argument", "Message", notSendableException.getMessage()); - Exception e = new Exception(); - notSendableException = new NotSendableException(e); - assertEquals("The throwable has to be the argument", e, notSendableException.getCause()); - notSendableException = new NotSendableException("Message", e); - assertEquals("The message has to be the argument", "Message", notSendableException.getMessage()); - assertEquals("The throwable has to be the argument", e,notSendableException.getCause()); - } + @Test + public void testConstructor() { + NotSendableException notSendableException = new NotSendableException("Message"); + assertEquals("The message has to be the argument", "Message", + notSendableException.getMessage()); + Exception e = new Exception(); + notSendableException = new NotSendableException(e); + assertEquals("The throwable has to be the argument", e, notSendableException.getCause()); + notSendableException = new NotSendableException("Message", e); + assertEquals("The message has to be the argument", "Message", + notSendableException.getMessage()); + assertEquals("The throwable has to be the argument", e, notSendableException.getCause()); + } } diff --git a/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java b/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java index f7f3b76ad..e1c681da1 100644 --- a/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java @@ -36,9 +36,9 @@ */ public class WebsocketNotConnectedExceptionTest { - @Test - public void testConstructor() { - WebsocketNotConnectedException websocketNotConnectedException = new WebsocketNotConnectedException(); - assertNotNull(websocketNotConnectedException); - } + @Test + public void testConstructor() { + WebsocketNotConnectedException websocketNotConnectedException = new WebsocketNotConnectedException(); + assertNotNull(websocketNotConnectedException); + } } diff --git a/src/test/java/org/java_websocket/extensions/AllExtensionTests.java b/src/test/java/org/java_websocket/extensions/AllExtensionTests.java index 47fe67498..3cbf552e6 100644 --- a/src/test/java/org/java_websocket/extensions/AllExtensionTests.java +++ b/src/test/java/org/java_websocket/extensions/AllExtensionTests.java @@ -24,17 +24,19 @@ */ package org.java_websocket.extensions; + import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ - org.java_websocket.extensions.DefaultExtensionTest.class, - org.java_websocket.extensions.CompressionExtensionTest.class + org.java_websocket.extensions.DefaultExtensionTest.class, + org.java_websocket.extensions.CompressionExtensionTest.class }) /** * Start all tests for extensions */ public class AllExtensionTests { + } diff --git a/src/test/java/org/java_websocket/extensions/CompressionExtensionTest.java b/src/test/java/org/java_websocket/extensions/CompressionExtensionTest.java index efd3bec67..d2c468936 100644 --- a/src/test/java/org/java_websocket/extensions/CompressionExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/CompressionExtensionTest.java @@ -9,68 +9,69 @@ public class CompressionExtensionTest { - @Test - public void testIsFrameValid() { - CustomCompressionExtension customCompressionExtension = new CustomCompressionExtension(); - TextFrame textFrame = new TextFrame(); - try { - customCompressionExtension.isFrameValid( textFrame ); - } catch ( Exception e ) { - fail( "This frame is valid" ); - } - textFrame.setRSV1( true ); - try { - customCompressionExtension.isFrameValid( textFrame ); - } catch ( Exception e ) { - fail( "This frame is valid" ); - } - textFrame.setRSV1( false ); - textFrame.setRSV2( true ); - try { - customCompressionExtension.isFrameValid( textFrame ); - fail( "This frame is not valid" ); - } catch ( Exception e ) { - // - } - textFrame.setRSV2( false ); - textFrame.setRSV3( true ); - try { - customCompressionExtension.isFrameValid( textFrame ); - fail( "This frame is not valid" ); - } catch ( Exception e ) { - // - } - PingFrame pingFrame = new PingFrame(); - try { - customCompressionExtension.isFrameValid( pingFrame ); - } catch ( Exception e ) { - fail( "This frame is valid" ); - } - pingFrame.setRSV1( true ); - try { - customCompressionExtension.isFrameValid( pingFrame ); - fail( "This frame is not valid" ); - } catch ( Exception e ) { - // - } - pingFrame.setRSV1( false ); - pingFrame.setRSV2( true ); - try { - customCompressionExtension.isFrameValid( pingFrame ); - fail( "This frame is not valid" ); - } catch ( Exception e ) { - // - } - pingFrame.setRSV2( false ); - pingFrame.setRSV3( true ); - try { - customCompressionExtension.isFrameValid( pingFrame ); - fail( "This frame is not valid" ); - } catch ( Exception e ) { - // - } + @Test + public void testIsFrameValid() { + CustomCompressionExtension customCompressionExtension = new CustomCompressionExtension(); + TextFrame textFrame = new TextFrame(); + try { + customCompressionExtension.isFrameValid(textFrame); + } catch (Exception e) { + fail("This frame is valid"); } - - private static class CustomCompressionExtension extends CompressionExtension { + textFrame.setRSV1(true); + try { + customCompressionExtension.isFrameValid(textFrame); + } catch (Exception e) { + fail("This frame is valid"); + } + textFrame.setRSV1(false); + textFrame.setRSV2(true); + try { + customCompressionExtension.isFrameValid(textFrame); + fail("This frame is not valid"); + } catch (Exception e) { + // + } + textFrame.setRSV2(false); + textFrame.setRSV3(true); + try { + customCompressionExtension.isFrameValid(textFrame); + fail("This frame is not valid"); + } catch (Exception e) { + // + } + PingFrame pingFrame = new PingFrame(); + try { + customCompressionExtension.isFrameValid(pingFrame); + } catch (Exception e) { + fail("This frame is valid"); + } + pingFrame.setRSV1(true); + try { + customCompressionExtension.isFrameValid(pingFrame); + fail("This frame is not valid"); + } catch (Exception e) { + // } + pingFrame.setRSV1(false); + pingFrame.setRSV2(true); + try { + customCompressionExtension.isFrameValid(pingFrame); + fail("This frame is not valid"); + } catch (Exception e) { + // + } + pingFrame.setRSV2(false); + pingFrame.setRSV3(true); + try { + customCompressionExtension.isFrameValid(pingFrame); + fail("This frame is not valid"); + } catch (Exception e) { + // + } + } + + private static class CustomCompressionExtension extends CompressionExtension { + + } } diff --git a/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java b/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java index d409d2a82..7aa66f7f4 100644 --- a/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java @@ -34,117 +34,118 @@ import static org.junit.Assert.*; public class DefaultExtensionTest { - @Test - public void testDecodeFrame() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - BinaryFrame binaryFrame = new BinaryFrame(); - binaryFrame.setPayload( ByteBuffer.wrap( "test".getBytes() ) ); - defaultExtension.decodeFrame( binaryFrame ); - assertEquals( ByteBuffer.wrap( "test".getBytes() ), binaryFrame.getPayloadData() ); - } - - @Test - public void testEncodeFrame() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - BinaryFrame binaryFrame = new BinaryFrame(); - binaryFrame.setPayload( ByteBuffer.wrap( "test".getBytes() ) ); - defaultExtension.encodeFrame( binaryFrame ); - assertEquals( ByteBuffer.wrap( "test".getBytes() ), binaryFrame.getPayloadData() ); - } - - @Test - public void testAcceptProvidedExtensionAsServer() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - assertTrue( defaultExtension.acceptProvidedExtensionAsServer( "Test" ) ); - assertTrue( defaultExtension.acceptProvidedExtensionAsServer( "" ) ); - assertTrue( defaultExtension.acceptProvidedExtensionAsServer( "Test, ASDC, as, ad" ) ); - assertTrue( defaultExtension.acceptProvidedExtensionAsServer( "ASDC, as,ad" ) ); - assertTrue( defaultExtension.acceptProvidedExtensionAsServer( "permessage-deflate" ) ); - } - - @Test - public void testAcceptProvidedExtensionAsClient() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - assertTrue( defaultExtension.acceptProvidedExtensionAsClient( "Test" ) ); - assertTrue( defaultExtension.acceptProvidedExtensionAsClient( "" ) ); - assertTrue( defaultExtension.acceptProvidedExtensionAsClient( "Test, ASDC, as, ad" ) ); - assertTrue( defaultExtension.acceptProvidedExtensionAsClient( "ASDC, as,ad" ) ); - assertTrue( defaultExtension.acceptProvidedExtensionAsClient( "permessage-deflate" ) ); - } - - @Test - public void testIsFrameValid() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - TextFrame textFrame = new TextFrame(); - try { - defaultExtension.isFrameValid( textFrame ); - } catch ( Exception e ) { - fail( "This frame is valid" ); - } - textFrame.setRSV1( true ); - try { - defaultExtension.isFrameValid( textFrame ); - fail( "This frame is not valid" ); - } catch ( Exception e ) { - // - } - textFrame.setRSV1( false ); - textFrame.setRSV2( true ); - try { - defaultExtension.isFrameValid( textFrame ); - fail( "This frame is not valid" ); - } catch ( Exception e ) { - // - } - textFrame.setRSV2( false ); - textFrame.setRSV3( true ); - try { - defaultExtension.isFrameValid( textFrame ); - fail( "This frame is not valid" ); - } catch ( Exception e ) { - // - } - } - - @Test - public void testGetProvidedExtensionAsClient() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - assertEquals( "", defaultExtension.getProvidedExtensionAsClient() ); - } - - @Test - public void testGetProvidedExtensionAsServer() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - assertEquals( "", defaultExtension.getProvidedExtensionAsServer() ); - } - - @Test - public void testCopyInstance() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - IExtension extensionCopy = defaultExtension.copyInstance(); - assertEquals( defaultExtension, extensionCopy ); - } - - @Test - public void testToString() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - assertEquals( "DefaultExtension", defaultExtension.toString() ); - } - - @Test - public void testHashCode() throws Exception { - DefaultExtension defaultExtension0 = new DefaultExtension(); - DefaultExtension defaultExtension1 = new DefaultExtension(); - assertEquals( defaultExtension0.hashCode(), defaultExtension1.hashCode() ); - } - - @Test - public void testEquals() throws Exception { - DefaultExtension defaultExtension0 = new DefaultExtension(); - DefaultExtension defaultExtension1 = new DefaultExtension(); - assertEquals( defaultExtension0, defaultExtension1 ); - assertFalse( defaultExtension0.equals(null) ); - assertFalse( defaultExtension0.equals(new Object()) ); - } + + @Test + public void testDecodeFrame() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + BinaryFrame binaryFrame = new BinaryFrame(); + binaryFrame.setPayload(ByteBuffer.wrap("test".getBytes())); + defaultExtension.decodeFrame(binaryFrame); + assertEquals(ByteBuffer.wrap("test".getBytes()), binaryFrame.getPayloadData()); + } + + @Test + public void testEncodeFrame() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + BinaryFrame binaryFrame = new BinaryFrame(); + binaryFrame.setPayload(ByteBuffer.wrap("test".getBytes())); + defaultExtension.encodeFrame(binaryFrame); + assertEquals(ByteBuffer.wrap("test".getBytes()), binaryFrame.getPayloadData()); + } + + @Test + public void testAcceptProvidedExtensionAsServer() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + assertTrue(defaultExtension.acceptProvidedExtensionAsServer("Test")); + assertTrue(defaultExtension.acceptProvidedExtensionAsServer("")); + assertTrue(defaultExtension.acceptProvidedExtensionAsServer("Test, ASDC, as, ad")); + assertTrue(defaultExtension.acceptProvidedExtensionAsServer("ASDC, as,ad")); + assertTrue(defaultExtension.acceptProvidedExtensionAsServer("permessage-deflate")); + } + + @Test + public void testAcceptProvidedExtensionAsClient() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + assertTrue(defaultExtension.acceptProvidedExtensionAsClient("Test")); + assertTrue(defaultExtension.acceptProvidedExtensionAsClient("")); + assertTrue(defaultExtension.acceptProvidedExtensionAsClient("Test, ASDC, as, ad")); + assertTrue(defaultExtension.acceptProvidedExtensionAsClient("ASDC, as,ad")); + assertTrue(defaultExtension.acceptProvidedExtensionAsClient("permessage-deflate")); + } + + @Test + public void testIsFrameValid() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + TextFrame textFrame = new TextFrame(); + try { + defaultExtension.isFrameValid(textFrame); + } catch (Exception e) { + fail("This frame is valid"); + } + textFrame.setRSV1(true); + try { + defaultExtension.isFrameValid(textFrame); + fail("This frame is not valid"); + } catch (Exception e) { + // + } + textFrame.setRSV1(false); + textFrame.setRSV2(true); + try { + defaultExtension.isFrameValid(textFrame); + fail("This frame is not valid"); + } catch (Exception e) { + // + } + textFrame.setRSV2(false); + textFrame.setRSV3(true); + try { + defaultExtension.isFrameValid(textFrame); + fail("This frame is not valid"); + } catch (Exception e) { + // + } + } + + @Test + public void testGetProvidedExtensionAsClient() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + assertEquals("", defaultExtension.getProvidedExtensionAsClient()); + } + + @Test + public void testGetProvidedExtensionAsServer() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + assertEquals("", defaultExtension.getProvidedExtensionAsServer()); + } + + @Test + public void testCopyInstance() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + IExtension extensionCopy = defaultExtension.copyInstance(); + assertEquals(defaultExtension, extensionCopy); + } + + @Test + public void testToString() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + assertEquals("DefaultExtension", defaultExtension.toString()); + } + + @Test + public void testHashCode() throws Exception { + DefaultExtension defaultExtension0 = new DefaultExtension(); + DefaultExtension defaultExtension1 = new DefaultExtension(); + assertEquals(defaultExtension0.hashCode(), defaultExtension1.hashCode()); + } + + @Test + public void testEquals() throws Exception { + DefaultExtension defaultExtension0 = new DefaultExtension(); + DefaultExtension defaultExtension1 = new DefaultExtension(); + assertEquals(defaultExtension0, defaultExtension1); + assertFalse(defaultExtension0.equals(null)); + assertFalse(defaultExtension0.equals(new Object())); + } } \ No newline at end of file diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index 9906cfa52..dbbd63497 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -18,168 +18,172 @@ public class PerMessageDeflateExtensionTest { - @Test - public void testDecodeFrame() throws InvalidDataException { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - String str = "This is a highly compressable text" - + "This is a highly compressable text" - + "This is a highly compressable text" - + "This is a highly compressable text" - + "This is a highly compressable text"; - byte[] message = str.getBytes(); - TextFrame frame = new TextFrame(); - frame.setPayload(ByteBuffer.wrap(message)); - deflateExtension.encodeFrame(frame); - deflateExtension.decodeFrame(frame); - assertArrayEquals(message, frame.getPayloadData().array()); - } - - @Test - public void testEncodeFrame() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - String str = "This is a highly compressable text" - + "This is a highly compressable text" - + "This is a highly compressable text" - + "This is a highly compressable text" - + "This is a highly compressable text"; - byte[] message = str.getBytes(); - TextFrame frame = new TextFrame(); - frame.setPayload(ByteBuffer.wrap(message)); - deflateExtension.encodeFrame(frame); - assertTrue(message.length > frame.getPayloadData().array().length); - } - - @Test - public void testAcceptProvidedExtensionAsServer() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertTrue(deflateExtension.acceptProvidedExtensionAsServer("permessage-deflate")); - assertTrue(deflateExtension.acceptProvidedExtensionAsServer("some-other-extension, permessage-deflate")); - assertFalse(deflateExtension.acceptProvidedExtensionAsServer("wrong-permessage-deflate")); - } - - @Test - public void testAcceptProvidedExtensionAsClient() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertTrue(deflateExtension.acceptProvidedExtensionAsClient("permessage-deflate")); - assertTrue(deflateExtension.acceptProvidedExtensionAsClient("some-other-extension, permessage-deflate")); - assertFalse(deflateExtension.acceptProvidedExtensionAsClient("wrong-permessage-deflate")); - } - - @Test - public void testIsFrameValid() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - TextFrame frame = new TextFrame(); - try { - deflateExtension.isFrameValid(frame); - fail("Frame not valid. RSV1 must be set."); - } catch (Exception e) { - // - } - frame.setRSV1(true); - try { - deflateExtension.isFrameValid(frame); - } catch (Exception e) { - fail("Frame is valid."); - } - frame.setRSV2(true); - try { - deflateExtension.isFrameValid(frame); - fail("Only RSV1 bit must be set."); - } catch (Exception e) { - // - } - ContinuousFrame contFrame = new ContinuousFrame(); - contFrame.setRSV1(true); - try { - deflateExtension.isFrameValid(contFrame); - fail("RSV1 must only be set for first fragments.Continuous frames can't have RSV1 bit set."); - } catch (Exception e) { - // - } - contFrame.setRSV1(false); - try { - deflateExtension.isFrameValid(contFrame); - } catch (Exception e) { - fail("Continuous frame is valid."); - } - } - - @Test - public void testGetProvidedExtensionAsClient() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertEquals( "permessage-deflate; server_no_context_takeover; client_no_context_takeover", - deflateExtension.getProvidedExtensionAsClient() ); - } - - @Test - public void testGetProvidedExtensionAsServer() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertEquals( "permessage-deflate; server_no_context_takeover", - deflateExtension.getProvidedExtensionAsServer() ); - } - - @Test - public void testToString() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertEquals( "PerMessageDeflateExtension", deflateExtension.toString() ); - } - - @Test - public void testIsServerNoContextTakeover() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertTrue(deflateExtension.isServerNoContextTakeover()); - } - - @Test - public void testSetServerNoContextTakeover() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - deflateExtension.setServerNoContextTakeover(false); - assertFalse(deflateExtension.isServerNoContextTakeover()); - } - - @Test - public void testIsClientNoContextTakeover() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertFalse(deflateExtension.isClientNoContextTakeover()); - } - - @Test - public void testSetClientNoContextTakeover() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - deflateExtension.setClientNoContextTakeover(true); - assertTrue(deflateExtension.isClientNoContextTakeover()); - } - - @Test - public void testCopyInstance() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - IExtension newDeflateExtension = deflateExtension.copyInstance(); - assertEquals(deflateExtension.toString(), newDeflateExtension.toString()); - } - - @Test - public void testGetInflater() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertEquals(deflateExtension.getInflater().getRemaining(), new Inflater(true).getRemaining()); - } - - @Test - public void testSetInflater() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - deflateExtension.setInflater(new Inflater(false)); - assertEquals(deflateExtension.getInflater().getRemaining(), new Inflater(false).getRemaining()); - } - - @Test - public void testGetDeflater() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertEquals(deflateExtension.getDeflater().finished(), new Deflater(Deflater.DEFAULT_COMPRESSION, true).finished()); - } - - @Test - public void testSetDeflater() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - deflateExtension.setDeflater(new Deflater(Deflater.DEFAULT_COMPRESSION, false)); - assertEquals(deflateExtension.getDeflater().finished(),new Deflater(Deflater.DEFAULT_COMPRESSION, false).finished()); - } + @Test + public void testDecodeFrame() throws InvalidDataException { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + String str = "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text"; + byte[] message = str.getBytes(); + TextFrame frame = new TextFrame(); + frame.setPayload(ByteBuffer.wrap(message)); + deflateExtension.encodeFrame(frame); + deflateExtension.decodeFrame(frame); + assertArrayEquals(message, frame.getPayloadData().array()); + } + + @Test + public void testEncodeFrame() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + String str = "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text"; + byte[] message = str.getBytes(); + TextFrame frame = new TextFrame(); + frame.setPayload(ByteBuffer.wrap(message)); + deflateExtension.encodeFrame(frame); + assertTrue(message.length > frame.getPayloadData().array().length); + } + + @Test + public void testAcceptProvidedExtensionAsServer() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertTrue(deflateExtension.acceptProvidedExtensionAsServer("permessage-deflate")); + assertTrue(deflateExtension + .acceptProvidedExtensionAsServer("some-other-extension, permessage-deflate")); + assertFalse(deflateExtension.acceptProvidedExtensionAsServer("wrong-permessage-deflate")); + } + + @Test + public void testAcceptProvidedExtensionAsClient() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertTrue(deflateExtension.acceptProvidedExtensionAsClient("permessage-deflate")); + assertTrue(deflateExtension + .acceptProvidedExtensionAsClient("some-other-extension, permessage-deflate")); + assertFalse(deflateExtension.acceptProvidedExtensionAsClient("wrong-permessage-deflate")); + } + + @Test + public void testIsFrameValid() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + TextFrame frame = new TextFrame(); + try { + deflateExtension.isFrameValid(frame); + fail("Frame not valid. RSV1 must be set."); + } catch (Exception e) { + // + } + frame.setRSV1(true); + try { + deflateExtension.isFrameValid(frame); + } catch (Exception e) { + fail("Frame is valid."); + } + frame.setRSV2(true); + try { + deflateExtension.isFrameValid(frame); + fail("Only RSV1 bit must be set."); + } catch (Exception e) { + // + } + ContinuousFrame contFrame = new ContinuousFrame(); + contFrame.setRSV1(true); + try { + deflateExtension.isFrameValid(contFrame); + fail("RSV1 must only be set for first fragments.Continuous frames can't have RSV1 bit set."); + } catch (Exception e) { + // + } + contFrame.setRSV1(false); + try { + deflateExtension.isFrameValid(contFrame); + } catch (Exception e) { + fail("Continuous frame is valid."); + } + } + + @Test + public void testGetProvidedExtensionAsClient() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertEquals("permessage-deflate; server_no_context_takeover; client_no_context_takeover", + deflateExtension.getProvidedExtensionAsClient()); + } + + @Test + public void testGetProvidedExtensionAsServer() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertEquals("permessage-deflate; server_no_context_takeover", + deflateExtension.getProvidedExtensionAsServer()); + } + + @Test + public void testToString() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertEquals("PerMessageDeflateExtension", deflateExtension.toString()); + } + + @Test + public void testIsServerNoContextTakeover() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertTrue(deflateExtension.isServerNoContextTakeover()); + } + + @Test + public void testSetServerNoContextTakeover() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setServerNoContextTakeover(false); + assertFalse(deflateExtension.isServerNoContextTakeover()); + } + + @Test + public void testIsClientNoContextTakeover() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertFalse(deflateExtension.isClientNoContextTakeover()); + } + + @Test + public void testSetClientNoContextTakeover() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setClientNoContextTakeover(true); + assertTrue(deflateExtension.isClientNoContextTakeover()); + } + + @Test + public void testCopyInstance() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + IExtension newDeflateExtension = deflateExtension.copyInstance(); + assertEquals(deflateExtension.toString(), newDeflateExtension.toString()); + } + + @Test + public void testGetInflater() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertEquals(deflateExtension.getInflater().getRemaining(), new Inflater(true).getRemaining()); + } + + @Test + public void testSetInflater() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setInflater(new Inflater(false)); + assertEquals(deflateExtension.getInflater().getRemaining(), new Inflater(false).getRemaining()); + } + + @Test + public void testGetDeflater() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertEquals(deflateExtension.getDeflater().finished(), + new Deflater(Deflater.DEFAULT_COMPRESSION, true).finished()); + } + + @Test + public void testSetDeflater() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setDeflater(new Deflater(Deflater.DEFAULT_COMPRESSION, false)); + assertEquals(deflateExtension.getDeflater().finished(), + new Deflater(Deflater.DEFAULT_COMPRESSION, false).finished()); + } } diff --git a/src/test/java/org/java_websocket/framing/AllFramingTests.java b/src/test/java/org/java_websocket/framing/AllFramingTests.java index 900e3f395..24265d8eb 100644 --- a/src/test/java/org/java_websocket/framing/AllFramingTests.java +++ b/src/test/java/org/java_websocket/framing/AllFramingTests.java @@ -32,16 +32,17 @@ @RunWith(Suite.class) @Suite.SuiteClasses({ - org.java_websocket.framing.BinaryFrameTest.class, - org.java_websocket.framing.PingFrameTest.class, - org.java_websocket.framing.PongFrameTest.class, - org.java_websocket.framing.CloseFrameTest.class, - org.java_websocket.framing.TextFrameTest.class, - org.java_websocket.framing.ContinuousFrameTest.class, - org.java_websocket.framing.FramedataImpl1Test.class + org.java_websocket.framing.BinaryFrameTest.class, + org.java_websocket.framing.PingFrameTest.class, + org.java_websocket.framing.PongFrameTest.class, + org.java_websocket.framing.CloseFrameTest.class, + org.java_websocket.framing.TextFrameTest.class, + org.java_websocket.framing.ContinuousFrameTest.class, + org.java_websocket.framing.FramedataImpl1Test.class }) /** * Start all tests for frames */ public class AllFramingTests { + } diff --git a/src/test/java/org/java_websocket/framing/BinaryFrameTest.java b/src/test/java/org/java_websocket/framing/BinaryFrameTest.java index 994660652..364b3cf61 100644 --- a/src/test/java/org/java_websocket/framing/BinaryFrameTest.java +++ b/src/test/java/org/java_websocket/framing/BinaryFrameTest.java @@ -37,36 +37,36 @@ */ public class BinaryFrameTest { - @Test - public void testConstructor() { - BinaryFrame frame = new BinaryFrame(); - assertEquals("Opcode must be equal", Opcode.BINARY , frame.getOpcode()); - assertEquals("Fin must be set", true , frame.isFin()); - assertEquals("TransferedMask must not be set", false , frame.getTransfereMasked()); - assertEquals("Payload must be empty", 0 , frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false , frame.isRSV1()); - assertEquals("RSV2 must be false", false , frame.isRSV2()); - assertEquals("RSV3 must be false", false , frame.isRSV3()); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } + @Test + public void testConstructor() { + BinaryFrame frame = new BinaryFrame(); + assertEquals("Opcode must be equal", Opcode.BINARY, frame.getOpcode()); + assertEquals("Fin must be set", true, frame.isFin()); + assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); + assertEquals("Payload must be empty", 0, frame.getPayloadData().capacity()); + assertEquals("RSV1 must be false", false, frame.isRSV1()); + assertEquals("RSV2 must be false", false, frame.isRSV2()); + assertEquals("RSV3 must be false", false, frame.isRSV3()); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); } + } - @Test - public void testExtends() { - BinaryFrame frame = new BinaryFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof DataFrame); - } + @Test + public void testExtends() { + BinaryFrame frame = new BinaryFrame(); + assertEquals("Frame must extend dataframe", true, frame instanceof DataFrame); + } - @Test - public void testIsValid() { - BinaryFrame frame = new BinaryFrame(); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } + @Test + public void testIsValid() { + BinaryFrame frame = new BinaryFrame(); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); } + } } diff --git a/src/test/java/org/java_websocket/framing/CloseFrameTest.java b/src/test/java/org/java_websocket/framing/CloseFrameTest.java index 3ddd9fa6c..2932e29cf 100644 --- a/src/test/java/org/java_websocket/framing/CloseFrameTest.java +++ b/src/test/java/org/java_websocket/framing/CloseFrameTest.java @@ -37,209 +37,211 @@ */ public class CloseFrameTest { - @Test - public void testConstructor() { - CloseFrame frame = new CloseFrame(); - assertEquals("Opcode must be equal", Opcode.CLOSING, frame.getOpcode()); - assertEquals("Fin must be set", true, frame.isFin()); - assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); - assertEquals("Payload must be 2 (close code)", 2, frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false, frame.isRSV1()); - assertEquals("RSV2 must be false", false, frame.isRSV2()); - assertEquals("RSV3 must be false", false, frame.isRSV3()); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } + @Test + public void testConstructor() { + CloseFrame frame = new CloseFrame(); + assertEquals("Opcode must be equal", Opcode.CLOSING, frame.getOpcode()); + assertEquals("Fin must be set", true, frame.isFin()); + assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); + assertEquals("Payload must be 2 (close code)", 2, frame.getPayloadData().capacity()); + assertEquals("RSV1 must be false", false, frame.isRSV1()); + assertEquals("RSV2 must be false", false, frame.isRSV2()); + assertEquals("RSV3 must be false", false, frame.isRSV3()); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); } + } - @Test - public void testExtends() { - CloseFrame frame = new CloseFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof ControlFrame); - } + @Test + public void testExtends() { + CloseFrame frame = new CloseFrame(); + assertEquals("Frame must extend dataframe", true, frame instanceof ControlFrame); + } - @Test - public void testToString() { - CloseFrame frame = new CloseFrame(); - String frameString = frame.toString(); - frameString = frameString.replaceAll("payload:(.*)}", "payload: *}"); - assertEquals("Frame toString must include a close code", "Framedata{ opcode:CLOSING, fin:true, rsv1:false, rsv2:false, rsv3:false, payload length:[pos:0, len:2], payload: *}code: 1000", frameString); - } + @Test + public void testToString() { + CloseFrame frame = new CloseFrame(); + String frameString = frame.toString(); + frameString = frameString.replaceAll("payload:(.*)}", "payload: *}"); + assertEquals("Frame toString must include a close code", + "Framedata{ opcode:CLOSING, fin:true, rsv1:false, rsv2:false, rsv3:false, payload length:[pos:0, len:2], payload: *}code: 1000", + frameString); + } - @Test - public void testIsValid() { - CloseFrame frame = new CloseFrame(); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setFin(false); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setFin(true); - frame.setRSV1(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV1(false); - frame.setRSV2(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV2(false); - frame.setRSV3(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV3(false); - frame.setCode(CloseFrame.NORMAL); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.GOING_AWAY); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.PROTOCOL_ERROR); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.REFUSE); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.NOCODE); - assertEquals(0,frame.getPayloadData().capacity()); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.ABNORMAL_CLOSE); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.POLICY_VALIDATION); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.TOOBIG); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.EXTENSION); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.UNEXPECTED_CONDITION); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.SERVICE_RESTART); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.TRY_AGAIN_LATER); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.BAD_GATEWAY); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.TLS_ERROR); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.NEVER_CONNECTED); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.BUGGYCLOSE); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.FLASHPOLICY); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.NOCODE); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.NO_UTF8); - frame.setReason(null); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.NOCODE); - frame.setReason("Close"); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } + @Test + public void testIsValid() { + CloseFrame frame = new CloseFrame(); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setFin(false); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setFin(true); + frame.setRSV1(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV1(false); + frame.setRSV2(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV2(false); + frame.setRSV3(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV3(false); + frame.setCode(CloseFrame.NORMAL); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.GOING_AWAY); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.PROTOCOL_ERROR); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.REFUSE); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.NOCODE); + assertEquals(0, frame.getPayloadData().capacity()); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.ABNORMAL_CLOSE); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.POLICY_VALIDATION); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.TOOBIG); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.EXTENSION); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.UNEXPECTED_CONDITION); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.SERVICE_RESTART); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.TRY_AGAIN_LATER); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.BAD_GATEWAY); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.TLS_ERROR); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.NEVER_CONNECTED); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.BUGGYCLOSE); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.FLASHPOLICY); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.NOCODE); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.NO_UTF8); + frame.setReason(null); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.NOCODE); + frame.setReason("Close"); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine } + } } diff --git a/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java b/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java index a6ea68e11..a39b6be10 100644 --- a/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java +++ b/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java @@ -37,36 +37,36 @@ */ public class ContinuousFrameTest { - @Test - public void testConstructor() { - ContinuousFrame frame = new ContinuousFrame(); - assertEquals("Opcode must be equal", Opcode.CONTINUOUS , frame.getOpcode()); - assertEquals("Fin must be set", true , frame.isFin()); - assertEquals("TransferedMask must not be set", false , frame.getTransfereMasked()); - assertEquals("Payload must be empty", 0 , frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false , frame.isRSV1()); - assertEquals("RSV2 must be false", false , frame.isRSV2()); - assertEquals("RSV3 must be false", false , frame.isRSV3()); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } + @Test + public void testConstructor() { + ContinuousFrame frame = new ContinuousFrame(); + assertEquals("Opcode must be equal", Opcode.CONTINUOUS, frame.getOpcode()); + assertEquals("Fin must be set", true, frame.isFin()); + assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); + assertEquals("Payload must be empty", 0, frame.getPayloadData().capacity()); + assertEquals("RSV1 must be false", false, frame.isRSV1()); + assertEquals("RSV2 must be false", false, frame.isRSV2()); + assertEquals("RSV3 must be false", false, frame.isRSV3()); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); } + } - @Test - public void testExtends() { - ContinuousFrame frame = new ContinuousFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof DataFrame); - } + @Test + public void testExtends() { + ContinuousFrame frame = new ContinuousFrame(); + assertEquals("Frame must extend dataframe", true, frame instanceof DataFrame); + } - @Test - public void testIsValid() { - ContinuousFrame frame = new ContinuousFrame(); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } + @Test + public void testIsValid() { + ContinuousFrame frame = new ContinuousFrame(); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); } + } } diff --git a/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java b/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java index fbfaa256e..8c099f0dc 100644 --- a/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java +++ b/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java @@ -39,67 +39,68 @@ */ public class FramedataImpl1Test { - @Test - public void testDefaultValues() { - FramedataImpl1 binary = FramedataImpl1.get(Opcode.BINARY); - assertEquals("Opcode must be equal", Opcode.BINARY, binary.getOpcode()); - assertEquals("Fin must be set", true, binary.isFin()); - assertEquals("TransferedMask must not be set", false, binary.getTransfereMasked()); - assertEquals("Payload must be empty", 0, binary.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false, binary.isRSV1()); - assertEquals("RSV2 must be false", false, binary.isRSV2()); - assertEquals("RSV3 must be false", false, binary.isRSV3()); - } + @Test + public void testDefaultValues() { + FramedataImpl1 binary = FramedataImpl1.get(Opcode.BINARY); + assertEquals("Opcode must be equal", Opcode.BINARY, binary.getOpcode()); + assertEquals("Fin must be set", true, binary.isFin()); + assertEquals("TransferedMask must not be set", false, binary.getTransfereMasked()); + assertEquals("Payload must be empty", 0, binary.getPayloadData().capacity()); + assertEquals("RSV1 must be false", false, binary.isRSV1()); + assertEquals("RSV2 must be false", false, binary.isRSV2()); + assertEquals("RSV3 must be false", false, binary.isRSV3()); + } - @Test - public void testGet() { - FramedataImpl1 binary = FramedataImpl1.get(Opcode.BINARY); - assertEquals("Frame must be binary", true, binary instanceof BinaryFrame); - FramedataImpl1 text = FramedataImpl1.get(Opcode.TEXT); - assertEquals("Frame must be text", true, text instanceof TextFrame); - FramedataImpl1 closing = FramedataImpl1.get(Opcode.CLOSING); - assertEquals("Frame must be closing", true, closing instanceof CloseFrame); - FramedataImpl1 continuous = FramedataImpl1.get(Opcode.CONTINUOUS); - assertEquals("Frame must be continuous", true, continuous instanceof ContinuousFrame); - FramedataImpl1 ping = FramedataImpl1.get(Opcode.PING); - assertEquals("Frame must be ping", true, ping instanceof PingFrame); - FramedataImpl1 pong = FramedataImpl1.get(Opcode.PONG); - assertEquals("Frame must be pong", true, pong instanceof PongFrame); - try { - FramedataImpl1.get(null); - fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException e) { - //Fine - } + @Test + public void testGet() { + FramedataImpl1 binary = FramedataImpl1.get(Opcode.BINARY); + assertEquals("Frame must be binary", true, binary instanceof BinaryFrame); + FramedataImpl1 text = FramedataImpl1.get(Opcode.TEXT); + assertEquals("Frame must be text", true, text instanceof TextFrame); + FramedataImpl1 closing = FramedataImpl1.get(Opcode.CLOSING); + assertEquals("Frame must be closing", true, closing instanceof CloseFrame); + FramedataImpl1 continuous = FramedataImpl1.get(Opcode.CONTINUOUS); + assertEquals("Frame must be continuous", true, continuous instanceof ContinuousFrame); + FramedataImpl1 ping = FramedataImpl1.get(Opcode.PING); + assertEquals("Frame must be ping", true, ping instanceof PingFrame); + FramedataImpl1 pong = FramedataImpl1.get(Opcode.PONG); + assertEquals("Frame must be pong", true, pong instanceof PongFrame); + try { + FramedataImpl1.get(null); + fail("IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException e) { + //Fine } + } - @Test - public void testSetters() { - FramedataImpl1 frame = FramedataImpl1.get(Opcode.BINARY); - frame.setFin(false); - assertEquals("Fin must not be set", false, frame.isFin()); - frame.setTransferemasked(true); - assertEquals("TransferedMask must be set", true, frame.getTransfereMasked()); - ByteBuffer buffer = ByteBuffer.allocate(100); - frame.setPayload(buffer); - assertEquals("Payload must be of size 100", 100, frame.getPayloadData().capacity()); - frame.setRSV1(true); - assertEquals("RSV1 must be true", true, frame.isRSV1()); - frame.setRSV2(true); - assertEquals("RSV2 must be true", true, frame.isRSV2()); - frame.setRSV3(true); - assertEquals("RSV3 must be true", true, frame.isRSV3()); - } + @Test + public void testSetters() { + FramedataImpl1 frame = FramedataImpl1.get(Opcode.BINARY); + frame.setFin(false); + assertEquals("Fin must not be set", false, frame.isFin()); + frame.setTransferemasked(true); + assertEquals("TransferedMask must be set", true, frame.getTransfereMasked()); + ByteBuffer buffer = ByteBuffer.allocate(100); + frame.setPayload(buffer); + assertEquals("Payload must be of size 100", 100, frame.getPayloadData().capacity()); + frame.setRSV1(true); + assertEquals("RSV1 must be true", true, frame.isRSV1()); + frame.setRSV2(true); + assertEquals("RSV2 must be true", true, frame.isRSV2()); + frame.setRSV3(true); + assertEquals("RSV3 must be true", true, frame.isRSV3()); + } - @Test - public void testAppend() { - FramedataImpl1 frame0 = FramedataImpl1.get(Opcode.BINARY); - frame0.setFin(false); - frame0.setPayload(ByteBuffer.wrap("first".getBytes())); - FramedataImpl1 frame1 = FramedataImpl1.get(Opcode.BINARY); - frame1.setPayload(ByteBuffer.wrap("second".getBytes())); - frame0.append(frame1); - assertEquals("Fin must be set", true, frame0.isFin()); - assertArrayEquals("Payload must be equal", "firstsecond".getBytes(), frame0.getPayloadData().array()); - } + @Test + public void testAppend() { + FramedataImpl1 frame0 = FramedataImpl1.get(Opcode.BINARY); + frame0.setFin(false); + frame0.setPayload(ByteBuffer.wrap("first".getBytes())); + FramedataImpl1 frame1 = FramedataImpl1.get(Opcode.BINARY); + frame1.setPayload(ByteBuffer.wrap("second".getBytes())); + frame0.append(frame1); + assertEquals("Fin must be set", true, frame0.isFin()); + assertArrayEquals("Payload must be equal", "firstsecond".getBytes(), + frame0.getPayloadData().array()); + } } diff --git a/src/test/java/org/java_websocket/framing/PingFrameTest.java b/src/test/java/org/java_websocket/framing/PingFrameTest.java index 2056d31b0..9c5177bbe 100644 --- a/src/test/java/org/java_websocket/framing/PingFrameTest.java +++ b/src/test/java/org/java_websocket/framing/PingFrameTest.java @@ -37,67 +37,67 @@ */ public class PingFrameTest { - @Test - public void testConstructor() { - PingFrame frame = new PingFrame(); - assertEquals("Opcode must be equal", Opcode.PING , frame.getOpcode()); - assertEquals("Fin must be set", true , frame.isFin()); - assertEquals("TransferedMask must not be set", false , frame.getTransfereMasked()); - assertEquals("Payload must be empty", 0 , frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false , frame.isRSV1()); - assertEquals("RSV2 must be false", false , frame.isRSV2()); - assertEquals("RSV3 must be false", false , frame.isRSV3()); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } + @Test + public void testConstructor() { + PingFrame frame = new PingFrame(); + assertEquals("Opcode must be equal", Opcode.PING, frame.getOpcode()); + assertEquals("Fin must be set", true, frame.isFin()); + assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); + assertEquals("Payload must be empty", 0, frame.getPayloadData().capacity()); + assertEquals("RSV1 must be false", false, frame.isRSV1()); + assertEquals("RSV2 must be false", false, frame.isRSV2()); + assertEquals("RSV3 must be false", false, frame.isRSV3()); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); } + } - @Test - public void testExtends() { - PingFrame frame = new PingFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof ControlFrame); - } + @Test + public void testExtends() { + PingFrame frame = new PingFrame(); + assertEquals("Frame must extend dataframe", true, frame instanceof ControlFrame); + } - @Test - public void testIsValid() { - PingFrame frame = new PingFrame(); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setFin(false); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setFin(true); - frame.setRSV1(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV1(false); - frame.setRSV2(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV2(false); - frame.setRSV3(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } + @Test + public void testIsValid() { + PingFrame frame = new PingFrame(); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setFin(false); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setFin(true); + frame.setRSV1(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV1(false); + frame.setRSV2(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV2(false); + frame.setRSV3(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine } + } } diff --git a/src/test/java/org/java_websocket/framing/PongFrameTest.java b/src/test/java/org/java_websocket/framing/PongFrameTest.java index 03bb316ed..6fb9490b3 100644 --- a/src/test/java/org/java_websocket/framing/PongFrameTest.java +++ b/src/test/java/org/java_websocket/framing/PongFrameTest.java @@ -39,75 +39,75 @@ */ public class PongFrameTest { - @Test - public void testConstructor() { - PongFrame frame = new PongFrame(); - assertEquals("Opcode must be equal", Opcode.PONG , frame.getOpcode()); - assertEquals("Fin must be set", true , frame.isFin()); - assertEquals("TransferedMask must not be set", false , frame.getTransfereMasked()); - assertEquals("Payload must be empty", 0 , frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false , frame.isRSV1()); - assertEquals("RSV2 must be false", false , frame.isRSV2()); - assertEquals("RSV3 must be false", false , frame.isRSV3()); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } + @Test + public void testConstructor() { + PongFrame frame = new PongFrame(); + assertEquals("Opcode must be equal", Opcode.PONG, frame.getOpcode()); + assertEquals("Fin must be set", true, frame.isFin()); + assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); + assertEquals("Payload must be empty", 0, frame.getPayloadData().capacity()); + assertEquals("RSV1 must be false", false, frame.isRSV1()); + assertEquals("RSV2 must be false", false, frame.isRSV2()); + assertEquals("RSV3 must be false", false, frame.isRSV3()); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); } + } - @Test - public void testCopyConstructor() { - PingFrame pingFrame = new PingFrame(); - pingFrame.setPayload(ByteBuffer.allocate(100)); - PongFrame pongFrame = new PongFrame(pingFrame); - assertEquals("Payload must be equal", pingFrame.getPayloadData() , pongFrame.getPayloadData()); - } + @Test + public void testCopyConstructor() { + PingFrame pingFrame = new PingFrame(); + pingFrame.setPayload(ByteBuffer.allocate(100)); + PongFrame pongFrame = new PongFrame(pingFrame); + assertEquals("Payload must be equal", pingFrame.getPayloadData(), pongFrame.getPayloadData()); + } - @Test - public void testExtends() { - PongFrame frame = new PongFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof ControlFrame); - } + @Test + public void testExtends() { + PongFrame frame = new PongFrame(); + assertEquals("Frame must extend dataframe", true, frame instanceof ControlFrame); + } - @Test - public void testIsValid() { - PongFrame frame = new PongFrame(); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setFin(false); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setFin(true); - frame.setRSV1(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV1(false); - frame.setRSV2(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV2(false); - frame.setRSV3(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } + @Test + public void testIsValid() { + PongFrame frame = new PongFrame(); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setFin(false); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setFin(true); + frame.setRSV1(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV1(false); + frame.setRSV2(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV2(false); + frame.setRSV3(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine } + } } diff --git a/src/test/java/org/java_websocket/framing/TextFrameTest.java b/src/test/java/org/java_websocket/framing/TextFrameTest.java index 433e89962..fc7d5041a 100644 --- a/src/test/java/org/java_websocket/framing/TextFrameTest.java +++ b/src/test/java/org/java_websocket/framing/TextFrameTest.java @@ -39,52 +39,52 @@ */ public class TextFrameTest { - @Test - public void testConstructor() { - TextFrame frame = new TextFrame(); - assertEquals("Opcode must be equal", Opcode.TEXT , frame.getOpcode()); - assertEquals("Fin must be set", true , frame.isFin()); - assertEquals("TransferedMask must not be set", false , frame.getTransfereMasked()); - assertEquals("Payload must be empty", 0 , frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false , frame.isRSV1()); - assertEquals("RSV2 must be false", false , frame.isRSV2()); - assertEquals("RSV3 must be false", false , frame.isRSV3()); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } + @Test + public void testConstructor() { + TextFrame frame = new TextFrame(); + assertEquals("Opcode must be equal", Opcode.TEXT, frame.getOpcode()); + assertEquals("Fin must be set", true, frame.isFin()); + assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); + assertEquals("Payload must be empty", 0, frame.getPayloadData().capacity()); + assertEquals("RSV1 must be false", false, frame.isRSV1()); + assertEquals("RSV2 must be false", false, frame.isRSV2()); + assertEquals("RSV3 must be false", false, frame.isRSV3()); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); } + } - @Test - public void testExtends() { - TextFrame frame = new TextFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof DataFrame); - } + @Test + public void testExtends() { + TextFrame frame = new TextFrame(); + assertEquals("Frame must extend dataframe", true, frame instanceof DataFrame); + } - @Test - public void testIsValid() { - TextFrame frame = new TextFrame(); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } + @Test + public void testIsValid() { + TextFrame frame = new TextFrame(); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } - frame = new TextFrame(); - frame.setPayload(ByteBuffer.wrap(new byte[] { - (byte) 0xD0, (byte) 0x9F, // 'П' - (byte) 0xD1, (byte) 0x80, // 'р' - (byte) 0xD0, // corrupted UTF-8, was 'и' - (byte) 0xD0, (byte) 0xB2, // 'в' - (byte) 0xD0, (byte) 0xB5, // 'е' - (byte) 0xD1, (byte) 0x82 // 'т' - })); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Utf8 Check should work - } + frame = new TextFrame(); + frame.setPayload(ByteBuffer.wrap(new byte[]{ + (byte) 0xD0, (byte) 0x9F, // 'П' + (byte) 0xD1, (byte) 0x80, // 'р' + (byte) 0xD0, // corrupted UTF-8, was 'и' + (byte) 0xD0, (byte) 0xB2, // 'в' + (byte) 0xD0, (byte) 0xB5, // 'е' + (byte) 0xD1, (byte) 0x82 // 'т' + })); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Utf8 Check should work } + } } diff --git a/src/test/java/org/java_websocket/issues/AllIssueTests.java b/src/test/java/org/java_websocket/issues/AllIssueTests.java index f763d04e4..3668bcb89 100644 --- a/src/test/java/org/java_websocket/issues/AllIssueTests.java +++ b/src/test/java/org/java_websocket/issues/AllIssueTests.java @@ -24,29 +24,31 @@ */ package org.java_websocket.issues; + import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ - org.java_websocket.issues.Issue609Test.class, - org.java_websocket.issues.Issue621Test.class, - org.java_websocket.issues.Issue580Test.class, - org.java_websocket.issues.Issue598Test.class, - org.java_websocket.issues.Issue256Test.class, - org.java_websocket.issues.Issue661Test.class, - org.java_websocket.issues.Issue666Test.class, - org.java_websocket.issues.Issue677Test.class, - org.java_websocket.issues.Issue732Test.class, - org.java_websocket.issues.Issue764Test.class, - org.java_websocket.issues.Issue765Test.class, - org.java_websocket.issues.Issue825Test.class, - org.java_websocket.issues.Issue834Test.class, - org.java_websocket.issues.Issue962Test.class + org.java_websocket.issues.Issue609Test.class, + org.java_websocket.issues.Issue621Test.class, + org.java_websocket.issues.Issue580Test.class, + org.java_websocket.issues.Issue598Test.class, + org.java_websocket.issues.Issue256Test.class, + org.java_websocket.issues.Issue661Test.class, + org.java_websocket.issues.Issue666Test.class, + org.java_websocket.issues.Issue677Test.class, + org.java_websocket.issues.Issue732Test.class, + org.java_websocket.issues.Issue764Test.class, + org.java_websocket.issues.Issue765Test.class, + org.java_websocket.issues.Issue825Test.class, + org.java_websocket.issues.Issue834Test.class, + org.java_websocket.issues.Issue962Test.class }) /** * Start all tests for issues */ public class AllIssueTests { + } diff --git a/src/test/java/org/java_websocket/issues/Issue256Test.java b/src/test/java/org/java_websocket/issues/Issue256Test.java index 29cae69ef..314185d12 100644 --- a/src/test/java/org/java_websocket/issues/Issue256Test.java +++ b/src/test/java/org/java_websocket/issues/Issue256Test.java @@ -51,112 +51,114 @@ @RunWith(Parameterized.class) public class Issue256Test { - private static final int NUMBER_OF_TESTS = 10; - private static WebSocketServer ws; - - private static int port; - static CountDownLatch countServerDownLatch = new CountDownLatch( 1 ); - @Rule - public ThreadCheck zombies = new ThreadCheck(); - - @Parameterized.Parameter - public int count; - - @BeforeClass - public static void startServer() throws Exception { - port = SocketUtil.getAvailablePort(); - ws = new WebSocketServer( new InetSocketAddress( port ) , 16) { - @Override - public void onOpen( WebSocket conn, ClientHandshake handshake ) { - - } - - @Override - public void onClose( WebSocket conn, int code, String reason, boolean remote ) { - - } - - @Override - public void onMessage( WebSocket conn, String message ) { - conn.send( message ); - } - - @Override - public void onError( WebSocket conn, Exception ex ) { - - ex.printStackTrace( ); - assumeThat(true, is(false)); - System.out.println("There should be no exception!"); - } - - @Override - public void onStart() { - countServerDownLatch.countDown(); - } - }; - ws.setConnectionLostTimeout( 0 ); - ws.start(); - countServerDownLatch.await(); - } - - private void runTestScenarioReconnect( boolean closeBlocking ) throws Exception { - final CountDownLatch countDownLatch0 = new CountDownLatch( 1 ); - final CountDownLatch countDownLatch1 = new CountDownLatch( 2 ); - WebSocketClient clt = new WebSocketClient( new URI( "ws://localhost:" + port ) ) { - @Override - public void onOpen( ServerHandshake handshakedata ) { - countDownLatch1.countDown(); - } - - @Override - public void onMessage( String message ) { - - } - - @Override - public void onClose( int code, String reason, boolean remote ) { - countDownLatch0.countDown(); - } - - @Override - public void onError( Exception ex ) { - ex.printStackTrace( ); - assumeThat(true, is(false)); - System.out.println("There should be no exception!"); - } - }; - clt.connectBlocking(); - if( closeBlocking ) { - clt.closeBlocking(); - } else { - clt.getSocket().close(); - } - countDownLatch0.await(); - clt.reconnectBlocking(); - clt.closeBlocking(); - } - - @AfterClass - public static void successTests() throws InterruptedException, IOException { - ws.stop(); - } - - @Parameterized.Parameters - public static Collection data() { - List ret = new ArrayList(NUMBER_OF_TESTS); - for (int i = 0; i < NUMBER_OF_TESTS; i++) ret.add(new Integer[]{i}); - return ret; - } - - @Test(timeout = 5000) - public void runReconnectSocketClose() throws Exception { - runTestScenarioReconnect( false ); - } - - @Test(timeout = 5000) - public void runReconnectCloseBlocking() throws Exception { - runTestScenarioReconnect( true ); - } + private static final int NUMBER_OF_TESTS = 10; + private static WebSocketServer ws; + + private static int port; + static CountDownLatch countServerDownLatch = new CountDownLatch(1); + @Rule + public ThreadCheck zombies = new ThreadCheck(); + + @Parameterized.Parameter + public int count; + + @BeforeClass + public static void startServer() throws Exception { + port = SocketUtil.getAvailablePort(); + ws = new WebSocketServer(new InetSocketAddress(port), 16) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + + } + + @Override + public void onMessage(WebSocket conn, String message) { + conn.send(message); + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + ex.printStackTrace(); + assumeThat(true, is(false)); + System.out.println("There should be no exception!"); + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + }; + ws.setConnectionLostTimeout(0); + ws.start(); + countServerDownLatch.await(); + } + + private void runTestScenarioReconnect(boolean closeBlocking) throws Exception { + final CountDownLatch countDownLatch0 = new CountDownLatch(1); + final CountDownLatch countDownLatch1 = new CountDownLatch(2); + WebSocketClient clt = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + countDownLatch1.countDown(); + } + + @Override + public void onMessage(String message) { + + } + + @Override + public void onClose(int code, String reason, boolean remote) { + countDownLatch0.countDown(); + } + + @Override + public void onError(Exception ex) { + ex.printStackTrace(); + assumeThat(true, is(false)); + System.out.println("There should be no exception!"); + } + }; + clt.connectBlocking(); + if (closeBlocking) { + clt.closeBlocking(); + } else { + clt.getSocket().close(); + } + countDownLatch0.await(); + clt.reconnectBlocking(); + clt.closeBlocking(); + } + + @AfterClass + public static void successTests() throws InterruptedException, IOException { + ws.stop(); + } + + @Parameterized.Parameters + public static Collection data() { + List ret = new ArrayList(NUMBER_OF_TESTS); + for (int i = 0; i < NUMBER_OF_TESTS; i++) { + ret.add(new Integer[]{i}); + } + return ret; + } + + @Test(timeout = 5000) + public void runReconnectSocketClose() throws Exception { + runTestScenarioReconnect(false); + } + + @Test(timeout = 5000) + public void runReconnectCloseBlocking() throws Exception { + runTestScenarioReconnect(true); + } } diff --git a/src/test/java/org/java_websocket/issues/Issue580Test.java b/src/test/java/org/java_websocket/issues/Issue580Test.java index b196d7c6a..64e445f37 100644 --- a/src/test/java/org/java_websocket/issues/Issue580Test.java +++ b/src/test/java/org/java_websocket/issues/Issue580Test.java @@ -48,90 +48,93 @@ @RunWith(Parameterized.class) public class Issue580Test { - private static final int NUMBER_OF_TESTS = 10; + private static final int NUMBER_OF_TESTS = 10; - @Parameterized.Parameter - public int count; + @Parameterized.Parameter + public int count; - @Rule - public ThreadCheck zombies = new ThreadCheck(); + @Rule + public ThreadCheck zombies = new ThreadCheck(); - private void runTestScenario(boolean closeBlocking) throws Exception { - final CountDownLatch countServerDownLatch = new CountDownLatch( 1 ); - int port = SocketUtil.getAvailablePort(); - WebSocketServer ws = new WebSocketServer( new InetSocketAddress( port ) ) { - @Override - public void onOpen( WebSocket conn, ClientHandshake handshake ) { + private void runTestScenario(boolean closeBlocking) throws Exception { + final CountDownLatch countServerDownLatch = new CountDownLatch(1); + int port = SocketUtil.getAvailablePort(); + WebSocketServer ws = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { - } + } - @Override - public void onClose( WebSocket conn, int code, String reason, boolean remote ) { + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { - } + } - @Override - public void onMessage( WebSocket conn, String message ) { + @Override + public void onMessage(WebSocket conn, String message) { - } + } - @Override - public void onError( WebSocket conn, Exception ex ) { + @Override + public void onError(WebSocket conn, Exception ex) { - } + } - @Override - public void onStart() { - countServerDownLatch.countDown(); - } - }; - ws.start(); - countServerDownLatch.await(); - WebSocketClient clt = new WebSocketClient( new URI( "ws://localhost:" + port ) ) { - @Override - public void onOpen( ServerHandshake handshakedata ) { + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + }; + ws.start(); + countServerDownLatch.await(); + WebSocketClient clt = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { - } + } - @Override - public void onMessage( String message ) { + @Override + public void onMessage(String message) { - } + } - @Override - public void onClose( int code, String reason, boolean remote ) { + @Override + public void onClose(int code, String reason, boolean remote) { - } + } - @Override - public void onError( Exception ex ) { + @Override + public void onError(Exception ex) { - } - }; - clt.connectBlocking(); - clt.send("test"); - if (closeBlocking) { - clt.closeBlocking(); - } - ws.stop(); - Thread.sleep( 100 ); - } + } + }; + clt.connectBlocking(); + clt.send("test"); + if (closeBlocking) { + clt.closeBlocking(); + } + ws.stop(); + Thread.sleep(100); + } - @Parameterized.Parameters - public static Collection data() { - List ret = new ArrayList(NUMBER_OF_TESTS); - for (int i = 0; i < NUMBER_OF_TESTS; i++) ret.add(new Integer[]{i}); - return ret; - } + @Parameterized.Parameters + public static Collection data() { + List ret = new ArrayList(NUMBER_OF_TESTS); + for (int i = 0; i < NUMBER_OF_TESTS; i++) { + ret.add(new Integer[]{i}); + } + return ret; + } - @Test - public void runNoCloseBlockingTestScenario() throws Exception { - runTestScenario(false); - } - @Test - public void runCloseBlockingTestScenario() throws Exception { - runTestScenario(true); - } + @Test + public void runNoCloseBlockingTestScenario() throws Exception { + runTestScenario(false); + } + + @Test + public void runCloseBlockingTestScenario() throws Exception { + runTestScenario(true); + } } diff --git a/src/test/java/org/java_websocket/issues/Issue598Test.java b/src/test/java/org/java_websocket/issues/Issue598Test.java index 50095ff3b..c6705a7c4 100644 --- a/src/test/java/org/java_websocket/issues/Issue598Test.java +++ b/src/test/java/org/java_websocket/issues/Issue598Test.java @@ -51,172 +51,185 @@ public class Issue598Test { - private static List protocolList = Collections.singletonList( new Protocol( "" )); - private static List extensionList = Collections.emptyList(); - - private static void runTestScenario(int testCase) throws Exception { - final CountDownLatch countServerDownLatch = new CountDownLatch( 1 ); - final CountDownLatch countReceiveDownLatch = new CountDownLatch( 1 ); - final CountDownLatch countCloseDownLatch = new CountDownLatch( 1 ); - int port = SocketUtil.getAvailablePort(); - Draft draft = null; - switch (testCase) { - case 0: - case 1: - case 2: - case 3: - draft = new Draft_6455(extensionList, protocolList, 10); - break; - case 4: - case 5: - case 6: - case 7: - draft = new Draft_6455(extensionList, protocolList, 9); - break; - } - WebSocketClient webSocket = new WebSocketClient( new URI( "ws://localhost:" + port )) { - @Override - public void onOpen( ServerHandshake handshakedata ) { - - } - - @Override - public void onMessage( String message ) { - } - - - @Override - public void onClose( int code, String reason, boolean remote ) { - - } - - @Override - public void onError( Exception ex ) { - - } - }; - WebSocketServer server = new WebSocketServer( new InetSocketAddress( port ) , Collections.singletonList(draft)) { - @Override - public void onOpen( WebSocket conn, ClientHandshake handshake ) { - } - - @Override - public void onClose( WebSocket conn, int code, String reason, boolean remote ) { - if (code == CloseFrame.TOOBIG) { - countCloseDownLatch.countDown(); - } - } - - @Override - public void onMessage( WebSocket conn, String message ) { - countReceiveDownLatch.countDown(); - } - - @Override - public void onMessage( WebSocket conn, ByteBuffer message ) { - countReceiveDownLatch.countDown(); - } - - @Override - public void onError( WebSocket conn, Exception ex ) { - - } - - @Override - public void onStart() { - countServerDownLatch.countDown(); - } - }; - server.start(); - countServerDownLatch.await(); - webSocket.connectBlocking(); - switch (testCase) { - case 0: - case 4: - byte[] bArray = new byte[10]; - for (byte i = 0; i < 10; i++) { - bArray[i] = i; - } - webSocket.send(ByteBuffer.wrap(bArray)); - if (testCase == 0) - countReceiveDownLatch.await(); - if (testCase == 4) - countCloseDownLatch.await(); - break; - case 2: - case 6: - bArray = "0123456789".getBytes(); - webSocket.send(ByteBuffer.wrap(bArray)); - if (testCase == 2) - countReceiveDownLatch.await(); - if (testCase == 6) - countCloseDownLatch.await(); - break; - case 1: - case 5: - bArray = new byte[2]; - for (byte i = 0; i < 10; i++) { - bArray[i%2] = i; - if (i % 2 == 1) - webSocket.sendFragmentedFrame(Opcode.BINARY, ByteBuffer.wrap(bArray), i == 9); - } - if (testCase == 1) - countReceiveDownLatch.await(); - if (testCase == 5) - countCloseDownLatch.await(); - break; - case 3: - case 7: - for (byte i = 0; i < 10; i++) { - webSocket.sendFragmentedFrame(Opcode.TEXT, ByteBuffer.wrap((Integer.toString(i)).getBytes()), i == 9); - } - if (testCase == 3) - countReceiveDownLatch.await(); - if (testCase == 7) - countCloseDownLatch.await(); - break; - } - server.stop(); - } - - @Test(timeout = 2000) - public void runBelowLimitBytebuffer() throws Exception { - runTestScenario(0); - } - - @Test(timeout = 2000) - public void runBelowSplitLimitBytebuffer() throws Exception { - runTestScenario(1); - } - - @Test(timeout = 2000) - public void runBelowLimitString() throws Exception { - runTestScenario(2); - } - - @Test(timeout = 2000) - public void runBelowSplitLimitString() throws Exception { - runTestScenario(3); - } - - @Test - //(timeout = 2000) - public void runAboveLimitBytebuffer() throws Exception { - runTestScenario(4); - } - - @Test(timeout = 2000) - public void runAboveSplitLimitBytebuffer() throws Exception { - runTestScenario(5); - } - - @Test(timeout = 2000) - public void runAboveLimitString() throws Exception { - runTestScenario(6); - } - - @Test(timeout = 2000) - public void runAboveSplitLimitString() throws Exception { - runTestScenario(7); - } + private static List protocolList = Collections.singletonList( + new Protocol("")); + private static List extensionList = Collections.emptyList(); + + private static void runTestScenario(int testCase) throws Exception { + final CountDownLatch countServerDownLatch = new CountDownLatch(1); + final CountDownLatch countReceiveDownLatch = new CountDownLatch(1); + final CountDownLatch countCloseDownLatch = new CountDownLatch(1); + int port = SocketUtil.getAvailablePort(); + Draft draft = null; + switch (testCase) { + case 0: + case 1: + case 2: + case 3: + draft = new Draft_6455(extensionList, protocolList, 10); + break; + case 4: + case 5: + case 6: + case 7: + draft = new Draft_6455(extensionList, protocolList, 9); + break; + } + WebSocketClient webSocket = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + + } + + @Override + public void onMessage(String message) { + } + + + @Override + public void onClose(int code, String reason, boolean remote) { + + } + + @Override + public void onError(Exception ex) { + + } + }; + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port), + Collections.singletonList(draft)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + if (code == CloseFrame.TOOBIG) { + countCloseDownLatch.countDown(); + } + } + + @Override + public void onMessage(WebSocket conn, String message) { + countReceiveDownLatch.countDown(); + } + + @Override + public void onMessage(WebSocket conn, ByteBuffer message) { + countReceiveDownLatch.countDown(); + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + }; + server.start(); + countServerDownLatch.await(); + webSocket.connectBlocking(); + switch (testCase) { + case 0: + case 4: + byte[] bArray = new byte[10]; + for (byte i = 0; i < 10; i++) { + bArray[i] = i; + } + webSocket.send(ByteBuffer.wrap(bArray)); + if (testCase == 0) { + countReceiveDownLatch.await(); + } + if (testCase == 4) { + countCloseDownLatch.await(); + } + break; + case 2: + case 6: + bArray = "0123456789".getBytes(); + webSocket.send(ByteBuffer.wrap(bArray)); + if (testCase == 2) { + countReceiveDownLatch.await(); + } + if (testCase == 6) { + countCloseDownLatch.await(); + } + break; + case 1: + case 5: + bArray = new byte[2]; + for (byte i = 0; i < 10; i++) { + bArray[i % 2] = i; + if (i % 2 == 1) { + webSocket.sendFragmentedFrame(Opcode.BINARY, ByteBuffer.wrap(bArray), i == 9); + } + } + if (testCase == 1) { + countReceiveDownLatch.await(); + } + if (testCase == 5) { + countCloseDownLatch.await(); + } + break; + case 3: + case 7: + for (byte i = 0; i < 10; i++) { + webSocket + .sendFragmentedFrame(Opcode.TEXT, ByteBuffer.wrap((Integer.toString(i)).getBytes()), + i == 9); + } + if (testCase == 3) { + countReceiveDownLatch.await(); + } + if (testCase == 7) { + countCloseDownLatch.await(); + } + break; + } + server.stop(); + } + + @Test(timeout = 2000) + public void runBelowLimitBytebuffer() throws Exception { + runTestScenario(0); + } + + @Test(timeout = 2000) + public void runBelowSplitLimitBytebuffer() throws Exception { + runTestScenario(1); + } + + @Test(timeout = 2000) + public void runBelowLimitString() throws Exception { + runTestScenario(2); + } + + @Test(timeout = 2000) + public void runBelowSplitLimitString() throws Exception { + runTestScenario(3); + } + + @Test + //(timeout = 2000) + public void runAboveLimitBytebuffer() throws Exception { + runTestScenario(4); + } + + @Test(timeout = 2000) + public void runAboveSplitLimitBytebuffer() throws Exception { + runTestScenario(5); + } + + @Test(timeout = 2000) + public void runAboveLimitString() throws Exception { + runTestScenario(6); + } + + @Test(timeout = 2000) + public void runAboveSplitLimitString() throws Exception { + runTestScenario(7); + } } diff --git a/src/test/java/org/java_websocket/issues/Issue609Test.java b/src/test/java/org/java_websocket/issues/Issue609Test.java index 3e605fd92..51b7f58b7 100644 --- a/src/test/java/org/java_websocket/issues/Issue609Test.java +++ b/src/test/java/org/java_websocket/issues/Issue609Test.java @@ -41,71 +41,71 @@ public class Issue609Test { - CountDownLatch countDownLatch = new CountDownLatch( 1 ); - CountDownLatch countServerDownLatch = new CountDownLatch( 1 ); - - boolean wasOpenClient; - boolean wasOpenServer; - - @Test - public void testIssue() throws Exception { - int port = SocketUtil.getAvailablePort(); - WebSocketClient webSocket = new WebSocketClient( new URI( "ws://localhost:" + port ) ) { - @Override - public void onOpen( ServerHandshake handshakedata ) { - - } - - @Override - public void onMessage( String message ) { - - } - - @Override - public void onClose( int code, String reason, boolean remote ) { - wasOpenClient = isOpen(); - countDownLatch.countDown(); - } - - @Override - public void onError( Exception ex ) { - - } - }; - WebSocketServer server = new WebSocketServer( new InetSocketAddress( port ) ) { - @Override - public void onOpen( WebSocket conn, ClientHandshake handshake ) { - } - - @Override - public void onClose( WebSocket conn, int code, String reason, boolean remote ) { - wasOpenServer = conn.isOpen(); - } - - @Override - public void onMessage( WebSocket conn, String message ) { - - } - - @Override - public void onError( WebSocket conn, Exception ex ) { - - } - - @Override - public void onStart() { - countServerDownLatch.countDown(); - } - }; - server.start(); - countServerDownLatch.await(); - webSocket.connectBlocking(); - assertTrue( "webSocket.isOpen()", webSocket.isOpen() ); - webSocket.getSocket().close(); - countDownLatch.await(); - assertTrue( "!webSocket.isOpen()", !webSocket.isOpen() ); - assertTrue( "!wasOpenClient", !wasOpenClient ); - assertTrue( "!wasOpenServer", !wasOpenServer ); - server.stop(); - } + CountDownLatch countDownLatch = new CountDownLatch(1); + CountDownLatch countServerDownLatch = new CountDownLatch(1); + + boolean wasOpenClient; + boolean wasOpenServer; + + @Test + public void testIssue() throws Exception { + int port = SocketUtil.getAvailablePort(); + WebSocketClient webSocket = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + + } + + @Override + public void onMessage(String message) { + + } + + @Override + public void onClose(int code, String reason, boolean remote) { + wasOpenClient = isOpen(); + countDownLatch.countDown(); + } + + @Override + public void onError(Exception ex) { + + } + }; + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + wasOpenServer = conn.isOpen(); + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + }; + server.start(); + countServerDownLatch.await(); + webSocket.connectBlocking(); + assertTrue("webSocket.isOpen()", webSocket.isOpen()); + webSocket.getSocket().close(); + countDownLatch.await(); + assertTrue("!webSocket.isOpen()", !webSocket.isOpen()); + assertTrue("!wasOpenClient", !wasOpenClient); + assertTrue("!wasOpenServer", !wasOpenServer); + server.stop(); + } } diff --git a/src/test/java/org/java_websocket/issues/Issue621Test.java b/src/test/java/org/java_websocket/issues/Issue621Test.java index a76256a7a..11cca8e9f 100644 --- a/src/test/java/org/java_websocket/issues/Issue621Test.java +++ b/src/test/java/org/java_websocket/issues/Issue621Test.java @@ -43,78 +43,79 @@ public class Issue621Test { - CountDownLatch countDownLatch = new CountDownLatch( 1 ); - CountDownLatch countServerDownLatch = new CountDownLatch( 1 ); - - boolean wasError = false; - - class TestPrintStream extends PrintStream { - public TestPrintStream( OutputStream out ) { - super( out ); - } - - @Override - public void println( Object o ) { - wasError = true; - super.println( o ); - } - } - - @Test - public void testIssue() throws Exception { - System.setErr( new TestPrintStream( System.err ) ); - int port = SocketUtil.getAvailablePort(); - WebSocketClient webSocket = new WebSocketClient( new URI( "ws://localhost:" + port ) ) { - @Override - public void onOpen( ServerHandshake handshakedata ) { - - } - - @Override - public void onMessage( String message ) { - - } - - @Override - public void onClose( int code, String reason, boolean remote ) { - countDownLatch.countDown(); - } - - @Override - public void onError( Exception ex ) { - - } - }; - WebSocketServer server = new WebSocketServer( new InetSocketAddress( port ) ) { - @Override - public void onOpen( WebSocket conn, ClientHandshake handshake ) { - conn.close(); - } - - @Override - public void onClose( WebSocket conn, int code, String reason, boolean remote ) { - } - - @Override - public void onMessage( WebSocket conn, String message ) { - - } - - @Override - public void onError( WebSocket conn, Exception ex ) { - - } - - @Override - public void onStart() { - countServerDownLatch.countDown(); - } - }; - server.start(); - countServerDownLatch.await(); - webSocket.connectBlocking(); - countDownLatch.await(); - assertTrue( "There was an error using System.err", !wasError ); - server.stop(); - } + CountDownLatch countDownLatch = new CountDownLatch(1); + CountDownLatch countServerDownLatch = new CountDownLatch(1); + + boolean wasError = false; + + class TestPrintStream extends PrintStream { + + public TestPrintStream(OutputStream out) { + super(out); + } + + @Override + public void println(Object o) { + wasError = true; + super.println(o); + } + } + + @Test + public void testIssue() throws Exception { + System.setErr(new TestPrintStream(System.err)); + int port = SocketUtil.getAvailablePort(); + WebSocketClient webSocket = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + + } + + @Override + public void onMessage(String message) { + + } + + @Override + public void onClose(int code, String reason, boolean remote) { + countDownLatch.countDown(); + } + + @Override + public void onError(Exception ex) { + + } + }; + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + conn.close(); + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + }; + server.start(); + countServerDownLatch.await(); + webSocket.connectBlocking(); + countDownLatch.await(); + assertTrue("There was an error using System.err", !wasError); + server.stop(); + } } diff --git a/src/test/java/org/java_websocket/issues/Issue661Test.java b/src/test/java/org/java_websocket/issues/Issue661Test.java index cf5ba5bc8..0c8965e84 100644 --- a/src/test/java/org/java_websocket/issues/Issue661Test.java +++ b/src/test/java/org/java_websocket/issues/Issue661Test.java @@ -43,85 +43,85 @@ public class Issue661Test { - @Rule - public ThreadCheck zombies = new ThreadCheck(); - - private CountDownLatch countServerDownLatch = new CountDownLatch( 1 ); - - private boolean wasError = false; - private boolean wasBindException = false; - - @Test(timeout = 2000) - public void testIssue() throws Exception { - int port = SocketUtil.getAvailablePort(); - WebSocketServer server0 = new WebSocketServer(new InetSocketAddress(port)) { - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - fail("There should be no onOpen"); - } - - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - fail("There should be no onClose"); - } - - @Override - public void onMessage(WebSocket conn, String message) { - fail("There should be no onMessage"); - } - - @Override - public void onError(WebSocket conn, Exception ex) { - fail("There should be no onError!"); - } - - @Override - public void onStart() { - countServerDownLatch.countDown(); - } - }; - server0.start(); - try { - countServerDownLatch.await(); - } catch (InterruptedException e) { - // - } - WebSocketServer server1 = new WebSocketServer(new InetSocketAddress(port)) { - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - fail("There should be no onOpen"); - } - - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - fail("There should be no onClose"); - } - - @Override - public void onMessage(WebSocket conn, String message) { - fail("There should be no onMessage"); - } - - @Override - public void onError(WebSocket conn, Exception ex) { - if (ex instanceof BindException){ - wasBindException = true; - } else { - wasError = true; - } - } - - @Override - public void onStart() { - fail("There should be no onStart!"); - } - }; - server1.start(); - Thread.sleep(1000); - server1.stop(); - server0.stop(); - Thread.sleep(100); - assertFalse("There was an unexpected exception!", wasError); - assertTrue("There was no bind exception!", wasBindException); - } + @Rule + public ThreadCheck zombies = new ThreadCheck(); + + private CountDownLatch countServerDownLatch = new CountDownLatch(1); + + private boolean wasError = false; + private boolean wasBindException = false; + + @Test(timeout = 2000) + public void testIssue() throws Exception { + int port = SocketUtil.getAvailablePort(); + WebSocketServer server0 = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + fail("There should be no onOpen"); + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + fail("There should be no onClose"); + } + + @Override + public void onMessage(WebSocket conn, String message) { + fail("There should be no onMessage"); + } + + @Override + public void onError(WebSocket conn, Exception ex) { + fail("There should be no onError!"); + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + }; + server0.start(); + try { + countServerDownLatch.await(); + } catch (InterruptedException e) { + // + } + WebSocketServer server1 = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + fail("There should be no onOpen"); + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + fail("There should be no onClose"); + } + + @Override + public void onMessage(WebSocket conn, String message) { + fail("There should be no onMessage"); + } + + @Override + public void onError(WebSocket conn, Exception ex) { + if (ex instanceof BindException) { + wasBindException = true; + } else { + wasError = true; + } + } + + @Override + public void onStart() { + fail("There should be no onStart!"); + } + }; + server1.start(); + Thread.sleep(1000); + server1.stop(); + server0.stop(); + Thread.sleep(100); + assertFalse("There was an unexpected exception!", wasError); + assertTrue("There was no bind exception!", wasBindException); + } } diff --git a/src/test/java/org/java_websocket/issues/Issue666Test.java b/src/test/java/org/java_websocket/issues/Issue666Test.java index 872ced59b..8c0fdb200 100644 --- a/src/test/java/org/java_websocket/issues/Issue666Test.java +++ b/src/test/java/org/java_websocket/issues/Issue666Test.java @@ -41,115 +41,118 @@ import java.util.concurrent.CountDownLatch; public class Issue666Test { - private CountDownLatch countServerDownLatch = new CountDownLatch( 1 ); - - @Test - public void testServer() throws Exception { - Map mapBefore = ThreadCheck.getThreadMap(); - int port = SocketUtil.getAvailablePort(); - WebSocketServer server = new WebSocketServer( new InetSocketAddress( port ) ) { - @Override - public void onOpen( WebSocket conn, ClientHandshake handshake ) { - } - - @Override - public void onClose( WebSocket conn, int code, String reason, boolean remote ) { - - } - - @Override - public void onMessage( WebSocket conn, String message ) { - - } - - @Override - public void onError( WebSocket conn, Exception ex ) { - - } - - @Override - public void onStart() { - countServerDownLatch.countDown(); - } - }; - server.start(); - countServerDownLatch.await(); - Map mapAfter = ThreadCheck.getThreadMap(); - for( long key : mapBefore.keySet() ) { - mapAfter.remove( key ); - } - for( Thread thread : mapAfter.values() ) { - String name = thread.getName(); - if( !name.startsWith( "WebSocketSelector-" ) && !name.startsWith( "WebSocketWorker-" ) && !name.startsWith( "connectionLostChecker-" ) ) { - Assert.fail( "Thread not correctly named! Is: " + name ); - } - } - server.stop(); - } - - @Test - public void testClient() throws Exception { - int port = SocketUtil.getAvailablePort(); - WebSocketClient client = new WebSocketClient( new URI( "ws://localhost:" + port ) ) { - @Override - public void onOpen( ServerHandshake handshakedata ) { - - } - - @Override - public void onMessage( String message ) { - - } - - @Override - public void onClose( int code, String reason, boolean remote ) { - } - - @Override - public void onError( Exception ex ) { - - } - }; - WebSocketServer server = new WebSocketServer( new InetSocketAddress( port ) ) { - @Override - public void onOpen( WebSocket conn, ClientHandshake handshake ) { - } - - @Override - public void onClose( WebSocket conn, int code, String reason, boolean remote ) { - - } - - @Override - public void onMessage( WebSocket conn, String message ) { - - } - - @Override - public void onError( WebSocket conn, Exception ex ) { - - } - - @Override - public void onStart() { - countServerDownLatch.countDown(); - } - }; - server.start(); - countServerDownLatch.await(); - Map mapBefore = ThreadCheck.getThreadMap(); - client.connectBlocking(); - Map mapAfter = ThreadCheck.getThreadMap(); - for( long key : mapBefore.keySet() ) { - mapAfter.remove( key ); - } - for( Thread thread : mapAfter.values() ) { - String name = thread.getName(); - if( !name.startsWith( "connectionLostChecker-" ) && !name.startsWith( "WebSocketWriteThread-" ) && !name.startsWith( "WebSocketConnectReadThread-" )) { - Assert.fail( "Thread not correctly named! Is: " + name ); - } - } - client.close(); - server.stop(); - } + + private CountDownLatch countServerDownLatch = new CountDownLatch(1); + + @Test + public void testServer() throws Exception { + Map mapBefore = ThreadCheck.getThreadMap(); + int port = SocketUtil.getAvailablePort(); + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + }; + server.start(); + countServerDownLatch.await(); + Map mapAfter = ThreadCheck.getThreadMap(); + for (long key : mapBefore.keySet()) { + mapAfter.remove(key); + } + for (Thread thread : mapAfter.values()) { + String name = thread.getName(); + if (!name.startsWith("WebSocketSelector-") && !name.startsWith("WebSocketWorker-") && !name + .startsWith("connectionLostChecker-")) { + Assert.fail("Thread not correctly named! Is: " + name); + } + } + server.stop(); + } + + @Test + public void testClient() throws Exception { + int port = SocketUtil.getAvailablePort(); + WebSocketClient client = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + + } + + @Override + public void onMessage(String message) { + + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + + } + }; + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + }; + server.start(); + countServerDownLatch.await(); + Map mapBefore = ThreadCheck.getThreadMap(); + client.connectBlocking(); + Map mapAfter = ThreadCheck.getThreadMap(); + for (long key : mapBefore.keySet()) { + mapAfter.remove(key); + } + for (Thread thread : mapAfter.values()) { + String name = thread.getName(); + if (!name.startsWith("connectionLostChecker-") && !name.startsWith("WebSocketWriteThread-") + && !name.startsWith("WebSocketConnectReadThread-")) { + Assert.fail("Thread not correctly named! Is: " + name); + } + } + client.close(); + server.stop(); + } } diff --git a/src/test/java/org/java_websocket/issues/Issue677Test.java b/src/test/java/org/java_websocket/issues/Issue677Test.java index 4a56957cf..39d8d16f1 100644 --- a/src/test/java/org/java_websocket/issues/Issue677Test.java +++ b/src/test/java/org/java_websocket/issues/Issue677Test.java @@ -42,87 +42,87 @@ public class Issue677Test { - CountDownLatch countDownLatch0 = new CountDownLatch( 1 ); - CountDownLatch countServerDownLatch = new CountDownLatch( 1 ); - - @Test - public void testIssue() throws Exception { - int port = SocketUtil.getAvailablePort(); - WebSocketClient webSocket0 = new WebSocketClient( new URI( "ws://localhost:" + port ) ) { - @Override - public void onOpen( ServerHandshake handshakedata ) { - - } - - @Override - public void onMessage( String message ) { - - } - - @Override - public void onClose( int code, String reason, boolean remote ) { - countDownLatch0.countDown(); - } - - @Override - public void onError( Exception ex ) { - - } - }; - WebSocketClient webSocket1 = new WebSocketClient( new URI( "ws://localhost:" + port ) ) { - @Override - public void onOpen( ServerHandshake handshakedata ) { - } - - @Override - public void onMessage( String message ) { - } - - @Override - public void onClose( int code, String reason, boolean remote ) { - } - - @Override - public void onError( Exception ex ) { - - } - }; - WebSocketServer server = new WebSocketServer( new InetSocketAddress( port ) ) { - @Override - public void onOpen( WebSocket conn, ClientHandshake handshake ) { - } - - @Override - public void onClose( WebSocket conn, int code, String reason, boolean remote ) { - } - - @Override - public void onMessage( WebSocket conn, String message ) { - - } - - @Override - public void onError( WebSocket conn, Exception ex ) { - - } - - @Override - public void onStart() { - countServerDownLatch.countDown(); - } - }; - server.start(); - countServerDownLatch.await(); - webSocket0.connectBlocking(); - assertTrue( "webSocket.isOpen()", webSocket0.isOpen() ); - webSocket0.close(); - assertTrue( "webSocket.isClosing()", webSocket0.isClosing() ); - countDownLatch0.await(); - assertTrue( "webSocket.isClosed()", webSocket0.isClosed() ); - webSocket1.connectBlocking(); - assertTrue( "webSocket.isOpen()", webSocket1.isOpen() ); - webSocket1.closeConnection(CloseFrame.ABNORMAL_CLOSE, "Abnormal close!"); - assertTrue( "webSocket.isClosed()", webSocket1.isClosed() ); - server.stop(); - } + CountDownLatch countDownLatch0 = new CountDownLatch(1); + CountDownLatch countServerDownLatch = new CountDownLatch(1); + + @Test + public void testIssue() throws Exception { + int port = SocketUtil.getAvailablePort(); + WebSocketClient webSocket0 = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + + } + + @Override + public void onMessage(String message) { + + } + + @Override + public void onClose(int code, String reason, boolean remote) { + countDownLatch0.countDown(); + } + + @Override + public void onError(Exception ex) { + + } + }; + WebSocketClient webSocket1 = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + } + + @Override + public void onMessage(String message) { + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + + } + }; + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + }; + server.start(); + countServerDownLatch.await(); + webSocket0.connectBlocking(); + assertTrue("webSocket.isOpen()", webSocket0.isOpen()); + webSocket0.close(); + assertTrue("webSocket.isClosing()", webSocket0.isClosing()); + countDownLatch0.await(); + assertTrue("webSocket.isClosed()", webSocket0.isClosed()); + webSocket1.connectBlocking(); + assertTrue("webSocket.isOpen()", webSocket1.isOpen()); + webSocket1.closeConnection(CloseFrame.ABNORMAL_CLOSE, "Abnormal close!"); + assertTrue("webSocket.isClosed()", webSocket1.isClosed()); + server.stop(); + } } diff --git a/src/test/java/org/java_websocket/issues/Issue713Test.java b/src/test/java/org/java_websocket/issues/Issue713Test.java index 6ed2f2e13..3121aa059 100644 --- a/src/test/java/org/java_websocket/issues/Issue713Test.java +++ b/src/test/java/org/java_websocket/issues/Issue713Test.java @@ -48,141 +48,142 @@ public class Issue713Test { - CountDownLatch countDownLatchString = new CountDownLatch( 10 ); - CountDownLatch countDownLatchConnect = new CountDownLatch( 10 ); - CountDownLatch countDownLatchBytebuffer = new CountDownLatch( 10 ); - - @Test - public void testIllegalArgument() throws IOException { - WebSocketServer server = new WebSocketServer( new InetSocketAddress( SocketUtil.getAvailablePort() ) ) { - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - - } - - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - - } - - @Override - public void onMessage(WebSocket conn, String message) { - - } - - @Override - public void onError(WebSocket conn, Exception ex) { - - } - - @Override - public void onStart() { - - } - }; - try { - server.broadcast((byte[]) null, null); - fail("IllegalArgumentException should be thrown"); - } catch (Exception e) { - // OK - } - try { - server.broadcast((String) null, null); - fail("IllegalArgumentException should be thrown"); - } catch (Exception e) { - // OK - } - } - - @Test(timeout=2000) - public void testIssue() throws Exception { - final int port = SocketUtil.getAvailablePort(); - WebSocketServer server = new WebSocketServer( new InetSocketAddress( port ) ) { - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake ) { - } - - @Override - public void onClose( WebSocket conn, int code, String reason, boolean remote ) { - } - - @Override - public void onMessage( WebSocket conn, String message ) { - - } - - @Override - public void onError( WebSocket conn, Exception ex ) { - - } - - @Override - public void onStart() { - try { - for (int i = 0; i < 10; i++) { - TestWebSocket tw = new TestWebSocket(port); - tw.connect(); - } - } catch (Exception e) { - fail("Exception during connect!"); - } - } - }; - server.start(); - countDownLatchConnect.await(); - server.broadcast("Hello world!"); - countDownLatchString.await(); - server.broadcast("Hello world".getBytes()); - countDownLatchBytebuffer.await(); - countDownLatchBytebuffer = new CountDownLatch( 10 ); - server.broadcast(ByteBuffer.wrap("Hello world".getBytes())); - countDownLatchBytebuffer.await(); - - - countDownLatchString = new CountDownLatch( 5 ); - ArrayList specialList = new ArrayList(server.getConnections()); - specialList.remove(8); - specialList.remove(6); - specialList.remove(4); - specialList.remove(2); - specialList.remove(0); - server.broadcast("Hello world", specialList); - countDownLatchString.await(); - - countDownLatchBytebuffer = new CountDownLatch( 5 ); - server.broadcast("Hello world".getBytes()); - countDownLatchBytebuffer.await(); - } - - - class TestWebSocket extends WebSocketClient { - - TestWebSocket(int port) throws URISyntaxException { - super(new URI( "ws://localhost:" + port)); - } - - @Override - public void onOpen( ServerHandshake handshakedata ) { - countDownLatchConnect.countDown(); - } - - @Override - public void onMessage( String message ) { - countDownLatchString.countDown(); - } - @Override - public void onMessage( ByteBuffer message ) { - countDownLatchBytebuffer.countDown(); - } - - @Override - public void onClose( int code, String reason, boolean remote ) { - - } - - @Override - public void onError( Exception ex ) { - - } - } + CountDownLatch countDownLatchString = new CountDownLatch(10); + CountDownLatch countDownLatchConnect = new CountDownLatch(10); + CountDownLatch countDownLatchBytebuffer = new CountDownLatch(10); + + @Test + public void testIllegalArgument() throws IOException { + WebSocketServer server = new WebSocketServer( + new InetSocketAddress(SocketUtil.getAvailablePort())) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + + } + }; + try { + server.broadcast((byte[]) null, null); + fail("IllegalArgumentException should be thrown"); + } catch (Exception e) { + // OK + } + try { + server.broadcast((String) null, null); + fail("IllegalArgumentException should be thrown"); + } catch (Exception e) { + // OK + } + } + + @Test(timeout = 2000) + public void testIssue() throws Exception { + final int port = SocketUtil.getAvailablePort(); + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + try { + for (int i = 0; i < 10; i++) { + TestWebSocket tw = new TestWebSocket(port); + tw.connect(); + } + } catch (Exception e) { + fail("Exception during connect!"); + } + } + }; + server.start(); + countDownLatchConnect.await(); + server.broadcast("Hello world!"); + countDownLatchString.await(); + server.broadcast("Hello world".getBytes()); + countDownLatchBytebuffer.await(); + countDownLatchBytebuffer = new CountDownLatch(10); + server.broadcast(ByteBuffer.wrap("Hello world".getBytes())); + countDownLatchBytebuffer.await(); + + countDownLatchString = new CountDownLatch(5); + ArrayList specialList = new ArrayList(server.getConnections()); + specialList.remove(8); + specialList.remove(6); + specialList.remove(4); + specialList.remove(2); + specialList.remove(0); + server.broadcast("Hello world", specialList); + countDownLatchString.await(); + + countDownLatchBytebuffer = new CountDownLatch(5); + server.broadcast("Hello world".getBytes()); + countDownLatchBytebuffer.await(); + } + + + class TestWebSocket extends WebSocketClient { + + TestWebSocket(int port) throws URISyntaxException { + super(new URI("ws://localhost:" + port)); + } + + @Override + public void onOpen(ServerHandshake handshakedata) { + countDownLatchConnect.countDown(); + } + + @Override + public void onMessage(String message) { + countDownLatchString.countDown(); + } + + @Override + public void onMessage(ByteBuffer message) { + countDownLatchBytebuffer.countDown(); + } + + @Override + public void onClose(int code, String reason, boolean remote) { + + } + + @Override + public void onError(Exception ex) { + + } + } } diff --git a/src/test/java/org/java_websocket/issues/Issue732Test.java b/src/test/java/org/java_websocket/issues/Issue732Test.java index 15a13f426..7a21ae51f 100644 --- a/src/test/java/org/java_websocket/issues/Issue732Test.java +++ b/src/test/java/org/java_websocket/issues/Issue732Test.java @@ -45,83 +45,83 @@ public class Issue732Test { - @Rule - public ThreadCheck zombies = new ThreadCheck(); + @Rule + public ThreadCheck zombies = new ThreadCheck(); - private CountDownLatch countServerDownLatch = new CountDownLatch(1); + private CountDownLatch countServerDownLatch = new CountDownLatch(1); - @Test(timeout = 2000) - public void testIssue() throws Exception { - int port = SocketUtil.getAvailablePort(); - final WebSocketClient webSocket = new WebSocketClient(new URI("ws://localhost:" + port)) { - @Override - public void onOpen(ServerHandshake handshakedata) { - try { - this.reconnect(); - Assert.fail("Exception should be thrown"); - } catch (IllegalStateException e) { - // - } - } + @Test(timeout = 2000) + public void testIssue() throws Exception { + int port = SocketUtil.getAvailablePort(); + final WebSocketClient webSocket = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + try { + this.reconnect(); + Assert.fail("Exception should be thrown"); + } catch (IllegalStateException e) { + // + } + } - @Override - public void onMessage(String message) { - try { - this.reconnect(); - Assert.fail("Exception should be thrown"); - } catch (IllegalStateException e) { - send("hi"); - } - } + @Override + public void onMessage(String message) { + try { + this.reconnect(); + Assert.fail("Exception should be thrown"); + } catch (IllegalStateException e) { + send("hi"); + } + } - @Override - public void onClose(int code, String reason, boolean remote) { - try { - this.reconnect(); - Assert.fail("Exception should be thrown"); - } catch (IllegalStateException e) { - // - } - } + @Override + public void onClose(int code, String reason, boolean remote) { + try { + this.reconnect(); + Assert.fail("Exception should be thrown"); + } catch (IllegalStateException e) { + // + } + } - @Override - public void onError(Exception ex) { - try { - this.reconnect(); - Assert.fail("Exception should be thrown"); - } catch (IllegalStateException e) { - // - } - } - }; - WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - conn.send("hi"); - } + @Override + public void onError(Exception ex) { + try { + this.reconnect(); + Assert.fail("Exception should be thrown"); + } catch (IllegalStateException e) { + // + } + } + }; + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + conn.send("hi"); + } - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - countServerDownLatch.countDown(); - } + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + countServerDownLatch.countDown(); + } - @Override - public void onMessage(WebSocket conn, String message) { - conn.close(); - } + @Override + public void onMessage(WebSocket conn, String message) { + conn.close(); + } - @Override - public void onError(WebSocket conn, Exception ex) { - fail("There should be no onError!"); - } + @Override + public void onError(WebSocket conn, Exception ex) { + fail("There should be no onError!"); + } - @Override - public void onStart() { - webSocket.connect(); - } - }; - server.start(); - countServerDownLatch.await(); - server.stop(); - } + @Override + public void onStart() { + webSocket.connect(); + } + }; + server.start(); + countServerDownLatch.await(); + server.stop(); + } } diff --git a/src/test/java/org/java_websocket/issues/Issue764Test.java b/src/test/java/org/java_websocket/issues/Issue764Test.java index b0d265286..ff84c2176 100644 --- a/src/test/java/org/java_websocket/issues/Issue764Test.java +++ b/src/test/java/org/java_websocket/issues/Issue764Test.java @@ -50,77 +50,81 @@ import java.util.concurrent.CountDownLatch; public class Issue764Test { - private CountDownLatch countClientDownLatch = new CountDownLatch(2); - private CountDownLatch countServerDownLatch = new CountDownLatch(1); - - @Test(timeout = 2000) - public void testIssue() throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { - int port = SocketUtil.getAvailablePort(); - final WebSocketClient webSocket = new WebSocketClient(new URI("wss://localhost:" + port)) { - @Override - public void onOpen(ServerHandshake handshakedata) { - countClientDownLatch.countDown(); - countServerDownLatch.countDown(); - } - - @Override - public void onMessage(String message) { - } - - @Override - public void onClose(int code, String reason, boolean remote) { - } - - @Override - public void onError(Exception ex) { - } - }; - WebSocketServer server = new MyWebSocketServer(port, webSocket, countServerDownLatch); - - SSLContext sslContext = SSLContextUtil.getContext(); - - server.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext)); - webSocket.setSocketFactory(sslContext.getSocketFactory()); - server.start(); - countServerDownLatch.await(); - webSocket.connectBlocking(); - webSocket.reconnectBlocking(); - countClientDownLatch.await(); - } - - - private static class MyWebSocketServer extends WebSocketServer { - private final WebSocketClient webSocket; - private final CountDownLatch countServerDownLatch; + private CountDownLatch countClientDownLatch = new CountDownLatch(2); + private CountDownLatch countServerDownLatch = new CountDownLatch(1); + + @Test(timeout = 2000) + public void testIssue() + throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { + int port = SocketUtil.getAvailablePort(); + final WebSocketClient webSocket = new WebSocketClient(new URI("wss://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + countClientDownLatch.countDown(); + countServerDownLatch.countDown(); + } + + @Override + public void onMessage(String message) { + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + } + }; + WebSocketServer server = new MyWebSocketServer(port, webSocket, countServerDownLatch); + + SSLContext sslContext = SSLContextUtil.getContext(); + + server.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext)); + webSocket.setSocketFactory(sslContext.getSocketFactory()); + server.start(); + countServerDownLatch.await(); + webSocket.connectBlocking(); + webSocket.reconnectBlocking(); + countClientDownLatch.await(); + } + + + private static class MyWebSocketServer extends WebSocketServer { + + private final WebSocketClient webSocket; + private final CountDownLatch countServerDownLatch; + + + public MyWebSocketServer(int port, WebSocketClient webSocket, + CountDownLatch countServerDownLatch) { + super(new InetSocketAddress(port)); + this.webSocket = webSocket; + this.countServerDownLatch = countServerDownLatch; + } - public MyWebSocketServer(int port, WebSocketClient webSocket, CountDownLatch countServerDownLatch) { - super(new InetSocketAddress(port)); - this.webSocket = webSocket; - this.countServerDownLatch = countServerDownLatch; - } - - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - } + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - } + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } - @Override - public void onMessage(WebSocket conn, String message) { + @Override + public void onMessage(WebSocket conn, String message) { - } + } - @Override - public void onError(WebSocket conn, Exception ex) { - ex.printStackTrace(); - } + @Override + public void onError(WebSocket conn, Exception ex) { + ex.printStackTrace(); + } - @Override - public void onStart() { - countServerDownLatch.countDown(); - } + @Override + public void onStart() { + countServerDownLatch.countDown(); } + } } diff --git a/src/test/java/org/java_websocket/issues/Issue765Test.java b/src/test/java/org/java_websocket/issues/Issue765Test.java index b6fc39ffc..44a43ccfa 100644 --- a/src/test/java/org/java_websocket/issues/Issue765Test.java +++ b/src/test/java/org/java_websocket/issues/Issue765Test.java @@ -44,62 +44,65 @@ public class Issue765Test { - boolean isClosedCalled = false; - @Test - public void testIssue() { - WebSocketServer webSocketServer = new MyWebSocketServer(); - webSocketServer.setWebSocketFactory(new LocalWebSocketFactory()); - Assert.assertFalse("Close should not have been called yet",isClosedCalled); - webSocketServer.setWebSocketFactory(new LocalWebSocketFactory()); - Assert.assertTrue("Close has been called", isClosedCalled); + boolean isClosedCalled = false; + + @Test + public void testIssue() { + WebSocketServer webSocketServer = new MyWebSocketServer(); + webSocketServer.setWebSocketFactory(new LocalWebSocketFactory()); + Assert.assertFalse("Close should not have been called yet", isClosedCalled); + webSocketServer.setWebSocketFactory(new LocalWebSocketFactory()); + Assert.assertTrue("Close has been called", isClosedCalled); + } + + private static class MyWebSocketServer extends WebSocketServer { + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } - private static class MyWebSocketServer extends WebSocketServer { - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { + @Override + public void onMessage(WebSocket conn, String message) { - } + } - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { + @Override + public void onError(WebSocket conn, Exception ex) { - } + } - @Override - public void onMessage(WebSocket conn, String message) { + @Override + public void onStart() { - } + } + } - @Override - public void onError(WebSocket conn, Exception ex) { + private class LocalWebSocketFactory implements WebSocketServerFactory { - } + @Override + public WebSocketImpl createWebSocket(WebSocketAdapter a, Draft d) { + return null; + } - @Override - public void onStart() { + @Override + public WebSocketImpl createWebSocket(WebSocketAdapter a, List drafts) { + return null; + } - } + @Override + public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException { + return null; } - private class LocalWebSocketFactory implements WebSocketServerFactory { - @Override - public WebSocketImpl createWebSocket(WebSocketAdapter a, Draft d) { - return null; - } - - @Override - public WebSocketImpl createWebSocket(WebSocketAdapter a, List drafts) { - return null; - } - - @Override - public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException { - return null; - } - - @Override - public void close() { - isClosedCalled = true; - } + @Override + public void close() { + isClosedCalled = true; } + } } diff --git a/src/test/java/org/java_websocket/issues/Issue811Test.java b/src/test/java/org/java_websocket/issues/Issue811Test.java index c6ebca0bd..e54e5e7c7 100644 --- a/src/test/java/org/java_websocket/issues/Issue811Test.java +++ b/src/test/java/org/java_websocket/issues/Issue811Test.java @@ -37,55 +37,58 @@ import java.util.concurrent.CountDownLatch; public class Issue811Test { - private CountDownLatch countServerDownLatch = new CountDownLatch(1); - - @Test(timeout = 2000) - public void testSetConnectionLostTimeout() throws IOException, InterruptedException { - final MyWebSocketServer server = new MyWebSocketServer(new InetSocketAddress(SocketUtil.getAvailablePort())); - server.start(); - new Thread(new Runnable() { - @Override - public void run() { - while (server.getConnectionLostTimeout() == 60) { - // do nothing - } - // will never reach this statement - countServerDownLatch.countDown(); - } - }).start(); - Thread.sleep(1000); - server.setConnectionLostTimeout(20); - countServerDownLatch.await(); - } - private static class MyWebSocketServer extends WebSocketServer { - public MyWebSocketServer(InetSocketAddress inetSocketAddress) { - super(inetSocketAddress); + private CountDownLatch countServerDownLatch = new CountDownLatch(1); + + @Test(timeout = 2000) + public void testSetConnectionLostTimeout() throws IOException, InterruptedException { + final MyWebSocketServer server = new MyWebSocketServer( + new InetSocketAddress(SocketUtil.getAvailablePort())); + server.start(); + new Thread(new Runnable() { + @Override + public void run() { + while (server.getConnectionLostTimeout() == 60) { + // do nothing } + // will never reach this statement + countServerDownLatch.countDown(); + } + }).start(); + Thread.sleep(1000); + server.setConnectionLostTimeout(20); + countServerDownLatch.await(); + } + + private static class MyWebSocketServer extends WebSocketServer { + + public MyWebSocketServer(InetSocketAddress inetSocketAddress) { + super(inetSocketAddress); + } - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { - } + } - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { - } + } - @Override - public void onMessage(WebSocket conn, String message) { + @Override + public void onMessage(WebSocket conn, String message) { - } + } - @Override - public void onError(WebSocket conn, Exception ex) { + @Override + public void onError(WebSocket conn, Exception ex) { - } + } - @Override - public void onStart() { + @Override + public void onStart() { - } } + } } diff --git a/src/test/java/org/java_websocket/issues/Issue825Test.java b/src/test/java/org/java_websocket/issues/Issue825Test.java index b427e8fa2..c56481da5 100644 --- a/src/test/java/org/java_websocket/issues/Issue825Test.java +++ b/src/test/java/org/java_websocket/issues/Issue825Test.java @@ -52,91 +52,95 @@ public class Issue825Test { - @Test(timeout = 15000) - public void testIssue() throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { - final CountDownLatch countClientOpenLatch = new CountDownLatch(3); - final CountDownLatch countClientMessageLatch = new CountDownLatch(3); - final CountDownLatch countServerDownLatch = new CountDownLatch(1); - int port = SocketUtil.getAvailablePort(); - final WebSocketClient webSocket = new WebSocketClient(new URI("wss://localhost:" + port)) { - @Override - public void onOpen(ServerHandshake handshakedata) { - countClientOpenLatch.countDown(); - } - - @Override - public void onMessage(String message) { - } - - @Override - public void onClose(int code, String reason, boolean remote) { - } - - @Override - public void onError(Exception ex) { - } - }; - WebSocketServer server = new MyWebSocketServer(port, countServerDownLatch, countClientMessageLatch); - - // load up the key store - SSLContext sslContext = SSLContextUtil.getContext(); - - server.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext)); - webSocket.setSocketFactory(sslContext.getSocketFactory()); - server.start(); - countServerDownLatch.await(); - webSocket.connectBlocking(); - webSocket.send( "hi" ); - Thread.sleep( 10 ); - webSocket.closeBlocking(); - - //Disconnect manually and reconnect blocking - webSocket.reconnectBlocking(); - webSocket.send( "it's" ); - Thread.sleep( 10000 ); - webSocket.closeBlocking(); - //Disconnect manually and reconnect - webSocket.reconnect(); - countClientOpenLatch.await(); - webSocket.send( "me" ); - Thread.sleep( 100 ); - webSocket.closeBlocking(); - countClientMessageLatch.await(); + @Test(timeout = 15000) + public void testIssue() + throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { + final CountDownLatch countClientOpenLatch = new CountDownLatch(3); + final CountDownLatch countClientMessageLatch = new CountDownLatch(3); + final CountDownLatch countServerDownLatch = new CountDownLatch(1); + int port = SocketUtil.getAvailablePort(); + final WebSocketClient webSocket = new WebSocketClient(new URI("wss://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + countClientOpenLatch.countDown(); + } + + @Override + public void onMessage(String message) { + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + } + }; + WebSocketServer server = new MyWebSocketServer(port, countServerDownLatch, + countClientMessageLatch); + + // load up the key store + SSLContext sslContext = SSLContextUtil.getContext(); + + server.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext)); + webSocket.setSocketFactory(sslContext.getSocketFactory()); + server.start(); + countServerDownLatch.await(); + webSocket.connectBlocking(); + webSocket.send("hi"); + Thread.sleep(10); + webSocket.closeBlocking(); + + //Disconnect manually and reconnect blocking + webSocket.reconnectBlocking(); + webSocket.send("it's"); + Thread.sleep(10000); + webSocket.closeBlocking(); + //Disconnect manually and reconnect + webSocket.reconnect(); + countClientOpenLatch.await(); + webSocket.send("me"); + Thread.sleep(100); + webSocket.closeBlocking(); + countClientMessageLatch.await(); + } + + + private static class MyWebSocketServer extends WebSocketServer { + + private final CountDownLatch countServerLatch; + private final CountDownLatch countClientMessageLatch; + + + public MyWebSocketServer(int port, CountDownLatch serverDownLatch, + CountDownLatch countClientMessageLatch) { + super(new InetSocketAddress(port)); + this.countServerLatch = serverDownLatch; + this.countClientMessageLatch = countClientMessageLatch; } + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } - private static class MyWebSocketServer extends WebSocketServer { - private final CountDownLatch countServerLatch; - private final CountDownLatch countClientMessageLatch; - - - public MyWebSocketServer(int port, CountDownLatch serverDownLatch, CountDownLatch countClientMessageLatch) { - super(new InetSocketAddress(port)); - this.countServerLatch = serverDownLatch; - this.countClientMessageLatch = countClientMessageLatch; - } - - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - } - - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - } + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } - @Override - public void onMessage(WebSocket conn, String message) { - countClientMessageLatch.countDown(); - } + @Override + public void onMessage(WebSocket conn, String message) { + countClientMessageLatch.countDown(); + } - @Override - public void onError(WebSocket conn, Exception ex) { - ex.printStackTrace(); - } + @Override + public void onError(WebSocket conn, Exception ex) { + ex.printStackTrace(); + } - @Override - public void onStart() { - countServerLatch.countDown(); - } + @Override + public void onStart() { + countServerLatch.countDown(); } + } } diff --git a/src/test/java/org/java_websocket/issues/Issue834Test.java b/src/test/java/org/java_websocket/issues/Issue834Test.java index b7753dfa1..434f53d05 100644 --- a/src/test/java/org/java_websocket/issues/Issue834Test.java +++ b/src/test/java/org/java_websocket/issues/Issue834Test.java @@ -13,38 +13,38 @@ public class Issue834Test { - @Test(timeout = 1000) - public void testNoNewThreads() throws IOException { + @Test(timeout = 1000) + public void testNoNewThreads() throws IOException { - Set threadSet1 = Thread.getAllStackTraces().keySet(); + Set threadSet1 = Thread.getAllStackTraces().keySet(); - new WebSocketServer(new InetSocketAddress(SocketUtil.getAvailablePort())) { - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - } + new WebSocketServer(new InetSocketAddress(SocketUtil.getAvailablePort())) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - } + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } - @Override - public void onMessage(WebSocket conn, String message) { - } + @Override + public void onMessage(WebSocket conn, String message) { + } - @Override - public void onError(WebSocket conn, Exception ex) { - } + @Override + public void onError(WebSocket conn, Exception ex) { + } - @Override - public void onStart() { - } - }; + @Override + public void onStart() { + } + }; - Set threadSet2 = Thread.getAllStackTraces().keySet(); + Set threadSet2 = Thread.getAllStackTraces().keySet(); - //checks that no threads are started in the constructor - Assert.assertEquals(threadSet1, threadSet2); + //checks that no threads are started in the constructor + Assert.assertEquals(threadSet1, threadSet2); - } + } } diff --git a/src/test/java/org/java_websocket/issues/Issue847Test.java b/src/test/java/org/java_websocket/issues/Issue847Test.java index b2f7ffd04..46b882cc6 100644 --- a/src/test/java/org/java_websocket/issues/Issue847Test.java +++ b/src/test/java/org/java_websocket/issues/Issue847Test.java @@ -55,134 +55,140 @@ @RunWith(Parameterized.class) public class Issue847Test { - private static Thread thread; - private static ServerSocket serverSocket; - - private static int port; - private static final int NUMBER_OF_TESTS = 20; - - @Parameterized.Parameter - public int size; - - @Parameterized.Parameters - public static Collection data() { - List ret = new ArrayList(NUMBER_OF_TESTS); - for (int i = 1; i <= NUMBER_OF_TESTS+1; i++) ret.add(new Integer[]{(int)Math.round(Math.pow(2, i))}); - return ret; - } - - @BeforeClass - public static void startServer() throws Exception { - port = SocketUtil.getAvailablePort(); - thread = new Thread( - new Runnable() { - public void run() { - try { - serverSocket = new ServerSocket( port ); - serverSocket.setReuseAddress( true ); - while( true ) { - Socket client = null; - try { - client = serverSocket.accept(); - Scanner in = new Scanner( client.getInputStream() ); - String input; - String seckey = ""; - String testCase; - boolean useMask = false; - int size = 0; - OutputStream os = client.getOutputStream(); - while( in.hasNext() ) { - input = in.nextLine(); - if( input.startsWith( "Sec-WebSocket-Key: " ) ) { - seckey = input.split( " " )[1]; - } - //Last - if( input.startsWith( "Upgrade" ) ) { - os.write(Charsetfunctions.asciiBytes("HTTP/1.1 101 Websocket Connection Upgrade\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + KeyUtils.getSecKey(seckey) + "\r\n")); - os.flush(); - Thread.sleep(10); - Draft_6455 draft_6455 = new Draft_6455(); - BinaryFrame binaryFrame = new BinaryFrame(); - binaryFrame.setPayload(ByteBuffer.allocate(size)); - binaryFrame.setTransferemasked(useMask); - ByteBuffer byteBuffer = draft_6455.createBinaryFrame(binaryFrame); - byte[] bytes = byteBuffer.array(); - int first = size/2; - os.write(bytes, 0, first); - os.flush(); - Thread.sleep(5); - os.write(bytes, first, bytes.length-first); - os.flush(); - break; - } - if( input.startsWith( "GET " ) ) { - testCase = input.split(" ")[1]; - String[] strings = testCase.split("/"); - useMask = Boolean.valueOf(strings[1]); - size = Integer.valueOf(strings[2]); - } - } - } catch ( IOException e ) { - // - } - } - } catch ( Exception e ) { - e.printStackTrace(); - fail( "There should be no exception" ); - } - } - } ); - thread.start(); - } - - @AfterClass - public static void successTests() throws IOException { - serverSocket.close(); - thread.interrupt(); - } - - @Test(timeout = 5000) - public void testIncrementalFrameUnmasked() throws Exception { - testIncrementalFrame( false, size ); - } - - @Test(timeout = 5000) - public void testIncrementalFrameMsked() throws Exception { - testIncrementalFrame( true, size ); - } - - - private void testIncrementalFrame(boolean useMask, int size ) throws Exception { - final boolean[] threadReturned = { false }; - final WebSocketClient webSocketClient = new WebSocketClient( new URI( "ws://localhost:"+ port + "/" + useMask + "/" + size ) ) { - @Override - public void onOpen( ServerHandshake handshakedata ) { - } - - @Override - public void onMessage( String message ) { - fail( "There should not be a message!" ); - } - public void onMessage( ByteBuffer message ) { - threadReturned[0] = true; - close(); - } - - @Override - public void onClose( int code, String reason, boolean remote ) { - } - - @Override - public void onError( Exception ex ) { - ex.printStackTrace(); - } - }; - Thread finalThread = new Thread( webSocketClient ); - finalThread.start(); - finalThread.join(); - if( !threadReturned[0] ) { - fail( "Error" ); - } - } + private static Thread thread; + private static ServerSocket serverSocket; + + private static int port; + private static final int NUMBER_OF_TESTS = 20; + + @Parameterized.Parameter + public int size; + + @Parameterized.Parameters + public static Collection data() { + List ret = new ArrayList(NUMBER_OF_TESTS); + for (int i = 1; i <= NUMBER_OF_TESTS + 1; i++) { + ret.add(new Integer[]{(int) Math.round(Math.pow(2, i))}); + } + return ret; + } + + @BeforeClass + public static void startServer() throws Exception { + port = SocketUtil.getAvailablePort(); + thread = new Thread( + new Runnable() { + public void run() { + try { + serverSocket = new ServerSocket(port); + serverSocket.setReuseAddress(true); + while (true) { + Socket client = null; + try { + client = serverSocket.accept(); + Scanner in = new Scanner(client.getInputStream()); + String input; + String seckey = ""; + String testCase; + boolean useMask = false; + int size = 0; + OutputStream os = client.getOutputStream(); + while (in.hasNext()) { + input = in.nextLine(); + if (input.startsWith("Sec-WebSocket-Key: ")) { + seckey = input.split(" ")[1]; + } + //Last + if (input.startsWith("Upgrade")) { + os.write(Charsetfunctions.asciiBytes( + "HTTP/1.1 101 Websocket Connection Upgrade\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + + KeyUtils.getSecKey(seckey) + "\r\n")); + os.flush(); + Thread.sleep(10); + Draft_6455 draft_6455 = new Draft_6455(); + BinaryFrame binaryFrame = new BinaryFrame(); + binaryFrame.setPayload(ByteBuffer.allocate(size)); + binaryFrame.setTransferemasked(useMask); + ByteBuffer byteBuffer = draft_6455.createBinaryFrame(binaryFrame); + byte[] bytes = byteBuffer.array(); + int first = size / 2; + os.write(bytes, 0, first); + os.flush(); + Thread.sleep(5); + os.write(bytes, first, bytes.length - first); + os.flush(); + break; + } + if (input.startsWith("GET ")) { + testCase = input.split(" ")[1]; + String[] strings = testCase.split("/"); + useMask = Boolean.valueOf(strings[1]); + size = Integer.valueOf(strings[2]); + } + } + } catch (IOException e) { + // + } + } + } catch (Exception e) { + e.printStackTrace(); + fail("There should be no exception"); + } + } + }); + thread.start(); + } + + @AfterClass + public static void successTests() throws IOException { + serverSocket.close(); + thread.interrupt(); + } + + @Test(timeout = 5000) + public void testIncrementalFrameUnmasked() throws Exception { + testIncrementalFrame(false, size); + } + + @Test(timeout = 5000) + public void testIncrementalFrameMsked() throws Exception { + testIncrementalFrame(true, size); + } + + + private void testIncrementalFrame(boolean useMask, int size) throws Exception { + final boolean[] threadReturned = {false}; + final WebSocketClient webSocketClient = new WebSocketClient( + new URI("ws://localhost:" + port + "/" + useMask + "/" + size)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + } + + @Override + public void onMessage(String message) { + fail("There should not be a message!"); + } + + public void onMessage(ByteBuffer message) { + threadReturned[0] = true; + close(); + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + ex.printStackTrace(); + } + }; + Thread finalThread = new Thread(webSocketClient); + finalThread.start(); + finalThread.join(); + if (!threadReturned[0]) { + fail("Error"); + } + } } diff --git a/src/test/java/org/java_websocket/issues/Issue855Test.java b/src/test/java/org/java_websocket/issues/Issue855Test.java index ca681ad09..15abaa84f 100644 --- a/src/test/java/org/java_websocket/issues/Issue855Test.java +++ b/src/test/java/org/java_websocket/issues/Issue855Test.java @@ -40,60 +40,60 @@ public class Issue855Test { - CountDownLatch countServerDownLatch = new CountDownLatch(1); - CountDownLatch countDownLatch = new CountDownLatch(1); - - @Test(timeout = 2000) - public void testIssue() throws Exception { - int port = SocketUtil.getAvailablePort(); - WebSocketClient webSocket = new WebSocketClient(new URI("ws://localhost:" + port)) { - @Override - public void onOpen(ServerHandshake handshakedata) { - countDownLatch.countDown(); - } - - @Override - public void onMessage(String message) { - - } - - @Override - public void onClose(int code, String reason, boolean remote) { - } - - @Override - public void onError(Exception ex) { - - } - }; - WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - conn.close(); - } - - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - } - - @Override - public void onMessage(WebSocket conn, String message) { - - } - - @Override - public void onError(WebSocket conn, Exception ex) { - - } - - @Override - public void onStart() { - countServerDownLatch.countDown(); - } - }; - new Thread(server).start(); - countServerDownLatch.await(); - webSocket.connectBlocking(); - server.stop(); - } + CountDownLatch countServerDownLatch = new CountDownLatch(1); + CountDownLatch countDownLatch = new CountDownLatch(1); + + @Test(timeout = 2000) + public void testIssue() throws Exception { + int port = SocketUtil.getAvailablePort(); + WebSocketClient webSocket = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + countDownLatch.countDown(); + } + + @Override + public void onMessage(String message) { + + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + + } + }; + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + conn.close(); + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + }; + new Thread(server).start(); + countServerDownLatch.await(); + webSocket.connectBlocking(); + server.stop(); + } } diff --git a/src/test/java/org/java_websocket/issues/Issue879Test.java b/src/test/java/org/java_websocket/issues/Issue879Test.java index 97bcfa333..5e4f978de 100644 --- a/src/test/java/org/java_websocket/issues/Issue879Test.java +++ b/src/test/java/org/java_websocket/issues/Issue879Test.java @@ -53,118 +53,125 @@ @RunWith(Parameterized.class) public class Issue879Test { - private static final int NUMBER_OF_TESTS = 20; - - @Parameterized.Parameter - public int numberOfConnections; - - - @Test(timeout= 10000) - public void QuickStopTest() throws IOException, InterruptedException, URISyntaxException { - final boolean[] wasBindException = {false}; - final boolean[] wasConcurrentException = new boolean[1]; - final CountDownLatch countDownLatch = new CountDownLatch(1); - - class SimpleServer extends WebSocketServer { - public SimpleServer(InetSocketAddress address) { - super(address); - } - - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - broadcast("new connection: " + handshake.getResourceDescriptor()); //This method sends a message to all clients connected - } - - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - } - - @Override - public void onMessage(WebSocket conn, String message) { - } - - @Override - public void onMessage(WebSocket conn, ByteBuffer message) { - } - - @Override - public void onError(WebSocket conn, Exception ex) { - if (ex instanceof BindException) { - wasBindException[0] = true; - } - if (ex instanceof ConcurrentModificationException) { - wasConcurrentException[0] = true; - } - } - - @Override - public void onStart() { - countDownLatch.countDown(); - } + private static final int NUMBER_OF_TESTS = 20; + + @Parameterized.Parameter + public int numberOfConnections; + + + @Test(timeout = 10000) + public void QuickStopTest() throws IOException, InterruptedException, URISyntaxException { + final boolean[] wasBindException = {false}; + final boolean[] wasConcurrentException = new boolean[1]; + final CountDownLatch countDownLatch = new CountDownLatch(1); + + class SimpleServer extends WebSocketServer { + + public SimpleServer(InetSocketAddress address) { + super(address); + } + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + broadcast("new connection: " + handshake + .getResourceDescriptor()); //This method sends a message to all clients connected + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } + + @Override + public void onMessage(WebSocket conn, String message) { + } + + @Override + public void onMessage(WebSocket conn, ByteBuffer message) { + } + + @Override + public void onError(WebSocket conn, Exception ex) { + if (ex instanceof BindException) { + wasBindException[0] = true; } - int port = SocketUtil.getAvailablePort(); - SimpleServer serverA = new SimpleServer(new InetSocketAddress( port)); - SimpleServer serverB = new SimpleServer(new InetSocketAddress( port)); - serverA.start(); - countDownLatch.await(); - List clients = startNewConnections(numberOfConnections, port); - Thread.sleep(100); - int numberOfConnected = 0; - for (WebSocketClient client : clients) { - if (client.isOpen()) - numberOfConnected++; + if (ex instanceof ConcurrentModificationException) { + wasConcurrentException[0] = true; } - // Number will differ since we use connect instead of connectBlocking - // System.out.println(numberOfConnected + " " + numberOfConnections); - - serverA.stop(); - serverB.start(); - clients.clear(); - assertFalse("There was a BindException", wasBindException[0]); - assertFalse("There was a ConcurrentModificationException", wasConcurrentException[0]); - } + } - @Parameterized.Parameters - public static Collection data() { - List ret = new ArrayList(NUMBER_OF_TESTS); - for (int i = 0; i < NUMBER_OF_TESTS; i++) ret.add(new Integer[]{25+ i*25}); - return ret; + @Override + public void onStart() { + countDownLatch.countDown(); + } } - - private List startNewConnections(int numberOfConnections, int port) throws URISyntaxException, InterruptedException { - List clients = new ArrayList(numberOfConnections); - for (int i = 0; i < numberOfConnections; i++) { - WebSocketClient client = new SimpleClient(new URI("ws://localhost:" + port)); - client.connect(); - Thread.sleep(1); - clients.add(client); - } - return clients; + int port = SocketUtil.getAvailablePort(); + SimpleServer serverA = new SimpleServer(new InetSocketAddress(port)); + SimpleServer serverB = new SimpleServer(new InetSocketAddress(port)); + serverA.start(); + countDownLatch.await(); + List clients = startNewConnections(numberOfConnections, port); + Thread.sleep(100); + int numberOfConnected = 0; + for (WebSocketClient client : clients) { + if (client.isOpen()) { + numberOfConnected++; + } } - class SimpleClient extends WebSocketClient { + // Number will differ since we use connect instead of connectBlocking + // System.out.println(numberOfConnected + " " + numberOfConnections); + + serverA.stop(); + serverB.start(); + clients.clear(); + assertFalse("There was a BindException", wasBindException[0]); + assertFalse("There was a ConcurrentModificationException", wasConcurrentException[0]); + } + + @Parameterized.Parameters + public static Collection data() { + List ret = new ArrayList(NUMBER_OF_TESTS); + for (int i = 0; i < NUMBER_OF_TESTS; i++) { + ret.add(new Integer[]{25 + i * 25}); + } + return ret; + } + + private List startNewConnections(int numberOfConnections, int port) + throws URISyntaxException, InterruptedException { + List clients = new ArrayList(numberOfConnections); + for (int i = 0; i < numberOfConnections; i++) { + WebSocketClient client = new SimpleClient(new URI("ws://localhost:" + port)); + client.connect(); + Thread.sleep(1); + clients.add(client); + } + return clients; + } - public SimpleClient(URI serverUri) { - super(serverUri); - } + class SimpleClient extends WebSocketClient { - @Override - public void onOpen(ServerHandshake handshakedata) { + public SimpleClient(URI serverUri) { + super(serverUri); + } - } + @Override + public void onOpen(ServerHandshake handshakedata) { + + } - @Override - public void onMessage(String message) { + @Override + public void onMessage(String message) { - } + } - @Override - public void onClose(int code, String reason, boolean remote) { + @Override + public void onClose(int code, String reason, boolean remote) { - } + } - @Override - public void onError(Exception ex) { + @Override + public void onError(Exception ex) { - } } + } } diff --git a/src/test/java/org/java_websocket/issues/Issue890Test.java b/src/test/java/org/java_websocket/issues/Issue890Test.java index 06d5db5dc..877ab3574 100644 --- a/src/test/java/org/java_websocket/issues/Issue890Test.java +++ b/src/test/java/org/java_websocket/issues/Issue890Test.java @@ -55,116 +55,120 @@ public class Issue890Test { - @Test(timeout = 4000) - public void testWithSSLSession() throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { - int port = SocketUtil.getAvailablePort(); - final CountDownLatch countServerDownLatch = new CountDownLatch(1); - final WebSocketClient webSocket = new WebSocketClient(new URI("wss://localhost:" + port)) { - @Override - public void onOpen(ServerHandshake handshakedata) { - countServerDownLatch.countDown(); - } - - @Override - public void onMessage(String message) { - } - - @Override - public void onClose(int code, String reason, boolean remote) { - } - - @Override - public void onError(Exception ex) { - } - }; - TestResult testResult = new TestResult(); - WebSocketServer server = new MyWebSocketServer(port, testResult, countServerDownLatch); - SSLContext sslContext = SSLContextUtil.getContext(); - - server.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext)); - webSocket.setSocketFactory(sslContext.getSocketFactory()); - server.start(); - countServerDownLatch.await(); - webSocket.connectBlocking(); - assertTrue(testResult.hasSSLSupport); - assertNotNull(testResult.sslSession); + @Test(timeout = 4000) + public void testWithSSLSession() + throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { + int port = SocketUtil.getAvailablePort(); + final CountDownLatch countServerDownLatch = new CountDownLatch(1); + final WebSocketClient webSocket = new WebSocketClient(new URI("wss://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + countServerDownLatch.countDown(); + } + + @Override + public void onMessage(String message) { + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + } + }; + TestResult testResult = new TestResult(); + WebSocketServer server = new MyWebSocketServer(port, testResult, countServerDownLatch); + SSLContext sslContext = SSLContextUtil.getContext(); + + server.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext)); + webSocket.setSocketFactory(sslContext.getSocketFactory()); + server.start(); + countServerDownLatch.await(); + webSocket.connectBlocking(); + assertTrue(testResult.hasSSLSupport); + assertNotNull(testResult.sslSession); + } + + @Test(timeout = 4000) + public void testWithOutSSLSession() + throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { + int port = SocketUtil.getAvailablePort(); + final CountDownLatch countServerDownLatch = new CountDownLatch(1); + final WebSocketClient webSocket = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + countServerDownLatch.countDown(); + } + + @Override + public void onMessage(String message) { + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + } + }; + TestResult testResult = new TestResult(); + WebSocketServer server = new MyWebSocketServer(port, testResult, countServerDownLatch); + server.start(); + countServerDownLatch.await(); + webSocket.connectBlocking(); + assertFalse(testResult.hasSSLSupport); + assertNull(testResult.sslSession); + } + + + private static class MyWebSocketServer extends WebSocketServer { + + private final TestResult testResult; + private final CountDownLatch countServerDownLatch; + + public MyWebSocketServer(int port, TestResult testResult, CountDownLatch countServerDownLatch) { + super(new InetSocketAddress(port)); + this.testResult = testResult; + this.countServerDownLatch = countServerDownLatch; } - @Test(timeout = 4000) - public void testWithOutSSLSession() throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { - int port = SocketUtil.getAvailablePort(); - final CountDownLatch countServerDownLatch = new CountDownLatch(1); - final WebSocketClient webSocket = new WebSocketClient(new URI("ws://localhost:" + port)) { - @Override - public void onOpen(ServerHandshake handshakedata) { - countServerDownLatch.countDown(); - } - - @Override - public void onMessage(String message) { - } - - @Override - public void onClose(int code, String reason, boolean remote) { - } - - @Override - public void onError(Exception ex) { - } - }; - TestResult testResult = new TestResult(); - WebSocketServer server = new MyWebSocketServer(port, testResult, countServerDownLatch); - server.start(); - countServerDownLatch.await(); - webSocket.connectBlocking(); - assertFalse(testResult.hasSSLSupport); - assertNull(testResult.sslSession); + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + testResult.hasSSLSupport = conn.hasSSLSupport(); + try { + testResult.sslSession = conn.getSSLSession(); + } catch (IllegalArgumentException e) { + // Ignore + } } + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } + + @Override + public void onMessage(WebSocket conn, String message) { - private static class MyWebSocketServer extends WebSocketServer { - - private final TestResult testResult; - private final CountDownLatch countServerDownLatch; - - public MyWebSocketServer(int port, TestResult testResult, CountDownLatch countServerDownLatch) { - super(new InetSocketAddress(port)); - this.testResult = testResult; - this.countServerDownLatch = countServerDownLatch; - } - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - testResult.hasSSLSupport = conn.hasSSLSupport(); - try { - testResult.sslSession = conn.getSSLSession(); - } catch (IllegalArgumentException e){ - // Ignore - } - } - - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - } - - @Override - public void onMessage(WebSocket conn, String message) { - - } - - @Override - public void onError(WebSocket conn, Exception ex) { - ex.printStackTrace(); - } - - @Override - public void onStart() { - countServerDownLatch.countDown(); - } } - private class TestResult { - public SSLSession sslSession = null; + @Override + public void onError(WebSocket conn, Exception ex) { + ex.printStackTrace(); + } - public boolean hasSSLSupport = false; + @Override + public void onStart() { + countServerDownLatch.countDown(); } + } + + private class TestResult { + + public SSLSession sslSession = null; + + public boolean hasSSLSupport = false; + } } diff --git a/src/test/java/org/java_websocket/issues/Issue900Test.java b/src/test/java/org/java_websocket/issues/Issue900Test.java index c528534ea..db606140d 100644 --- a/src/test/java/org/java_websocket/issues/Issue900Test.java +++ b/src/test/java/org/java_websocket/issues/Issue900Test.java @@ -45,109 +45,111 @@ public class Issue900Test { - CountDownLatch serverStartLatch = new CountDownLatch(1); - CountDownLatch closeCalledLatch = new CountDownLatch(1); - - @Test(timeout = 2000) - public void testIssue() throws Exception { - int port = SocketUtil.getAvailablePort(); - final WebSocketClient client = new WebSocketClient(new URI("ws://localhost:" + port)) { - @Override - public void onOpen(ServerHandshake handshakedata) { - - } - - @Override - public void onMessage(String message) { - } - - @Override - public void onClose(int code, String reason, boolean remote) { - } - - @Override - public void onError(Exception ex) { - - } - }; - WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - } - - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - closeCalledLatch.countDown(); - } - - @Override - public void onMessage(WebSocket conn, String message) { - - } - - @Override - public void onError(WebSocket conn, Exception ex) { - - } - - @Override - public void onStart() { - serverStartLatch.countDown(); - } - }; - new Thread(server).start(); - serverStartLatch.await(); - client.connectBlocking(); - WebSocketImpl websocketImpl = (WebSocketImpl)new ArrayList(server.getConnections()).get(0); - websocketImpl.setChannel(new ExceptionThrowingByteChannel()); - server.broadcast("test"); - closeCalledLatch.await(); + CountDownLatch serverStartLatch = new CountDownLatch(1); + CountDownLatch closeCalledLatch = new CountDownLatch(1); + + @Test(timeout = 2000) + public void testIssue() throws Exception { + int port = SocketUtil.getAvailablePort(); + final WebSocketClient client = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + + } + + @Override + public void onMessage(String message) { + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + + } + }; + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + closeCalledLatch.countDown(); + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + serverStartLatch.countDown(); + } + }; + new Thread(server).start(); + serverStartLatch.await(); + client.connectBlocking(); + WebSocketImpl websocketImpl = (WebSocketImpl) new ArrayList(server.getConnections()) + .get(0); + websocketImpl.setChannel(new ExceptionThrowingByteChannel()); + server.broadcast("test"); + closeCalledLatch.await(); + } + + class ExceptionThrowingByteChannel implements WrappedByteChannel { + + @Override + public boolean isNeedWrite() { + return true; } - class ExceptionThrowingByteChannel implements WrappedByteChannel { - - @Override - public boolean isNeedWrite() { - return true; - } - - @Override - public void writeMore() throws IOException { - throw new IOException(); - } - - @Override - public boolean isNeedRead() { - return true; - } - - @Override - public int readMore(ByteBuffer dst) throws IOException { - throw new IOException(); - } - - @Override - public boolean isBlocking() { - return false; - } - - @Override - public int read(ByteBuffer dst) throws IOException { - throw new IOException(); - } - - @Override - public int write(ByteBuffer src) throws IOException { - throw new IOException(); - } - - @Override - public boolean isOpen() { - return false; - } - - @Override - public void close() throws IOException { - throw new IOException(); - } + + @Override + public void writeMore() throws IOException { + throw new IOException(); + } + + @Override + public boolean isNeedRead() { + return true; + } + + @Override + public int readMore(ByteBuffer dst) throws IOException { + throw new IOException(); + } + + @Override + public boolean isBlocking() { + return false; + } + + @Override + public int read(ByteBuffer dst) throws IOException { + throw new IOException(); + } + + @Override + public int write(ByteBuffer src) throws IOException { + throw new IOException(); + } + + @Override + public boolean isOpen() { + return false; + } + + @Override + public void close() throws IOException { + throw new IOException(); } + } } diff --git a/src/test/java/org/java_websocket/issues/Issue941Test.java b/src/test/java/org/java_websocket/issues/Issue941Test.java index 25d53dc15..9553cd6a7 100644 --- a/src/test/java/org/java_websocket/issues/Issue941Test.java +++ b/src/test/java/org/java_websocket/issues/Issue941Test.java @@ -44,61 +44,80 @@ public class Issue941Test { - private CountDownLatch pingLatch = new CountDownLatch(1); - private CountDownLatch pongLatch = new CountDownLatch(1); - private byte[] pingBuffer, receivedPingBuffer, pongBuffer; - - @Test - public void testIssue() throws Exception { - int port = SocketUtil.getAvailablePort(); - WebSocketClient client = new WebSocketClient(new URI( "ws://localhost:" + port)) { - @Override - public void onOpen(ServerHandshake handshakedata) { } - @Override - public void onMessage(String message) { } - @Override - public void onClose(int code, String reason, boolean remote) { } - @Override - public void onError(Exception ex) { } - @Override - public PingFrame onPreparePing(WebSocket conn) { - PingFrame frame = new PingFrame(); - pingBuffer = new byte[]{1,2,3,4,5,6,7,8,9,10}; - frame.setPayload(ByteBuffer.wrap(pingBuffer)); - return frame; - } - @Override - public void onWebsocketPong(WebSocket conn, Framedata f) { - pongBuffer = f.getPayloadData().array(); - pongLatch.countDown(); - } - }; - - WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { } - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { } - @Override - public void onMessage(WebSocket conn, String message) { } - @Override - public void onError(WebSocket conn, Exception ex) { } - @Override - public void onStart() { } - @Override - public void onWebsocketPing(WebSocket conn, Framedata f) { - receivedPingBuffer = f.getPayloadData().array(); - super.onWebsocketPing(conn, f); - pingLatch.countDown(); - } - }; - - server.start(); - client.connectBlocking(); - client.setConnectionLostTimeout(1); - pingLatch.await(); - assertArrayEquals(pingBuffer, receivedPingBuffer); - pongLatch.await(); - assertArrayEquals(pingBuffer, pongBuffer); - } + private CountDownLatch pingLatch = new CountDownLatch(1); + private CountDownLatch pongLatch = new CountDownLatch(1); + private byte[] pingBuffer, receivedPingBuffer, pongBuffer; + + @Test + public void testIssue() throws Exception { + int port = SocketUtil.getAvailablePort(); + WebSocketClient client = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + } + + @Override + public void onMessage(String message) { + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + } + + @Override + public PingFrame onPreparePing(WebSocket conn) { + PingFrame frame = new PingFrame(); + pingBuffer = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + frame.setPayload(ByteBuffer.wrap(pingBuffer)); + return frame; + } + + @Override + public void onWebsocketPong(WebSocket conn, Framedata f) { + pongBuffer = f.getPayloadData().array(); + pongLatch.countDown(); + } + }; + + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } + + @Override + public void onMessage(WebSocket conn, String message) { + } + + @Override + public void onError(WebSocket conn, Exception ex) { + } + + @Override + public void onStart() { + } + + @Override + public void onWebsocketPing(WebSocket conn, Framedata f) { + receivedPingBuffer = f.getPayloadData().array(); + super.onWebsocketPing(conn, f); + pingLatch.countDown(); + } + }; + + server.start(); + client.connectBlocking(); + client.setConnectionLostTimeout(1); + pingLatch.await(); + assertArrayEquals(pingBuffer, receivedPingBuffer); + pongLatch.await(); + assertArrayEquals(pingBuffer, pongBuffer); + } } diff --git a/src/test/java/org/java_websocket/issues/Issue962Test.java b/src/test/java/org/java_websocket/issues/Issue962Test.java index 1cc9b2984..b7d107171 100644 --- a/src/test/java/org/java_websocket/issues/Issue962Test.java +++ b/src/test/java/org/java_websocket/issues/Issue962Test.java @@ -43,101 +43,102 @@ public class Issue962Test { - private static class TestSocketFactory extends SocketFactory { - - private final SocketFactory socketFactory = SocketFactory.getDefault(); - private final String bindingAddress; - - public TestSocketFactory(String bindingAddress) { - this.bindingAddress = bindingAddress; - } - - @Override - public Socket createSocket() throws IOException { - Socket socket = socketFactory.createSocket(); - socket.bind(new InetSocketAddress(bindingAddress, 0)); - return socket; - } - - @Override - public Socket createSocket(String string, int i) throws IOException, UnknownHostException { - Socket socket = socketFactory.createSocket(string, i); - socket.bind(new InetSocketAddress(bindingAddress, 0)); - return socket; - } - - @Override - public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException, UnknownHostException { - throw new UnsupportedOperationException(); - } - - @Override - public Socket createSocket(InetAddress ia, int i) throws IOException { - Socket socket = socketFactory.createSocket(ia, i); - socket.bind(new InetSocketAddress(bindingAddress, 0)); - return socket; - } - - @Override - public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException { - throw new UnsupportedOperationException(); - } + private static class TestSocketFactory extends SocketFactory { + private final SocketFactory socketFactory = SocketFactory.getDefault(); + private final String bindingAddress; + + public TestSocketFactory(String bindingAddress) { + this.bindingAddress = bindingAddress; + } + + @Override + public Socket createSocket() throws IOException { + Socket socket = socketFactory.createSocket(); + socket.bind(new InetSocketAddress(bindingAddress, 0)); + return socket; + } + + @Override + public Socket createSocket(String string, int i) throws IOException, UnknownHostException { + Socket socket = socketFactory.createSocket(string, i); + socket.bind(new InetSocketAddress(bindingAddress, 0)); + return socket; } - @Test(timeout = 2000) - public void testIssue() throws IOException, URISyntaxException, InterruptedException { - int port = SocketUtil.getAvailablePort(); - WebSocketClient client = new WebSocketClient(new URI("ws://127.0.0.1:" + port)) { - @Override - public void onOpen(ServerHandshake handshakedata) { - } - - @Override - public void onMessage(String message) { - } - - @Override - public void onClose(int code, String reason, boolean remote) { - } - - @Override - public void onError(Exception ex) { - Assert.fail(ex.toString() + " should not occur"); - } - }; - - String bindingAddress = "127.0.0.1"; - - client.setSocketFactory(new TestSocketFactory(bindingAddress)); - - WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - } - - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - } - - @Override - public void onMessage(WebSocket conn, String message) { - } - - @Override - public void onError(WebSocket conn, Exception ex) { - } - - @Override - public void onStart() { - } - }; - - server.start(); - client.connectBlocking(); - Assert.assertEquals(bindingAddress, client.getSocket().getLocalAddress().getHostAddress()); - Assert.assertNotEquals(0, client.getSocket().getLocalPort()); - Assert.assertTrue(client.getSocket().isConnected()); + @Override + public Socket createSocket(String string, int i, InetAddress ia, int i1) + throws IOException, UnknownHostException { + throw new UnsupportedOperationException(); } + @Override + public Socket createSocket(InetAddress ia, int i) throws IOException { + Socket socket = socketFactory.createSocket(ia, i); + socket.bind(new InetSocketAddress(bindingAddress, 0)); + return socket; + } + + @Override + public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException { + throw new UnsupportedOperationException(); + } + + } + + @Test(timeout = 2000) + public void testIssue() throws IOException, URISyntaxException, InterruptedException { + int port = SocketUtil.getAvailablePort(); + WebSocketClient client = new WebSocketClient(new URI("ws://127.0.0.1:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + } + + @Override + public void onMessage(String message) { + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + Assert.fail(ex.toString() + " should not occur"); + } + }; + + String bindingAddress = "127.0.0.1"; + + client.setSocketFactory(new TestSocketFactory(bindingAddress)); + + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } + + @Override + public void onMessage(WebSocket conn, String message) { + } + + @Override + public void onError(WebSocket conn, Exception ex) { + } + + @Override + public void onStart() { + } + }; + + server.start(); + client.connectBlocking(); + Assert.assertEquals(bindingAddress, client.getSocket().getLocalAddress().getHostAddress()); + Assert.assertNotEquals(0, client.getSocket().getLocalPort()); + Assert.assertTrue(client.getSocket().isConnected()); + } + } diff --git a/src/test/java/org/java_websocket/issues/Issue997Test.java b/src/test/java/org/java_websocket/issues/Issue997Test.java index 493dd69b7..93f8cefe4 100644 --- a/src/test/java/org/java_websocket/issues/Issue997Test.java +++ b/src/test/java/org/java_websocket/issues/Issue997Test.java @@ -54,135 +54,159 @@ public class Issue997Test { - @Test(timeout=2000) - public void test_localServer_ServerLocalhost_Client127_CheckActive() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), "HTTPS"); - assertFalse(client.onOpen); - assertTrue(client.onSSLError); - } - @Test(timeout=2000) - public void test_localServer_ServerLocalhost_Client127_CheckInactive() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), ""); - assertTrue(client.onOpen); - assertFalse(client.onSSLError); + @Test(timeout = 2000) + public void test_localServer_ServerLocalhost_Client127_CheckActive() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), + "HTTPS"); + assertFalse(client.onOpen); + assertTrue(client.onSSLError); + } + + @Test(timeout = 2000) + public void test_localServer_ServerLocalhost_Client127_CheckInactive() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), ""); + assertTrue(client.onOpen); + assertFalse(client.onSSLError); + } + + @Test(timeout = 2000) + public void test_localServer_ServerLocalhost_Client127_CheckDefault() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), null); + assertFalse(client.onOpen); + assertTrue(client.onSSLError); + } + + @Test(timeout = 2000) + public void test_localServer_ServerLocalhost_ClientLocalhost_CheckActive() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), + "HTTPS"); + assertTrue(client.onOpen); + assertFalse(client.onSSLError); + } + + @Test(timeout = 2000) + public void test_localServer_ServerLocalhost_ClientLocalhost_CheckInactive() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), ""); + assertTrue(client.onOpen); + assertFalse(client.onSSLError); + } + + @Test(timeout = 2000) + public void test_localServer_ServerLocalhost_ClientLocalhost_CheckDefault() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), null); + assertTrue(client.onOpen); + assertFalse(client.onSSLError); + } + + + public SSLWebSocketClient testIssueWithLocalServer(String address, int port, + SSLContext serverContext, SSLContext clientContext, String endpointIdentificationAlgorithm) + throws IOException, URISyntaxException, InterruptedException { + CountDownLatch countServerDownLatch = new CountDownLatch(1); + SSLWebSocketClient client = new SSLWebSocketClient(address, port, + endpointIdentificationAlgorithm); + WebSocketServer server = new SSLWebSocketServer(port, countServerDownLatch); + + server.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(serverContext)); + if (clientContext != null) { + client.setSocketFactory(clientContext.getSocketFactory()); } + server.start(); + countServerDownLatch.await(); + client.connectBlocking(1, TimeUnit.SECONDS); + return client; + } - @Test(timeout=2000) - public void test_localServer_ServerLocalhost_Client127_CheckDefault() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), null); - assertFalse(client.onOpen); - assertTrue(client.onSSLError); - } - @Test(timeout=2000) - public void test_localServer_ServerLocalhost_ClientLocalhost_CheckActive() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), "HTTPS"); - assertTrue(client.onOpen); - assertFalse(client.onSSLError); - } - @Test(timeout=2000) - public void test_localServer_ServerLocalhost_ClientLocalhost_CheckInactive() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), ""); - assertTrue(client.onOpen); - assertFalse(client.onSSLError); - } + private static class SSLWebSocketClient extends WebSocketClient { - @Test(timeout=2000) - public void test_localServer_ServerLocalhost_ClientLocalhost_CheckDefault() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), null); - assertTrue(client.onOpen); - assertFalse(client.onSSLError); - } + private final String endpointIdentificationAlgorithm; + public boolean onSSLError = false; + public boolean onOpen = false; - - public SSLWebSocketClient testIssueWithLocalServer(String address, int port, SSLContext serverContext, SSLContext clientContext, String endpointIdentificationAlgorithm) throws IOException, URISyntaxException, InterruptedException { - CountDownLatch countServerDownLatch = new CountDownLatch(1); - SSLWebSocketClient client = new SSLWebSocketClient(address, port, endpointIdentificationAlgorithm); - WebSocketServer server = new SSLWebSocketServer(port, countServerDownLatch); - - server.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(serverContext)); - if (clientContext != null) { - client.setSocketFactory(clientContext.getSocketFactory()); - } - server.start(); - countServerDownLatch.await(); - client.connectBlocking(1, TimeUnit.SECONDS); - return client; + public SSLWebSocketClient(String address, int port, String endpointIdentificationAlgorithm) + throws URISyntaxException { + super(new URI("wss://" + address + ':' + port)); + this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm; } + @Override + public void onOpen(ServerHandshake handshakedata) { + this.onOpen = true; + } - private static class SSLWebSocketClient extends WebSocketClient { - private final String endpointIdentificationAlgorithm; - public boolean onSSLError = false; - public boolean onOpen = false; - - public SSLWebSocketClient(String address, int port, String endpointIdentificationAlgorithm) throws URISyntaxException { - super(new URI("wss://"+ address + ':' +port)); - this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm; - } + @Override + public void onMessage(String message) { + } - @Override - public void onOpen(ServerHandshake handshakedata) { - this.onOpen = true; - } + @Override + public void onClose(int code, String reason, boolean remote) { + } - @Override - public void onMessage(String message) { - } + @Override + public void onError(Exception ex) { + if (ex instanceof SSLHandshakeException) { + this.onSSLError = true; + } + } - @Override - public void onClose(int code, String reason, boolean remote) { - } + @Override + protected void onSetSSLParameters(SSLParameters sslParameters) { + // Always call super to ensure hostname validation is active by default + super.onSetSSLParameters(sslParameters); + if (endpointIdentificationAlgorithm != null) { + sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm); + } + } - @Override - public void onError(Exception ex) { - if (ex instanceof SSLHandshakeException) { - this.onSSLError = true; - } - } + } - @Override - protected void onSetSSLParameters(SSLParameters sslParameters) { - // Always call super to ensure hostname validation is active by default - super.onSetSSLParameters(sslParameters); - if (endpointIdentificationAlgorithm != null) { - sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm); - } - } + ; - }; + private static class SSLWebSocketServer extends WebSocketServer { - private static class SSLWebSocketServer extends WebSocketServer { - private final CountDownLatch countServerDownLatch; + private final CountDownLatch countServerDownLatch; - public SSLWebSocketServer(int port, CountDownLatch countServerDownLatch) { - super(new InetSocketAddress(port)); - this.countServerDownLatch = countServerDownLatch; - } + public SSLWebSocketServer(int port, CountDownLatch countServerDownLatch) { + super(new InetSocketAddress(port)); + this.countServerDownLatch = countServerDownLatch; + } - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - } + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - } + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } - @Override - public void onMessage(WebSocket conn, String message) { + @Override + public void onMessage(WebSocket conn, String message) { - } + } - @Override - public void onError(WebSocket conn, Exception ex) { - ex.printStackTrace(); - } + @Override + public void onError(WebSocket conn, Exception ex) { + ex.printStackTrace(); + } - @Override - public void onStart() { - countServerDownLatch.countDown(); - } + @Override + public void onStart() { + countServerDownLatch.countDown(); } + } } diff --git a/src/test/java/org/java_websocket/misc/AllMiscTests.java b/src/test/java/org/java_websocket/misc/AllMiscTests.java index 19ca884e5..bd643c093 100644 --- a/src/test/java/org/java_websocket/misc/AllMiscTests.java +++ b/src/test/java/org/java_websocket/misc/AllMiscTests.java @@ -24,16 +24,18 @@ */ package org.java_websocket.misc; + import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ - org.java_websocket.misc.OpeningHandshakeRejectionTest.class + org.java_websocket.misc.OpeningHandshakeRejectionTest.class }) /** * Start all tests for mics */ public class AllMiscTests { + } diff --git a/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java b/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java index 05e40f28f..11cbb0133 100644 --- a/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java +++ b/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java @@ -45,211 +45,228 @@ public class OpeningHandshakeRejectionTest { - private static final String additionalHandshake = "Upgrade: websocket\r\nConnection: Upgrade\r\n\r\n"; - private static int counter = 0; - private static Thread thread; - private static ServerSocket serverSocket; - - private static boolean debugPrintouts = false; - - private static int port; - - @BeforeClass - public static void startServer() throws Exception { - port = SocketUtil.getAvailablePort(); - thread = new Thread( - new Runnable() { - public void run() { - try { - serverSocket = new ServerSocket( port ); - serverSocket.setReuseAddress( true ); - while( true ) { - Socket client = null; - try { - client = serverSocket.accept(); - Scanner in = new Scanner( client.getInputStream() ); - String input = in.nextLine(); - String testCase = input.split( " " )[1]; - OutputStream os = client.getOutputStream(); - if( "/0".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( "HTTP/1.1 100 Switching Protocols\r\n" + additionalHandshake ) ); - os.flush(); - } - if( "/1".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( "HTTP/1.0 100 Switching Protocols\r\n" + additionalHandshake ) ); - os.flush(); - } - if( "/2".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( "HTTP 100 Switching Protocols\r\n" + additionalHandshake ) ); - os.flush(); - } - if( "/3".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( "HTTP/1.1 200 Switching Protocols\r\n" + additionalHandshake ) ); - os.flush(); - } - if( "/4".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( "HTTP 101 Switching Protocols\r\n" + additionalHandshake ) ); - os.flush(); - } - if( "/5".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( "HTTP/1.1 404 Switching Protocols\r\n" + additionalHandshake ) ); - os.flush(); - } - if( "/6".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( "HTTP/2.0 404 Switching Protocols\r\n" + additionalHandshake ) ); - os.flush(); - } - if( "/7".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( "HTTP/1.1 500 Switching Protocols\r\n" + additionalHandshake ) ); - os.flush(); - } - if( "/8".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( "GET 302 Switching Protocols\r\n" + additionalHandshake ) ); - os.flush(); - } - if( "/9".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( "GET HTTP/1.1 101 Switching Protocols\r\n" + additionalHandshake ) ); - os.flush(); - } - if( "/10".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( "HTTP/1.1 101 Switching Protocols\r\n" + additionalHandshake ) ); - os.flush(); - } - if( "/11".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( "HTTP/1.1 101 Websocket Connection Upgrade\r\n" + additionalHandshake ) ); - os.flush(); - } - } catch ( IOException e ) { - // - } - } - } catch ( Exception e ) { - fail( "There should be no exception" ); - } - } - } ); - thread.start(); - } - - @AfterClass - public static void successTests() throws InterruptedException, IOException { - serverSocket.close(); - thread.interrupt(); - if( debugPrintouts ) - System.out.println( counter + " successful tests" ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase0() throws Exception { - testHandshakeRejection( 0 ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase1() throws Exception { - testHandshakeRejection( 1 ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase2() throws Exception { - testHandshakeRejection( 2 ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase3() throws Exception { - testHandshakeRejection( 3 ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase4() throws Exception { - testHandshakeRejection( 4 ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase5() throws Exception { - testHandshakeRejection( 5 ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase6() throws Exception { - testHandshakeRejection( 6 ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase7() throws Exception { - testHandshakeRejection( 7 ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase8() throws Exception { - testHandshakeRejection( 8 ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase9() throws Exception { - testHandshakeRejection( 9 ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase10() throws Exception { - testHandshakeRejection( 10 ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase11() throws Exception { - testHandshakeRejection( 11 ); - } - - private void testHandshakeRejection( int i ) throws Exception { - final int finalI = i; - final boolean[] threadReturned = { false }; - WebSocketClient webSocketClient = new WebSocketClient( new URI( "ws://localhost:"+ port + "/" + finalI ) ) { - @Override - public void onOpen( ServerHandshake handshakedata ) { - fail( "There should not be a connection!" ); - } - - @Override - public void onMessage( String message ) { - fail( "There should not be a message!" ); - } - - @Override - public void onClose( int code, String reason, boolean remote ) { - if( finalI != 10 && finalI != 11 ) { - if( code != CloseFrame.PROTOCOL_ERROR ) { - fail( "There should be a protocol error!" ); - } else if( reason.startsWith( "Invalid status code received:" ) || reason.startsWith( "Invalid status line received:" ) ) { - if( debugPrintouts ) - System.out.println( "Protocol error for test case: " + finalI ); - threadReturned[0] = true; - counter++; - } else { - fail( "The reason should be included!" ); - } - } else { - //Since we do not include a correct Sec-WebSocket-Accept, onClose will be called with reason 'Draft refuses handshake' - if( !reason.endsWith( "refuses handshake" ) ) { - fail( "onClose should not be called!" ); - } else { - if( debugPrintouts ) - System.out.println( "Refuses handshake error for test case: " + finalI ); - counter++; - threadReturned[0] = true; - } - } - } - - @Override - public void onError( Exception ex ) { - fail( "There should not be an exception" ); - } - }; - Thread finalThread = new Thread( webSocketClient ); - finalThread.start(); - finalThread.join(); - - if( !threadReturned[0] ) { - fail( "Error" ); - } - } + private static final String additionalHandshake = "Upgrade: websocket\r\nConnection: Upgrade\r\n\r\n"; + private static int counter = 0; + private static Thread thread; + private static ServerSocket serverSocket; + + private static boolean debugPrintouts = false; + + private static int port; + + @BeforeClass + public static void startServer() throws Exception { + port = SocketUtil.getAvailablePort(); + thread = new Thread( + new Runnable() { + public void run() { + try { + serverSocket = new ServerSocket(port); + serverSocket.setReuseAddress(true); + while (true) { + Socket client = null; + try { + client = serverSocket.accept(); + Scanner in = new Scanner(client.getInputStream()); + String input = in.nextLine(); + String testCase = input.split(" ")[1]; + OutputStream os = client.getOutputStream(); + if ("/0".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.1 100 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/1".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.0 100 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/2".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP 100 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/3".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.1 200 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/4".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP 101 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/5".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.1 404 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/6".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/2.0 404 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/7".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.1 500 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/8".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("GET 302 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/9".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + "GET HTTP/1.1 101 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/10".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.1 101 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/11".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + "HTTP/1.1 101 Websocket Connection Upgrade\r\n" + additionalHandshake)); + os.flush(); + } + } catch (IOException e) { + // + } + } + } catch (Exception e) { + fail("There should be no exception"); + } + } + }); + thread.start(); + } + + @AfterClass + public static void successTests() throws InterruptedException, IOException { + serverSocket.close(); + thread.interrupt(); + if (debugPrintouts) { + System.out.println(counter + " successful tests"); + } + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase0() throws Exception { + testHandshakeRejection(0); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase1() throws Exception { + testHandshakeRejection(1); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase2() throws Exception { + testHandshakeRejection(2); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase3() throws Exception { + testHandshakeRejection(3); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase4() throws Exception { + testHandshakeRejection(4); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase5() throws Exception { + testHandshakeRejection(5); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase6() throws Exception { + testHandshakeRejection(6); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase7() throws Exception { + testHandshakeRejection(7); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase8() throws Exception { + testHandshakeRejection(8); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase9() throws Exception { + testHandshakeRejection(9); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase10() throws Exception { + testHandshakeRejection(10); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase11() throws Exception { + testHandshakeRejection(11); + } + + private void testHandshakeRejection(int i) throws Exception { + final int finalI = i; + final boolean[] threadReturned = {false}; + WebSocketClient webSocketClient = new WebSocketClient( + new URI("ws://localhost:" + port + "/" + finalI)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + fail("There should not be a connection!"); + } + + @Override + public void onMessage(String message) { + fail("There should not be a message!"); + } + + @Override + public void onClose(int code, String reason, boolean remote) { + if (finalI != 10 && finalI != 11) { + if (code != CloseFrame.PROTOCOL_ERROR) { + fail("There should be a protocol error!"); + } else if (reason.startsWith("Invalid status code received:") || reason + .startsWith("Invalid status line received:")) { + if (debugPrintouts) { + System.out.println("Protocol error for test case: " + finalI); + } + threadReturned[0] = true; + counter++; + } else { + fail("The reason should be included!"); + } + } else { + //Since we do not include a correct Sec-WebSocket-Accept, onClose will be called with reason 'Draft refuses handshake' + if (!reason.endsWith("refuses handshake")) { + fail("onClose should not be called!"); + } else { + if (debugPrintouts) { + System.out.println("Refuses handshake error for test case: " + finalI); + } + counter++; + threadReturned[0] = true; + } + } + } + + @Override + public void onError(Exception ex) { + fail("There should not be an exception"); + } + }; + Thread finalThread = new Thread(webSocketClient); + finalThread.start(); + finalThread.join(); + + if (!threadReturned[0]) { + fail("Error"); + } + } } diff --git a/src/test/java/org/java_websocket/protocols/AllProtocolTests.java b/src/test/java/org/java_websocket/protocols/AllProtocolTests.java index 03d5eaad8..ae403d7ba 100644 --- a/src/test/java/org/java_websocket/protocols/AllProtocolTests.java +++ b/src/test/java/org/java_websocket/protocols/AllProtocolTests.java @@ -31,11 +31,12 @@ @RunWith(Suite.class) @Suite.SuiteClasses({ - org.java_websocket.protocols.ProtocolTest.class, - org.java_websocket.protocols.ProtoclHandshakeRejectionTest.class + org.java_websocket.protocols.ProtocolTest.class, + org.java_websocket.protocols.ProtoclHandshakeRejectionTest.class }) /** * Start all tests for protocols */ public class AllProtocolTests { + } diff --git a/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java b/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java index 6c0b8072d..f0bf82fcb 100644 --- a/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java +++ b/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java @@ -52,508 +52,566 @@ public class ProtoclHandshakeRejectionTest { - private static final String additionalHandshake = "HTTP/1.1 101 Websocket Connection Upgrade\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"; - private static Thread thread; - private static ServerSocket serverSocket; - - private static int port; - - @BeforeClass - public static void startServer() throws Exception { - port = SocketUtil.getAvailablePort(); - thread = new Thread( - new Runnable() { - public void run() { - try { - serverSocket = new ServerSocket( port ); - serverSocket.setReuseAddress( true ); - while( true ) { - Socket client = null; - try { - client = serverSocket.accept(); - Scanner in = new Scanner( client.getInputStream() ); - String input = in.nextLine(); - String testCase = input.split( " " )[1]; - String seckey = ""; - String secproc = ""; - while( in.hasNext() ) { - input = in.nextLine(); - if( input.startsWith( "Sec-WebSocket-Key: " ) ) { - seckey = input.split( " " )[1]; - } - if( input.startsWith( "Sec-WebSocket-Protocol: " ) ) { - secproc = input.split( " " )[1]; - } - //Last - if( input.startsWith( "Upgrade" ) ) { - break; - } - } - OutputStream os = client.getOutputStream(); - if( "/0".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "\r\n" ) ); - os.flush(); - } - if( "/1".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/2".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat, chat2" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/3".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat,chat2,chat3" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/4".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat\r\nSec-WebSocket-Protocol: chat2,chat3" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/5".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "\r\n" ) ); - os.flush(); - } - if( "/6".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/7".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat, chat2" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/8".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat,chat2,chat3" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/9".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat\r\nSec-WebSocket-Protocol: chat2,chat3" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/10".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat2,chat3" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/11".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat2, chat3" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/12".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat2\r\nSec-WebSocket-Protocol: chat3" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/13".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat2\r\nSec-WebSocket-Protocol: chat" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/14".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat2,chat" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/15".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat3" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/16".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "\r\n" ) ); - os.flush(); - } - if( "/17".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "\r\n" ) ); - os.flush(); - } - if( "/18".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + "Sec-WebSocket-Accept: abc\r\n" + "\r\n" ) ); - os.flush(); - } - if( "/19".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + "\r\n" ) ); - os.flush(); - } - // Order check - if( "/20".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/21".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake +getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/22".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/23".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/24".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/25".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: abc" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/26".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "\r\n\r\n" ) ); - os.flush(); - } - if( "/27".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/28".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "Sec-WebSocket-Protocol: abc" + "\r\n\r\n" ) ); - os.flush(); - } - if( "/29".equals( testCase ) ) { - os.write( Charsetfunctions.asciiBytes( additionalHandshake + getSecKey( seckey ) + "\r\n\r\n" ) ); - os.flush(); - } - } catch ( IOException e ) { - // - } - } - } catch ( Exception e ) { - e.printStackTrace(); - fail( "There should be no exception" ); - } - } - } ); - thread.start(); - } - - private static String getSecKey( String seckey ) { - return "Sec-WebSocket-Accept: " + generateFinalKey( seckey ) + "\r\n"; - } - - @AfterClass - public static void successTests() throws IOException { - serverSocket.close(); - thread.interrupt(); - } - - @Test(timeout = 5000) - public void testProtocolRejectionTestCase0() throws Exception { - testProtocolRejection( 0, new Draft_6455(Collections.emptyList(), Collections.singletonList( new Protocol( "" ))) ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase1() throws Exception { - testProtocolRejection( 1, new Draft_6455() ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase2() throws Exception { - testProtocolRejection( 2, new Draft_6455() ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase3() throws Exception { - testProtocolRejection( 3, new Draft_6455() ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase4() throws Exception { - testProtocolRejection( 4, new Draft_6455() ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase5() throws Exception { - testProtocolRejection( 5, new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ) ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase6() throws Exception { - testProtocolRejection( 6, new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ) ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase7() throws Exception { - testProtocolRejection( 7, new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ) ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase8() throws Exception { - testProtocolRejection( 8, new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ) ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase9() throws Exception { - testProtocolRejection( 9, new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ) ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase10() throws Exception { - testProtocolRejection( 10, new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ) ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase11() throws Exception { - testProtocolRejection( 11, new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ) ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase12() throws Exception { - testProtocolRejection( 12, new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ) ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase13() throws Exception { - testProtocolRejection( 13, new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "chat" ) ) ) ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase14() throws Exception { - ArrayList protocols = new ArrayList(); - protocols.add( new Protocol( "chat" ) ); - protocols.add( new Protocol( "chat2" ) ); - testProtocolRejection( 14, new Draft_6455( Collections.emptyList(), protocols ) ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase15() throws Exception { - ArrayList protocols = new ArrayList(); - protocols.add( new Protocol( "chat" ) ); - protocols.add( new Protocol( "chat2" ) ); - testProtocolRejection( 15, new Draft_6455( Collections.emptyList(), protocols ) ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase16() throws Exception { - ArrayList protocols = new ArrayList(); - protocols.add( new Protocol( "chat" ) ); - protocols.add( new Protocol( "chat2" ) ); - testProtocolRejection( 16, new Draft_6455( Collections.emptyList(), protocols ) ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase17() throws Exception { - ArrayList protocols = new ArrayList(); - protocols.add( new Protocol( "chat" ) ); - protocols.add( new Protocol( "" ) ); - testProtocolRejection( 17, new Draft_6455( Collections.emptyList(), protocols ) ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase18() throws Exception { - testProtocolRejection( 18, new Draft_6455() ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase19() throws Exception { - testProtocolRejection( 19, new Draft_6455() ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase20() throws Exception { - testProtocolRejection( 20, new Draft_6455() ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase21() throws Exception { - ArrayList protocols = new ArrayList(); - protocols.add( new Protocol( "chat1" ) ); - protocols.add( new Protocol( "chat2" ) ); - protocols.add( new Protocol( "chat3" ) ); - testProtocolRejection( 21, new Draft_6455( Collections.emptyList(), protocols ) ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase22() throws Exception { - ArrayList protocols = new ArrayList(); - protocols.add( new Protocol( "chat2" ) ); - protocols.add( new Protocol( "chat3" ) ); - protocols.add( new Protocol( "chat1" ) ); - testProtocolRejection( 22, new Draft_6455( Collections.emptyList(), protocols ) ); - } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase23() throws Exception { - ArrayList protocols = new ArrayList(); - protocols.add( new Protocol( "chat3" ) ); - protocols.add( new Protocol( "chat2" ) ); - protocols.add( new Protocol( "chat1" ) ); - testProtocolRejection( 23, new Draft_6455( Collections.emptyList(), protocols ) ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase24() throws Exception { - testProtocolRejection( 24, new Draft_6455() ); - } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase25() throws Exception { - testProtocolRejection( 25, new Draft_6455() ); - } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase26() throws Exception { - testProtocolRejection( 26, new Draft_6455() ); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase27() throws Exception { - testProtocolRejection( 27, new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "opc" ) ) ) ); - } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase28() throws Exception { - testProtocolRejection( 28, new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "opc" ) ) ) ); - } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase29() throws Exception { - testProtocolRejection( 29, new Draft_6455( Collections.emptyList(), Collections.singletonList( new Protocol( "opc" ) ) ) ); - } - private void testProtocolRejection( int i, Draft_6455 draft ) throws Exception { - final int finalI = i; - final boolean[] threadReturned = { false }; - WebSocketClient webSocketClient = new WebSocketClient( new URI( "ws://localhost:" + port + "/" + finalI ), draft ) { - @Override - public void onOpen( ServerHandshake handshakedata ) { - switch(finalI) { - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - case 8: - case 9: - case 13: - case 14: - case 17: - case 20: - case 21: - case 22: - case 23: - case 24: - case 25: - case 26: - threadReturned[0] = true; - closeConnection( CloseFrame.ABNORMAL_CLOSE, "Bye" ); - break; - default: - fail( "There should not be a connection!" ); - } - } - - @Override - public void onMessage( String message ) { - fail( "There should not be a message!" ); - } - - @Override - public void onClose( int code, String reason, boolean remote ) { - switch (finalI) { - case 0: - case 1: - case 2: - case 3: - case 4: - case 20: - case 24: - case 25: - case 26: - assertEquals("" ,getProtocol().getProvidedProtocol()); - break; - case 5: - case 9: - case 10: - case 11: - case 12: - case 13: - case 15: - case 16: - case 18: - case 19: - case 27: - case 28: - case 29: - assertNull(getProtocol()); - break; - case 6: - case 7: - case 8: - case 17: - assertEquals("chat" ,getProtocol().getProvidedProtocol()); - break; - case 14: - case 22: - assertEquals("chat2" ,getProtocol().getProvidedProtocol()); - break; - case 21: - assertEquals("chat1" ,getProtocol().getProvidedProtocol()); - break; - case 23: - assertEquals("chat3" ,getProtocol().getProvidedProtocol()); - break; - default: - fail(); - } - if( code == CloseFrame.ABNORMAL_CLOSE ) { - switch(finalI) { - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - case 8: - case 9: - case 13: - case 14: - case 17: - case 20: - case 21: - case 22: - case 23: - case 24: - case 25: - case 26: - return; - } - } - if( code != CloseFrame.PROTOCOL_ERROR ) { - fail( "There should be a protocol error! " + finalI + " " + code ); - } else if( reason.endsWith( "refuses handshake" ) ) { - threadReturned[0] = true; - } else { - fail( "The reason should be included!" ); - } - } - - @Override - public void onError( Exception ex ) { - fail( "There should not be an exception" ); - } - }; - Thread finalThread = new Thread( webSocketClient ); - finalThread.start(); - finalThread.join(); - - if( !threadReturned[0] ) { - fail( "Error" ); - } - - } - - /** - * Generate a final key from a input string - * - * @param in the input string - * @return a final key - */ - private static String generateFinalKey( String in ) { - String seckey = in.trim(); - String acc = seckey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; - MessageDigest sh1; - try { - sh1 = MessageDigest.getInstance( "SHA1" ); - } catch ( NoSuchAlgorithmException e ) { - throw new IllegalStateException( e ); - } - return Base64.encodeBytes( sh1.digest( acc.getBytes() ) ); - } + private static final String additionalHandshake = "HTTP/1.1 101 Websocket Connection Upgrade\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"; + private static Thread thread; + private static ServerSocket serverSocket; + + private static int port; + + @BeforeClass + public static void startServer() throws Exception { + port = SocketUtil.getAvailablePort(); + thread = new Thread( + new Runnable() { + public void run() { + try { + serverSocket = new ServerSocket(port); + serverSocket.setReuseAddress(true); + while (true) { + Socket client = null; + try { + client = serverSocket.accept(); + Scanner in = new Scanner(client.getInputStream()); + String input = in.nextLine(); + String testCase = input.split(" ")[1]; + String seckey = ""; + String secproc = ""; + while (in.hasNext()) { + input = in.nextLine(); + if (input.startsWith("Sec-WebSocket-Key: ")) { + seckey = input.split(" ")[1]; + } + if (input.startsWith("Sec-WebSocket-Protocol: ")) { + secproc = input.split(" ")[1]; + } + //Last + if (input.startsWith("Upgrade")) { + break; + } + } + OutputStream os = client.getOutputStream(); + if ("/0".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); + os.flush(); + } + if ("/1".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: chat" + + "\r\n\r\n")); + os.flush(); + } + if ("/2".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat, chat2" + "\r\n\r\n")); + os.flush(); + } + if ("/3".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/4".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat\r\nSec-WebSocket-Protocol: chat2,chat3" + + "\r\n\r\n")); + os.flush(); + } + if ("/5".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); + os.flush(); + } + if ("/6".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: chat" + + "\r\n\r\n")); + os.flush(); + } + if ("/7".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat, chat2" + "\r\n\r\n")); + os.flush(); + } + if ("/8".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/9".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat\r\nSec-WebSocket-Protocol: chat2,chat3" + + "\r\n\r\n")); + os.flush(); + } + if ("/10".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/11".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat2, chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/12".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat2\r\nSec-WebSocket-Protocol: chat3" + + "\r\n\r\n")); + os.flush(); + } + if ("/13".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat2\r\nSec-WebSocket-Protocol: chat" + + "\r\n\r\n")); + os.flush(); + } + if ("/14".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat2,chat" + "\r\n\r\n")); + os.flush(); + } + if ("/15".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: chat3" + + "\r\n\r\n")); + os.flush(); + } + if ("/16".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); + os.flush(); + } + if ("/17".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); + os.flush(); + } + if ("/18".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + "Sec-WebSocket-Accept: abc\r\n" + "\r\n")); + os.flush(); + } + if ("/19".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + "\r\n")); + os.flush(); + } + // Order check + if ("/20".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/21".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/22".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/23".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/24".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/25".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: abc" + + "\r\n\r\n")); + os.flush(); + } + if ("/26".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n\r\n")); + os.flush(); + } + if ("/27".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/28".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: abc" + + "\r\n\r\n")); + os.flush(); + } + if ("/29".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n\r\n")); + os.flush(); + } + } catch (IOException e) { + // + } + } + } catch (Exception e) { + e.printStackTrace(); + fail("There should be no exception"); + } + } + }); + thread.start(); + } + + private static String getSecKey(String seckey) { + return "Sec-WebSocket-Accept: " + generateFinalKey(seckey) + "\r\n"; + } + + @AfterClass + public static void successTests() throws IOException { + serverSocket.close(); + thread.interrupt(); + } + + @Test(timeout = 5000) + public void testProtocolRejectionTestCase0() throws Exception { + testProtocolRejection(0, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("")))); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase1() throws Exception { + testProtocolRejection(1, new Draft_6455()); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase2() throws Exception { + testProtocolRejection(2, new Draft_6455()); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase3() throws Exception { + testProtocolRejection(3, new Draft_6455()); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase4() throws Exception { + testProtocolRejection(4, new Draft_6455()); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase5() throws Exception { + testProtocolRejection(5, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase6() throws Exception { + testProtocolRejection(6, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase7() throws Exception { + testProtocolRejection(7, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase8() throws Exception { + testProtocolRejection(8, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase9() throws Exception { + testProtocolRejection(9, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase10() throws Exception { + testProtocolRejection(10, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase11() throws Exception { + testProtocolRejection(11, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase12() throws Exception { + testProtocolRejection(12, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase13() throws Exception { + testProtocolRejection(13, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase14() throws Exception { + ArrayList protocols = new ArrayList(); + protocols.add(new Protocol("chat")); + protocols.add(new Protocol("chat2")); + testProtocolRejection(14, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase15() throws Exception { + ArrayList protocols = new ArrayList(); + protocols.add(new Protocol("chat")); + protocols.add(new Protocol("chat2")); + testProtocolRejection(15, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase16() throws Exception { + ArrayList protocols = new ArrayList(); + protocols.add(new Protocol("chat")); + protocols.add(new Protocol("chat2")); + testProtocolRejection(16, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase17() throws Exception { + ArrayList protocols = new ArrayList(); + protocols.add(new Protocol("chat")); + protocols.add(new Protocol("")); + testProtocolRejection(17, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase18() throws Exception { + testProtocolRejection(18, new Draft_6455()); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase19() throws Exception { + testProtocolRejection(19, new Draft_6455()); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase20() throws Exception { + testProtocolRejection(20, new Draft_6455()); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase21() throws Exception { + ArrayList protocols = new ArrayList(); + protocols.add(new Protocol("chat1")); + protocols.add(new Protocol("chat2")); + protocols.add(new Protocol("chat3")); + testProtocolRejection(21, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase22() throws Exception { + ArrayList protocols = new ArrayList(); + protocols.add(new Protocol("chat2")); + protocols.add(new Protocol("chat3")); + protocols.add(new Protocol("chat1")); + testProtocolRejection(22, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase23() throws Exception { + ArrayList protocols = new ArrayList(); + protocols.add(new Protocol("chat3")); + protocols.add(new Protocol("chat2")); + protocols.add(new Protocol("chat1")); + testProtocolRejection(23, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase24() throws Exception { + testProtocolRejection(24, new Draft_6455()); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase25() throws Exception { + testProtocolRejection(25, new Draft_6455()); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase26() throws Exception { + testProtocolRejection(26, new Draft_6455()); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase27() throws Exception { + testProtocolRejection(27, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("opc")))); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase28() throws Exception { + testProtocolRejection(28, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("opc")))); + } + + @Test(timeout = 5000) + public void testHandshakeRejectionTestCase29() throws Exception { + testProtocolRejection(29, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("opc")))); + } + + private void testProtocolRejection(int i, Draft_6455 draft) throws Exception { + final int finalI = i; + final boolean[] threadReturned = {false}; + WebSocketClient webSocketClient = new WebSocketClient( + new URI("ws://localhost:" + port + "/" + finalI), draft) { + @Override + public void onOpen(ServerHandshake handshakedata) { + switch (finalI) { + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 13: + case 14: + case 17: + case 20: + case 21: + case 22: + case 23: + case 24: + case 25: + case 26: + threadReturned[0] = true; + closeConnection(CloseFrame.ABNORMAL_CLOSE, "Bye"); + break; + default: + fail("There should not be a connection!"); + } + } + + @Override + public void onMessage(String message) { + fail("There should not be a message!"); + } + + @Override + public void onClose(int code, String reason, boolean remote) { + switch (finalI) { + case 0: + case 1: + case 2: + case 3: + case 4: + case 20: + case 24: + case 25: + case 26: + assertEquals("", getProtocol().getProvidedProtocol()); + break; + case 5: + case 9: + case 10: + case 11: + case 12: + case 13: + case 15: + case 16: + case 18: + case 19: + case 27: + case 28: + case 29: + assertNull(getProtocol()); + break; + case 6: + case 7: + case 8: + case 17: + assertEquals("chat", getProtocol().getProvidedProtocol()); + break; + case 14: + case 22: + assertEquals("chat2", getProtocol().getProvidedProtocol()); + break; + case 21: + assertEquals("chat1", getProtocol().getProvidedProtocol()); + break; + case 23: + assertEquals("chat3", getProtocol().getProvidedProtocol()); + break; + default: + fail(); + } + if (code == CloseFrame.ABNORMAL_CLOSE) { + switch (finalI) { + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 13: + case 14: + case 17: + case 20: + case 21: + case 22: + case 23: + case 24: + case 25: + case 26: + return; + } + } + if (code != CloseFrame.PROTOCOL_ERROR) { + fail("There should be a protocol error! " + finalI + " " + code); + } else if (reason.endsWith("refuses handshake")) { + threadReturned[0] = true; + } else { + fail("The reason should be included!"); + } + } + + @Override + public void onError(Exception ex) { + fail("There should not be an exception"); + } + }; + Thread finalThread = new Thread(webSocketClient); + finalThread.start(); + finalThread.join(); + + if (!threadReturned[0]) { + fail("Error"); + } + + } + + /** + * Generate a final key from a input string + * + * @param in the input string + * @return a final key + */ + private static String generateFinalKey(String in) { + String seckey = in.trim(); + String acc = seckey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + MessageDigest sh1; + try { + sh1 = MessageDigest.getInstance("SHA1"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + return Base64.encodeBytes(sh1.digest(acc.getBytes())); + } } diff --git a/src/test/java/org/java_websocket/protocols/ProtocolTest.java b/src/test/java/org/java_websocket/protocols/ProtocolTest.java index 91d7b3394..23dd4d485 100644 --- a/src/test/java/org/java_websocket/protocols/ProtocolTest.java +++ b/src/test/java/org/java_websocket/protocols/ProtocolTest.java @@ -31,80 +31,80 @@ public class ProtocolTest { - @Test - public void testConstructor() throws Exception { - Protocol protocol0 = new Protocol( "" ); - try { - Protocol protocol1 = new Protocol( null ); - fail( "IllegalArgumentException expected" ); - } catch ( IllegalArgumentException e ) { - //Fine - } - } + @Test + public void testConstructor() throws Exception { + Protocol protocol0 = new Protocol(""); + try { + Protocol protocol1 = new Protocol(null); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException e) { + //Fine + } + } - @Test - public void testAcceptProvidedProtocol() throws Exception { - Protocol protocol0 = new Protocol( "" ); - assertTrue( protocol0.acceptProvidedProtocol( "" ) ); - assertTrue( protocol0.acceptProvidedProtocol( "chat" ) ); - assertTrue( protocol0.acceptProvidedProtocol( "chat, test" ) ); - assertTrue( protocol0.acceptProvidedProtocol( "chat, test," ) ); - Protocol protocol1 = new Protocol( "chat" ); - assertTrue( protocol1.acceptProvidedProtocol( "chat" ) ); - assertFalse( protocol1.acceptProvidedProtocol( "test" ) ); - assertTrue( protocol1.acceptProvidedProtocol( "chat, test" ) ); - assertTrue( protocol1.acceptProvidedProtocol( "test, chat" ) ); - assertTrue( protocol1.acceptProvidedProtocol( "test,chat" ) ); - assertTrue( protocol1.acceptProvidedProtocol( "chat,test" ) ); - assertTrue( protocol1.acceptProvidedProtocol( "asdchattest,test, chat" ) ); - } + @Test + public void testAcceptProvidedProtocol() throws Exception { + Protocol protocol0 = new Protocol(""); + assertTrue(protocol0.acceptProvidedProtocol("")); + assertTrue(protocol0.acceptProvidedProtocol("chat")); + assertTrue(protocol0.acceptProvidedProtocol("chat, test")); + assertTrue(protocol0.acceptProvidedProtocol("chat, test,")); + Protocol protocol1 = new Protocol("chat"); + assertTrue(protocol1.acceptProvidedProtocol("chat")); + assertFalse(protocol1.acceptProvidedProtocol("test")); + assertTrue(protocol1.acceptProvidedProtocol("chat, test")); + assertTrue(protocol1.acceptProvidedProtocol("test, chat")); + assertTrue(protocol1.acceptProvidedProtocol("test,chat")); + assertTrue(protocol1.acceptProvidedProtocol("chat,test")); + assertTrue(protocol1.acceptProvidedProtocol("asdchattest,test, chat")); + } - @Test - public void testGetProvidedProtocol() throws Exception { - Protocol protocol0 = new Protocol( "" ); - assertEquals( "", protocol0.getProvidedProtocol()); - Protocol protocol1 = new Protocol( "protocol" ); - assertEquals( "protocol" , protocol1.getProvidedProtocol()); - } + @Test + public void testGetProvidedProtocol() throws Exception { + Protocol protocol0 = new Protocol(""); + assertEquals("", protocol0.getProvidedProtocol()); + Protocol protocol1 = new Protocol("protocol"); + assertEquals("protocol", protocol1.getProvidedProtocol()); + } - @Test - public void testCopyInstance() throws Exception { - IProtocol protocol0 = new Protocol( "" ); - IProtocol protoocl1 = protocol0.copyInstance(); - assertEquals( protocol0, protoocl1 ); - IProtocol protocol2 = new Protocol( "protocol" ); - IProtocol protocol3 = protocol2.copyInstance(); - assertEquals( protocol2, protocol3 ); - } + @Test + public void testCopyInstance() throws Exception { + IProtocol protocol0 = new Protocol(""); + IProtocol protoocl1 = protocol0.copyInstance(); + assertEquals(protocol0, protoocl1); + IProtocol protocol2 = new Protocol("protocol"); + IProtocol protocol3 = protocol2.copyInstance(); + assertEquals(protocol2, protocol3); + } - @Test - public void testToString() throws Exception { - Protocol protocol0 = new Protocol( "" ); - assertEquals( "", protocol0.getProvidedProtocol() ); - Protocol protocol1 = new Protocol( "protocol" ); - assertEquals( "protocol", protocol1.getProvidedProtocol() ); - } + @Test + public void testToString() throws Exception { + Protocol protocol0 = new Protocol(""); + assertEquals("", protocol0.getProvidedProtocol()); + Protocol protocol1 = new Protocol("protocol"); + assertEquals("protocol", protocol1.getProvidedProtocol()); + } - @Test - public void testEquals() throws Exception { - Protocol protocol0 = new Protocol( "" ); - Protocol protocol1 = new Protocol( "protocol" ); - Protocol protocol2 = new Protocol( "protocol" ); - assertTrue( !protocol0.equals( protocol1 ) ); - assertTrue( !protocol0.equals( protocol2 ) ); - assertTrue( protocol1.equals( protocol2 ) ); - assertTrue( !protocol1.equals( null ) ); - assertTrue( !protocol1.equals( new Object() ) ); - } + @Test + public void testEquals() throws Exception { + Protocol protocol0 = new Protocol(""); + Protocol protocol1 = new Protocol("protocol"); + Protocol protocol2 = new Protocol("protocol"); + assertTrue(!protocol0.equals(protocol1)); + assertTrue(!protocol0.equals(protocol2)); + assertTrue(protocol1.equals(protocol2)); + assertTrue(!protocol1.equals(null)); + assertTrue(!protocol1.equals(new Object())); + } - @Test - public void testHashCode() throws Exception { - Protocol protocol0 = new Protocol( "" ); - Protocol protocol1 = new Protocol( "protocol" ); - Protocol protocol2 = new Protocol( "protocol" ); - assertNotEquals( protocol0, protocol1 ); - assertNotEquals( protocol0, protocol2 ); - assertEquals( protocol1, protocol2 ); - } + @Test + public void testHashCode() throws Exception { + Protocol protocol0 = new Protocol(""); + Protocol protocol1 = new Protocol("protocol"); + Protocol protocol2 = new Protocol("protocol"); + assertNotEquals(protocol0, protocol1); + assertNotEquals(protocol0, protocol2); + assertEquals(protocol1, protocol2); + } } \ No newline at end of file diff --git a/src/test/java/org/java_websocket/server/AllServerTests.java b/src/test/java/org/java_websocket/server/AllServerTests.java index 4009a6b40..9f7683552 100644 --- a/src/test/java/org/java_websocket/server/AllServerTests.java +++ b/src/test/java/org/java_websocket/server/AllServerTests.java @@ -31,11 +31,12 @@ @RunWith(Suite.class) @Suite.SuiteClasses({ - org.java_websocket.server.DefaultWebSocketServerFactoryTest.class, - org.java_websocket.protocols.ProtoclHandshakeRejectionTest.class + org.java_websocket.server.DefaultWebSocketServerFactoryTest.class, + org.java_websocket.protocols.ProtoclHandshakeRejectionTest.class }) /** * Start all tests for the server */ public class AllServerTests { + } diff --git a/src/test/java/org/java_websocket/server/CustomSSLWebSocketServerFactoryTest.java b/src/test/java/org/java_websocket/server/CustomSSLWebSocketServerFactoryTest.java index ff8c3c676..1222026ef 100644 --- a/src/test/java/org/java_websocket/server/CustomSSLWebSocketServerFactoryTest.java +++ b/src/test/java/org/java_websocket/server/CustomSSLWebSocketServerFactoryTest.java @@ -24,137 +24,150 @@ public class CustomSSLWebSocketServerFactoryTest { - final String[] emptyArray = new String[0]; - @Test - public void testConstructor() throws NoSuchAlgorithmException { - try { - new CustomSSLWebSocketServerFactory(null, null, null); - fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException e) { - // Good - } - try { - new CustomSSLWebSocketServerFactory(null, null, null, null); - fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException e) { - // Good - } - try { - new CustomSSLWebSocketServerFactory(SSLContext.getDefault(), null, null, null); - fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException e) { - } - try { - new CustomSSLWebSocketServerFactory(SSLContext.getDefault(), null, null); - } catch (IllegalArgumentException e) { - fail("IllegalArgumentException should not be thrown"); - } - try { - new CustomSSLWebSocketServerFactory(SSLContext.getDefault(), Executors.newCachedThreadPool(), null, null); - } catch (IllegalArgumentException e) { - fail("IllegalArgumentException should not be thrown"); - } - try { - new CustomSSLWebSocketServerFactory(SSLContext.getDefault(), Executors.newCachedThreadPool(), emptyArray, null); - } catch (IllegalArgumentException e) { - fail("IllegalArgumentException should not be thrown"); - } - try { - new CustomSSLWebSocketServerFactory(SSLContext.getDefault(), Executors.newCachedThreadPool(), null, emptyArray); - } catch (IllegalArgumentException e) { - fail("IllegalArgumentException should not be thrown"); - } - try { - new CustomSSLWebSocketServerFactory(SSLContext.getDefault(), Executors.newCachedThreadPool(), emptyArray, emptyArray); - } catch (IllegalArgumentException e) { - fail("IllegalArgumentException should not be thrown"); - } - } - @Test - public void testCreateWebSocket() throws NoSuchAlgorithmException { - CustomSSLWebSocketServerFactory webSocketServerFactory = new CustomSSLWebSocketServerFactory(SSLContext.getDefault(), null, null); - CustomWebSocketAdapter webSocketAdapter = new CustomWebSocketAdapter(); - WebSocketImpl webSocketImpl = webSocketServerFactory.createWebSocket(webSocketAdapter, new Draft_6455()); - assertNotNull("webSocketImpl != null", webSocketImpl); - webSocketImpl = webSocketServerFactory.createWebSocket(webSocketAdapter, Collections.singletonList(new Draft_6455())); - assertNotNull("webSocketImpl != null", webSocketImpl); - } - - @Test - public void testWrapChannel() throws IOException, NoSuchAlgorithmException { - CustomSSLWebSocketServerFactory webSocketServerFactory = new CustomSSLWebSocketServerFactory(SSLContext.getDefault(), null, null); - SocketChannel channel = SocketChannel.open(); - try { - ByteChannel result = webSocketServerFactory.wrapChannel(channel, null); - } catch (NotYetConnectedException e) { - //We do not really connect - } - channel.close(); - webSocketServerFactory = new CustomSSLWebSocketServerFactory(SSLContext.getDefault(), new String[]{"TLSv1.2"}, new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA"}); - channel = SocketChannel.open(); - try { - ByteChannel result = webSocketServerFactory.wrapChannel(channel, null); - } catch (NotYetConnectedException e) { - //We do not really connect - } - channel.close(); - } - - @Test - public void testClose() { - DefaultWebSocketServerFactory webSocketServerFactory = new DefaultWebSocketServerFactory(); - webSocketServerFactory.close(); - } - - private static class CustomWebSocketAdapter extends WebSocketAdapter { - @Override - public void onWebsocketMessage(WebSocket conn, String message) { - - } - - @Override - public void onWebsocketMessage(WebSocket conn, ByteBuffer blob) { - - } - - @Override - public void onWebsocketOpen(WebSocket conn, Handshakedata d) { - - } - - @Override - public void onWebsocketClose(WebSocket ws, int code, String reason, boolean remote) { - - } - - @Override - public void onWebsocketClosing(WebSocket ws, int code, String reason, boolean remote) { - - } - - @Override - public void onWebsocketCloseInitiated(WebSocket ws, int code, String reason) { - - } - - @Override - public void onWebsocketError(WebSocket conn, Exception ex) { - - } - - @Override - public void onWriteDemand(WebSocket conn) { - - } - - @Override - public InetSocketAddress getLocalSocketAddress(WebSocket conn) { - return null; - } - - @Override - public InetSocketAddress getRemoteSocketAddress(WebSocket conn) { - return null; - } + final String[] emptyArray = new String[0]; + + @Test + public void testConstructor() throws NoSuchAlgorithmException { + try { + new CustomSSLWebSocketServerFactory(null, null, null); + fail("IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException e) { + // Good } + try { + new CustomSSLWebSocketServerFactory(null, null, null, null); + fail("IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException e) { + // Good + } + try { + new CustomSSLWebSocketServerFactory(SSLContext.getDefault(), null, null, null); + fail("IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException e) { + } + try { + new CustomSSLWebSocketServerFactory(SSLContext.getDefault(), null, null); + } catch (IllegalArgumentException e) { + fail("IllegalArgumentException should not be thrown"); + } + try { + new CustomSSLWebSocketServerFactory(SSLContext.getDefault(), Executors.newCachedThreadPool(), + null, null); + } catch (IllegalArgumentException e) { + fail("IllegalArgumentException should not be thrown"); + } + try { + new CustomSSLWebSocketServerFactory(SSLContext.getDefault(), Executors.newCachedThreadPool(), + emptyArray, null); + } catch (IllegalArgumentException e) { + fail("IllegalArgumentException should not be thrown"); + } + try { + new CustomSSLWebSocketServerFactory(SSLContext.getDefault(), Executors.newCachedThreadPool(), + null, emptyArray); + } catch (IllegalArgumentException e) { + fail("IllegalArgumentException should not be thrown"); + } + try { + new CustomSSLWebSocketServerFactory(SSLContext.getDefault(), Executors.newCachedThreadPool(), + emptyArray, emptyArray); + } catch (IllegalArgumentException e) { + fail("IllegalArgumentException should not be thrown"); + } + } + + @Test + public void testCreateWebSocket() throws NoSuchAlgorithmException { + CustomSSLWebSocketServerFactory webSocketServerFactory = new CustomSSLWebSocketServerFactory( + SSLContext.getDefault(), null, null); + CustomWebSocketAdapter webSocketAdapter = new CustomWebSocketAdapter(); + WebSocketImpl webSocketImpl = webSocketServerFactory + .createWebSocket(webSocketAdapter, new Draft_6455()); + assertNotNull("webSocketImpl != null", webSocketImpl); + webSocketImpl = webSocketServerFactory + .createWebSocket(webSocketAdapter, Collections.singletonList(new Draft_6455())); + assertNotNull("webSocketImpl != null", webSocketImpl); + } + + @Test + public void testWrapChannel() throws IOException, NoSuchAlgorithmException { + CustomSSLWebSocketServerFactory webSocketServerFactory = new CustomSSLWebSocketServerFactory( + SSLContext.getDefault(), null, null); + SocketChannel channel = SocketChannel.open(); + try { + ByteChannel result = webSocketServerFactory.wrapChannel(channel, null); + } catch (NotYetConnectedException e) { + //We do not really connect + } + channel.close(); + webSocketServerFactory = new CustomSSLWebSocketServerFactory(SSLContext.getDefault(), + new String[]{"TLSv1.2"}, + new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA"}); + channel = SocketChannel.open(); + try { + ByteChannel result = webSocketServerFactory.wrapChannel(channel, null); + } catch (NotYetConnectedException e) { + //We do not really connect + } + channel.close(); + } + + @Test + public void testClose() { + DefaultWebSocketServerFactory webSocketServerFactory = new DefaultWebSocketServerFactory(); + webSocketServerFactory.close(); + } + + private static class CustomWebSocketAdapter extends WebSocketAdapter { + + @Override + public void onWebsocketMessage(WebSocket conn, String message) { + + } + + @Override + public void onWebsocketMessage(WebSocket conn, ByteBuffer blob) { + + } + + @Override + public void onWebsocketOpen(WebSocket conn, Handshakedata d) { + + } + + @Override + public void onWebsocketClose(WebSocket ws, int code, String reason, boolean remote) { + + } + + @Override + public void onWebsocketClosing(WebSocket ws, int code, String reason, boolean remote) { + + } + + @Override + public void onWebsocketCloseInitiated(WebSocket ws, int code, String reason) { + + } + + @Override + public void onWebsocketError(WebSocket conn, Exception ex) { + + } + + @Override + public void onWriteDemand(WebSocket conn) { + + } + + @Override + public InetSocketAddress getLocalSocketAddress(WebSocket conn) { + return null; + } + + @Override + public InetSocketAddress getRemoteSocketAddress(WebSocket conn) { + return null; + } + } } diff --git a/src/test/java/org/java_websocket/server/DefaultSSLWebSocketServerFactoryTest.java b/src/test/java/org/java_websocket/server/DefaultSSLWebSocketServerFactoryTest.java index 75f89b932..d2dd8f73f 100644 --- a/src/test/java/org/java_websocket/server/DefaultSSLWebSocketServerFactoryTest.java +++ b/src/test/java/org/java_websocket/server/DefaultSSLWebSocketServerFactoryTest.java @@ -27,113 +27,120 @@ public class DefaultSSLWebSocketServerFactoryTest { - @Test - public void testConstructor() throws NoSuchAlgorithmException { - try { - new DefaultSSLWebSocketServerFactory(null); - fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException e) { - // Good - } - try { - new DefaultSSLWebSocketServerFactory(null, null); - fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException e) { - // Good - } - try { - new DefaultSSLWebSocketServerFactory(SSLContext.getDefault(), null); - fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException e) { - } - try { - new DefaultSSLWebSocketServerFactory(SSLContext.getDefault()); - } catch (IllegalArgumentException e) { - fail("IllegalArgumentException should not be thrown"); - } - try { - new DefaultSSLWebSocketServerFactory(SSLContext.getDefault(), Executors.newCachedThreadPool()); - } catch (IllegalArgumentException e) { - fail("IllegalArgumentException should not be thrown"); - } - } - @Test - public void testCreateWebSocket() throws NoSuchAlgorithmException { - DefaultSSLWebSocketServerFactory webSocketServerFactory = new DefaultSSLWebSocketServerFactory(SSLContext.getDefault()); - CustomWebSocketAdapter webSocketAdapter = new CustomWebSocketAdapter(); - WebSocketImpl webSocketImpl = webSocketServerFactory.createWebSocket(webSocketAdapter, new Draft_6455()); - assertNotNull("webSocketImpl != null", webSocketImpl); - webSocketImpl = webSocketServerFactory.createWebSocket(webSocketAdapter, Collections.singletonList(new Draft_6455())); - assertNotNull("webSocketImpl != null", webSocketImpl); - } - - @Test - public void testWrapChannel() throws IOException, NoSuchAlgorithmException { - DefaultSSLWebSocketServerFactory webSocketServerFactory = new DefaultSSLWebSocketServerFactory(SSLContext.getDefault()); - SocketChannel channel = SocketChannel.open(); - try { - ByteChannel result = webSocketServerFactory.wrapChannel(channel, null); - } catch (NotYetConnectedException e) { - //We do not really connect - } - channel.close(); - } - - @Test - public void testClose() { - DefaultWebSocketServerFactory webSocketServerFactory = new DefaultWebSocketServerFactory(); - webSocketServerFactory.close(); - } - - private static class CustomWebSocketAdapter extends WebSocketAdapter { - @Override - public void onWebsocketMessage(WebSocket conn, String message) { - - } - - @Override - public void onWebsocketMessage(WebSocket conn, ByteBuffer blob) { - - } - - @Override - public void onWebsocketOpen(WebSocket conn, Handshakedata d) { - - } - - @Override - public void onWebsocketClose(WebSocket ws, int code, String reason, boolean remote) { - - } - - @Override - public void onWebsocketClosing(WebSocket ws, int code, String reason, boolean remote) { - - } - - @Override - public void onWebsocketCloseInitiated(WebSocket ws, int code, String reason) { - - } - - @Override - public void onWebsocketError(WebSocket conn, Exception ex) { - - } - - @Override - public void onWriteDemand(WebSocket conn) { - - } - - @Override - public InetSocketAddress getLocalSocketAddress(WebSocket conn) { - return null; - } - - @Override - public InetSocketAddress getRemoteSocketAddress(WebSocket conn) { - return null; - } + @Test + public void testConstructor() throws NoSuchAlgorithmException { + try { + new DefaultSSLWebSocketServerFactory(null); + fail("IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException e) { + // Good } + try { + new DefaultSSLWebSocketServerFactory(null, null); + fail("IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException e) { + // Good + } + try { + new DefaultSSLWebSocketServerFactory(SSLContext.getDefault(), null); + fail("IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException e) { + } + try { + new DefaultSSLWebSocketServerFactory(SSLContext.getDefault()); + } catch (IllegalArgumentException e) { + fail("IllegalArgumentException should not be thrown"); + } + try { + new DefaultSSLWebSocketServerFactory(SSLContext.getDefault(), + Executors.newCachedThreadPool()); + } catch (IllegalArgumentException e) { + fail("IllegalArgumentException should not be thrown"); + } + } + + @Test + public void testCreateWebSocket() throws NoSuchAlgorithmException { + DefaultSSLWebSocketServerFactory webSocketServerFactory = new DefaultSSLWebSocketServerFactory( + SSLContext.getDefault()); + CustomWebSocketAdapter webSocketAdapter = new CustomWebSocketAdapter(); + WebSocketImpl webSocketImpl = webSocketServerFactory + .createWebSocket(webSocketAdapter, new Draft_6455()); + assertNotNull("webSocketImpl != null", webSocketImpl); + webSocketImpl = webSocketServerFactory + .createWebSocket(webSocketAdapter, Collections.singletonList(new Draft_6455())); + assertNotNull("webSocketImpl != null", webSocketImpl); + } + + @Test + public void testWrapChannel() throws IOException, NoSuchAlgorithmException { + DefaultSSLWebSocketServerFactory webSocketServerFactory = new DefaultSSLWebSocketServerFactory( + SSLContext.getDefault()); + SocketChannel channel = SocketChannel.open(); + try { + ByteChannel result = webSocketServerFactory.wrapChannel(channel, null); + } catch (NotYetConnectedException e) { + //We do not really connect + } + channel.close(); + } + + @Test + public void testClose() { + DefaultWebSocketServerFactory webSocketServerFactory = new DefaultWebSocketServerFactory(); + webSocketServerFactory.close(); + } + + private static class CustomWebSocketAdapter extends WebSocketAdapter { + + @Override + public void onWebsocketMessage(WebSocket conn, String message) { + + } + + @Override + public void onWebsocketMessage(WebSocket conn, ByteBuffer blob) { + + } + + @Override + public void onWebsocketOpen(WebSocket conn, Handshakedata d) { + + } + + @Override + public void onWebsocketClose(WebSocket ws, int code, String reason, boolean remote) { + + } + + @Override + public void onWebsocketClosing(WebSocket ws, int code, String reason, boolean remote) { + + } + + @Override + public void onWebsocketCloseInitiated(WebSocket ws, int code, String reason) { + + } + + @Override + public void onWebsocketError(WebSocket conn, Exception ex) { + + } + + @Override + public void onWriteDemand(WebSocket conn) { + + } + + @Override + public InetSocketAddress getLocalSocketAddress(WebSocket conn) { + return null; + } + + @Override + public InetSocketAddress getRemoteSocketAddress(WebSocket conn) { + return null; + } + } } diff --git a/src/test/java/org/java_websocket/server/DefaultWebSocketServerFactoryTest.java b/src/test/java/org/java_websocket/server/DefaultWebSocketServerFactoryTest.java index f3f758cd3..13a65bfcc 100644 --- a/src/test/java/org/java_websocket/server/DefaultWebSocketServerFactoryTest.java +++ b/src/test/java/org/java_websocket/server/DefaultWebSocketServerFactoryTest.java @@ -19,78 +19,82 @@ public class DefaultWebSocketServerFactoryTest { - @Test - public void testCreateWebSocket() { - DefaultWebSocketServerFactory webSocketServerFactory = new DefaultWebSocketServerFactory(); - CustomWebSocketAdapter webSocketAdapter = new CustomWebSocketAdapter(); - WebSocketImpl webSocketImpl = webSocketServerFactory.createWebSocket(webSocketAdapter, new Draft_6455()); - assertNotNull("webSocketImpl != null", webSocketImpl); - webSocketImpl = webSocketServerFactory.createWebSocket(webSocketAdapter, Collections.singletonList(new Draft_6455())); - assertNotNull("webSocketImpl != null", webSocketImpl); - } + @Test + public void testCreateWebSocket() { + DefaultWebSocketServerFactory webSocketServerFactory = new DefaultWebSocketServerFactory(); + CustomWebSocketAdapter webSocketAdapter = new CustomWebSocketAdapter(); + WebSocketImpl webSocketImpl = webSocketServerFactory + .createWebSocket(webSocketAdapter, new Draft_6455()); + assertNotNull("webSocketImpl != null", webSocketImpl); + webSocketImpl = webSocketServerFactory + .createWebSocket(webSocketAdapter, Collections.singletonList(new Draft_6455())); + assertNotNull("webSocketImpl != null", webSocketImpl); + } + + @Test + public void testWrapChannel() { + DefaultWebSocketServerFactory webSocketServerFactory = new DefaultWebSocketServerFactory(); + SocketChannel channel = (new Socket()).getChannel(); + SocketChannel result = webSocketServerFactory.wrapChannel(channel, null); + assertSame("channel == result", channel, result); + } + + @Test + public void testClose() { + DefaultWebSocketServerFactory webSocketServerFactory = new DefaultWebSocketServerFactory(); + webSocketServerFactory.close(); + } + + private static class CustomWebSocketAdapter extends WebSocketAdapter { + + @Override + public void onWebsocketMessage(WebSocket conn, String message) { - @Test - public void testWrapChannel() { - DefaultWebSocketServerFactory webSocketServerFactory = new DefaultWebSocketServerFactory(); - SocketChannel channel = (new Socket()).getChannel(); - SocketChannel result = webSocketServerFactory.wrapChannel(channel, null); - assertSame("channel == result", channel, result); - } - @Test - public void testClose() { - DefaultWebSocketServerFactory webSocketServerFactory = new DefaultWebSocketServerFactory(); - webSocketServerFactory.close(); } - private static class CustomWebSocketAdapter extends WebSocketAdapter { - @Override - public void onWebsocketMessage(WebSocket conn, String message) { - - } + @Override + public void onWebsocketMessage(WebSocket conn, ByteBuffer blob) { - @Override - public void onWebsocketMessage(WebSocket conn, ByteBuffer blob) { - - } + } - @Override - public void onWebsocketOpen(WebSocket conn, Handshakedata d) { + @Override + public void onWebsocketOpen(WebSocket conn, Handshakedata d) { - } + } - @Override - public void onWebsocketClose(WebSocket ws, int code, String reason, boolean remote) { + @Override + public void onWebsocketClose(WebSocket ws, int code, String reason, boolean remote) { - } + } - @Override - public void onWebsocketClosing(WebSocket ws, int code, String reason, boolean remote) { + @Override + public void onWebsocketClosing(WebSocket ws, int code, String reason, boolean remote) { - } + } - @Override - public void onWebsocketCloseInitiated(WebSocket ws, int code, String reason) { + @Override + public void onWebsocketCloseInitiated(WebSocket ws, int code, String reason) { - } + } - @Override - public void onWebsocketError(WebSocket conn, Exception ex) { + @Override + public void onWebsocketError(WebSocket conn, Exception ex) { - } + } - @Override - public void onWriteDemand(WebSocket conn) { + @Override + public void onWriteDemand(WebSocket conn) { - } + } - @Override - public InetSocketAddress getLocalSocketAddress(WebSocket conn) { - return null; - } + @Override + public InetSocketAddress getLocalSocketAddress(WebSocket conn) { + return null; + } - @Override - public InetSocketAddress getRemoteSocketAddress(WebSocket conn) { - return null; - } + @Override + public InetSocketAddress getRemoteSocketAddress(WebSocket conn) { + return null; } + } } diff --git a/src/test/java/org/java_websocket/server/SSLParametersWebSocketServerFactoryTest.java b/src/test/java/org/java_websocket/server/SSLParametersWebSocketServerFactoryTest.java index 6ee236926..5b6300dd5 100644 --- a/src/test/java/org/java_websocket/server/SSLParametersWebSocketServerFactoryTest.java +++ b/src/test/java/org/java_websocket/server/SSLParametersWebSocketServerFactoryTest.java @@ -25,107 +25,114 @@ public class SSLParametersWebSocketServerFactoryTest { - @Test - public void testConstructor() throws NoSuchAlgorithmException { - try { - new SSLParametersWebSocketServerFactory(null, null); - fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException e) { - // Good - } - try { - new SSLParametersWebSocketServerFactory(SSLContext.getDefault(), null); - fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException e) { - } - try { - new SSLParametersWebSocketServerFactory(SSLContext.getDefault(), new SSLParameters()); - } catch (IllegalArgumentException e) { - fail("IllegalArgumentException should not be thrown"); - } - try { - new SSLParametersWebSocketServerFactory(SSLContext.getDefault(), Executors.newCachedThreadPool(), new SSLParameters()); - } catch (IllegalArgumentException e) { - fail("IllegalArgumentException should not be thrown"); - } + @Test + public void testConstructor() throws NoSuchAlgorithmException { + try { + new SSLParametersWebSocketServerFactory(null, null); + fail("IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException e) { + // Good } - @Test - public void testCreateWebSocket() throws NoSuchAlgorithmException { - SSLParametersWebSocketServerFactory webSocketServerFactory = new SSLParametersWebSocketServerFactory(SSLContext.getDefault(), new SSLParameters()); - CustomWebSocketAdapter webSocketAdapter = new CustomWebSocketAdapter(); - WebSocketImpl webSocketImpl = webSocketServerFactory.createWebSocket(webSocketAdapter, new Draft_6455()); - assertNotNull("webSocketImpl != null", webSocketImpl); - webSocketImpl = webSocketServerFactory.createWebSocket(webSocketAdapter, Collections.singletonList(new Draft_6455())); - assertNotNull("webSocketImpl != null", webSocketImpl); + try { + new SSLParametersWebSocketServerFactory(SSLContext.getDefault(), null); + fail("IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException e) { } - - @Test - public void testWrapChannel() throws IOException, NoSuchAlgorithmException { - SSLParametersWebSocketServerFactory webSocketServerFactory = new SSLParametersWebSocketServerFactory(SSLContext.getDefault(), new SSLParameters()); - SocketChannel channel = SocketChannel.open(); - try { - ByteChannel result = webSocketServerFactory.wrapChannel(channel, null); - } catch (NotYetConnectedException e) { - //We do not really connect - } - channel.close(); + try { + new SSLParametersWebSocketServerFactory(SSLContext.getDefault(), new SSLParameters()); + } catch (IllegalArgumentException e) { + fail("IllegalArgumentException should not be thrown"); } - - @Test - public void testClose() { - DefaultWebSocketServerFactory webSocketServerFactory = new DefaultWebSocketServerFactory(); - webSocketServerFactory.close(); + try { + new SSLParametersWebSocketServerFactory(SSLContext.getDefault(), + Executors.newCachedThreadPool(), new SSLParameters()); + } catch (IllegalArgumentException e) { + fail("IllegalArgumentException should not be thrown"); } + } + + @Test + public void testCreateWebSocket() throws NoSuchAlgorithmException { + SSLParametersWebSocketServerFactory webSocketServerFactory = new SSLParametersWebSocketServerFactory( + SSLContext.getDefault(), new SSLParameters()); + CustomWebSocketAdapter webSocketAdapter = new CustomWebSocketAdapter(); + WebSocketImpl webSocketImpl = webSocketServerFactory + .createWebSocket(webSocketAdapter, new Draft_6455()); + assertNotNull("webSocketImpl != null", webSocketImpl); + webSocketImpl = webSocketServerFactory + .createWebSocket(webSocketAdapter, Collections.singletonList(new Draft_6455())); + assertNotNull("webSocketImpl != null", webSocketImpl); + } + + @Test + public void testWrapChannel() throws IOException, NoSuchAlgorithmException { + SSLParametersWebSocketServerFactory webSocketServerFactory = new SSLParametersWebSocketServerFactory( + SSLContext.getDefault(), new SSLParameters()); + SocketChannel channel = SocketChannel.open(); + try { + ByteChannel result = webSocketServerFactory.wrapChannel(channel, null); + } catch (NotYetConnectedException e) { + //We do not really connect + } + channel.close(); + } - private static class CustomWebSocketAdapter extends WebSocketAdapter { - @Override - public void onWebsocketMessage(WebSocket conn, String message) { + @Test + public void testClose() { + DefaultWebSocketServerFactory webSocketServerFactory = new DefaultWebSocketServerFactory(); + webSocketServerFactory.close(); + } - } + private static class CustomWebSocketAdapter extends WebSocketAdapter { - @Override - public void onWebsocketMessage(WebSocket conn, ByteBuffer blob) { + @Override + public void onWebsocketMessage(WebSocket conn, String message) { - } + } + + @Override + public void onWebsocketMessage(WebSocket conn, ByteBuffer blob) { + + } - @Override - public void onWebsocketOpen(WebSocket conn, Handshakedata d) { + @Override + public void onWebsocketOpen(WebSocket conn, Handshakedata d) { - } + } - @Override - public void onWebsocketClose(WebSocket ws, int code, String reason, boolean remote) { + @Override + public void onWebsocketClose(WebSocket ws, int code, String reason, boolean remote) { - } + } - @Override - public void onWebsocketClosing(WebSocket ws, int code, String reason, boolean remote) { + @Override + public void onWebsocketClosing(WebSocket ws, int code, String reason, boolean remote) { - } + } - @Override - public void onWebsocketCloseInitiated(WebSocket ws, int code, String reason) { + @Override + public void onWebsocketCloseInitiated(WebSocket ws, int code, String reason) { - } + } - @Override - public void onWebsocketError(WebSocket conn, Exception ex) { + @Override + public void onWebsocketError(WebSocket conn, Exception ex) { - } + } - @Override - public void onWriteDemand(WebSocket conn) { + @Override + public void onWriteDemand(WebSocket conn) { - } + } - @Override - public InetSocketAddress getLocalSocketAddress(WebSocket conn) { - return null; - } + @Override + public InetSocketAddress getLocalSocketAddress(WebSocket conn) { + return null; + } - @Override - public InetSocketAddress getRemoteSocketAddress(WebSocket conn) { - return null; - } + @Override + public InetSocketAddress getRemoteSocketAddress(WebSocket conn) { + return null; } + } } diff --git a/src/test/java/org/java_websocket/server/WebSocketServerTest.java b/src/test/java/org/java_websocket/server/WebSocketServerTest.java index d7ab804f6..1f45a9e1f 100644 --- a/src/test/java/org/java_websocket/server/WebSocketServerTest.java +++ b/src/test/java/org/java_websocket/server/WebSocketServerTest.java @@ -47,179 +47,190 @@ public class WebSocketServerTest { - @Test - public void testConstructor() { - List draftCollection = Collections.singletonList(new Draft_6455()); - Collection webSocketCollection = new HashSet(); - InetSocketAddress inetAddress = new InetSocketAddress(1337); - - try { - WebSocketServer server = new MyWebSocketServer(null, 1,draftCollection, webSocketCollection ); - fail("Should fail"); - } catch (IllegalArgumentException e) { - //OK - } - try { - WebSocketServer server = new MyWebSocketServer(inetAddress, 0,draftCollection, webSocketCollection ); - fail("Should fail"); - } catch (IllegalArgumentException e) { - //OK - } - try { - WebSocketServer server = new MyWebSocketServer(inetAddress, -1,draftCollection, webSocketCollection ); - fail("Should fail"); - } catch (IllegalArgumentException e) { - //OK - } - try { - WebSocketServer server = new MyWebSocketServer(inetAddress, Integer.MIN_VALUE, draftCollection, webSocketCollection ); - fail("Should fail"); - } catch (IllegalArgumentException e) { - //OK - } - try { - WebSocketServer server = new MyWebSocketServer(inetAddress, Integer.MIN_VALUE, draftCollection, webSocketCollection ); - fail("Should fail"); - } catch (IllegalArgumentException e) { - //OK - } - try { - WebSocketServer server = new MyWebSocketServer(inetAddress, 1, draftCollection, null ); - fail("Should fail"); - } catch (IllegalArgumentException e) { - //OK - } - - try { - WebSocketServer server = new MyWebSocketServer(inetAddress, 1, draftCollection, webSocketCollection ); - // OK - } catch (IllegalArgumentException e) { - fail("Should not fail"); - } - try { - WebSocketServer server = new MyWebSocketServer(inetAddress, 1, null, webSocketCollection ); - // OK - } catch (IllegalArgumentException e) { - fail("Should not fail"); - } - } - - - @Test - public void testGetAddress() throws IOException { - int port = SocketUtil.getAvailablePort(); - InetSocketAddress inetSocketAddress = new InetSocketAddress(port); - MyWebSocketServer server = new MyWebSocketServer(port); - assertEquals(inetSocketAddress, server.getAddress()); - } - - @Test - public void testGetDrafts() { - List draftCollection = Collections.singletonList(new Draft_6455()); - Collection webSocketCollection = new HashSet(); - InetSocketAddress inetAddress = new InetSocketAddress(1337); - MyWebSocketServer server = new MyWebSocketServer(inetAddress, 1, draftCollection, webSocketCollection); - assertEquals(1, server.getDraft().size()); - assertEquals(draftCollection.get(0), server.getDraft().get(0)); - } - - @Test - public void testGetPort() throws IOException, InterruptedException { - int port = SocketUtil.getAvailablePort(); - CountDownLatch countServerDownLatch = new CountDownLatch( 1 ); - MyWebSocketServer server = new MyWebSocketServer(port); - assertEquals(port, server.getPort()); - server = new MyWebSocketServer(0, countServerDownLatch); - assertEquals(0, server.getPort()); - server.start(); - countServerDownLatch.await(); - assertNotEquals(0, server.getPort()); - } - - @Test - public void testBroadcast() { - MyWebSocketServer server = new MyWebSocketServer(1337); - try { - server.broadcast((byte[]) null, Collections.emptyList()); - fail("Should fail"); - } catch (IllegalArgumentException e) { - // OK - } - try { - server.broadcast((ByteBuffer) null, Collections.emptyList()); - fail("Should fail"); - } catch (IllegalArgumentException e) { - // OK - } - try { - server.broadcast((String) null, Collections.emptyList()); - fail("Should fail"); - } catch (IllegalArgumentException e) { - // OK - } - try { - server.broadcast(new byte[] {(byte) 0xD0}, null); - fail("Should fail"); - } catch (IllegalArgumentException e) { - // OK - } - try { - server.broadcast(ByteBuffer.wrap(new byte[] {(byte) 0xD0}), null); - fail("Should fail"); - } catch (IllegalArgumentException e) { - // OK - } - try { - server.broadcast("", null); - fail("Should fail"); - } catch (IllegalArgumentException e) { - // OK - } - try { - server.broadcast("", Collections.emptyList()); - // OK - } catch (IllegalArgumentException e) { - fail("Should not fail"); - } - } - private static class MyWebSocketServer extends WebSocketServer { - private CountDownLatch serverLatch = null; - - public MyWebSocketServer(InetSocketAddress address , int decodercount , List drafts , Collection connectionscontainer) { - super(address, decodercount, drafts, connectionscontainer); - } - public MyWebSocketServer(int port, CountDownLatch serverLatch) { - super(new InetSocketAddress(port)); - this.serverLatch = serverLatch; - } - public MyWebSocketServer(int port) { - this(port, null); - } - - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - } - - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - } - - @Override - public void onMessage(WebSocket conn, String message) { - - } - - @Override - public void onError(WebSocket conn, Exception ex) { - ex.printStackTrace(); - } - - @Override - public void onStart() { - if (serverLatch != null) { - serverLatch.countDown(); - } - } + @Test + public void testConstructor() { + List draftCollection = Collections.singletonList(new Draft_6455()); + Collection webSocketCollection = new HashSet(); + InetSocketAddress inetAddress = new InetSocketAddress(1337); + + try { + WebSocketServer server = new MyWebSocketServer(null, 1, draftCollection, webSocketCollection); + fail("Should fail"); + } catch (IllegalArgumentException e) { + //OK } + try { + WebSocketServer server = new MyWebSocketServer(inetAddress, 0, draftCollection, + webSocketCollection); + fail("Should fail"); + } catch (IllegalArgumentException e) { + //OK + } + try { + WebSocketServer server = new MyWebSocketServer(inetAddress, -1, draftCollection, + webSocketCollection); + fail("Should fail"); + } catch (IllegalArgumentException e) { + //OK + } + try { + WebSocketServer server = new MyWebSocketServer(inetAddress, Integer.MIN_VALUE, + draftCollection, webSocketCollection); + fail("Should fail"); + } catch (IllegalArgumentException e) { + //OK + } + try { + WebSocketServer server = new MyWebSocketServer(inetAddress, Integer.MIN_VALUE, + draftCollection, webSocketCollection); + fail("Should fail"); + } catch (IllegalArgumentException e) { + //OK + } + try { + WebSocketServer server = new MyWebSocketServer(inetAddress, 1, draftCollection, null); + fail("Should fail"); + } catch (IllegalArgumentException e) { + //OK + } + + try { + WebSocketServer server = new MyWebSocketServer(inetAddress, 1, draftCollection, + webSocketCollection); + // OK + } catch (IllegalArgumentException e) { + fail("Should not fail"); + } + try { + WebSocketServer server = new MyWebSocketServer(inetAddress, 1, null, webSocketCollection); + // OK + } catch (IllegalArgumentException e) { + fail("Should not fail"); + } + } + + + @Test + public void testGetAddress() throws IOException { + int port = SocketUtil.getAvailablePort(); + InetSocketAddress inetSocketAddress = new InetSocketAddress(port); + MyWebSocketServer server = new MyWebSocketServer(port); + assertEquals(inetSocketAddress, server.getAddress()); + } + + @Test + public void testGetDrafts() { + List draftCollection = Collections.singletonList(new Draft_6455()); + Collection webSocketCollection = new HashSet(); + InetSocketAddress inetAddress = new InetSocketAddress(1337); + MyWebSocketServer server = new MyWebSocketServer(inetAddress, 1, draftCollection, + webSocketCollection); + assertEquals(1, server.getDraft().size()); + assertEquals(draftCollection.get(0), server.getDraft().get(0)); + } + + @Test + public void testGetPort() throws IOException, InterruptedException { + int port = SocketUtil.getAvailablePort(); + CountDownLatch countServerDownLatch = new CountDownLatch(1); + MyWebSocketServer server = new MyWebSocketServer(port); + assertEquals(port, server.getPort()); + server = new MyWebSocketServer(0, countServerDownLatch); + assertEquals(0, server.getPort()); + server.start(); + countServerDownLatch.await(); + assertNotEquals(0, server.getPort()); + } + + @Test + public void testBroadcast() { + MyWebSocketServer server = new MyWebSocketServer(1337); + try { + server.broadcast((byte[]) null, Collections.emptyList()); + fail("Should fail"); + } catch (IllegalArgumentException e) { + // OK + } + try { + server.broadcast((ByteBuffer) null, Collections.emptyList()); + fail("Should fail"); + } catch (IllegalArgumentException e) { + // OK + } + try { + server.broadcast((String) null, Collections.emptyList()); + fail("Should fail"); + } catch (IllegalArgumentException e) { + // OK + } + try { + server.broadcast(new byte[]{(byte) 0xD0}, null); + fail("Should fail"); + } catch (IllegalArgumentException e) { + // OK + } + try { + server.broadcast(ByteBuffer.wrap(new byte[]{(byte) 0xD0}), null); + fail("Should fail"); + } catch (IllegalArgumentException e) { + // OK + } + try { + server.broadcast("", null); + fail("Should fail"); + } catch (IllegalArgumentException e) { + // OK + } + try { + server.broadcast("", Collections.emptyList()); + // OK + } catch (IllegalArgumentException e) { + fail("Should not fail"); + } + } + + private static class MyWebSocketServer extends WebSocketServer { + + private CountDownLatch serverLatch = null; + + public MyWebSocketServer(InetSocketAddress address, int decodercount, List drafts, + Collection connectionscontainer) { + super(address, decodercount, drafts, connectionscontainer); + } + + public MyWebSocketServer(int port, CountDownLatch serverLatch) { + super(new InetSocketAddress(port)); + this.serverLatch = serverLatch; + } + + public MyWebSocketServer(int port) { + this(port, null); + } + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + ex.printStackTrace(); + } + + @Override + public void onStart() { + if (serverLatch != null) { + serverLatch.countDown(); + } + } + } } diff --git a/src/test/java/org/java_websocket/util/Base64Test.java b/src/test/java/org/java_websocket/util/Base64Test.java index 7670e670b..a45ddb9be 100644 --- a/src/test/java/org/java_websocket/util/Base64Test.java +++ b/src/test/java/org/java_websocket/util/Base64Test.java @@ -34,94 +34,96 @@ public class Base64Test { - @Rule public final ExpectedException thrown = ExpectedException.none(); + @Rule + public final ExpectedException thrown = ExpectedException.none(); - @Test - public void testEncodeBytes() throws IOException { - Assert.assertEquals("", Base64.encodeBytes(new byte[0])); - Assert.assertEquals("QHE=", - Base64.encodeBytes(new byte[] {49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 2, 2, 0)); - Assert.assertEquals("H4sIAAAAAAAAADMEALfv3IMBAAAA", - Base64.encodeBytes(new byte[] {49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 0, 1, 6)); - Assert.assertEquals("H4sIAAAAAAAAAHMoBABQHKKWAgAAAA==", - Base64.encodeBytes(new byte[] {49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 2, 2, 18)); - Assert.assertEquals("F63=", - Base64.encodeBytes(new byte[] {49, 121, 64, 113, 63, 43, -24, 62, 4, 48}, 2, 2, 32)); - Assert.assertEquals("6sg7---------6Bc0-0F699L-V----==", - Base64.encodeBytes(new byte[] {49, 121, 64, 113, 63, 43, -24, 62, 4, 48}, 2, 2, 34)); - } + @Test + public void testEncodeBytes() throws IOException { + Assert.assertEquals("", Base64.encodeBytes(new byte[0])); + Assert.assertEquals("QHE=", + Base64.encodeBytes(new byte[]{49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 2, 2, 0)); + Assert.assertEquals("H4sIAAAAAAAAADMEALfv3IMBAAAA", + Base64.encodeBytes(new byte[]{49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 0, 1, 6)); + Assert.assertEquals("H4sIAAAAAAAAAHMoBABQHKKWAgAAAA==", + Base64.encodeBytes(new byte[]{49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 2, 2, 18)); + Assert.assertEquals("F63=", + Base64.encodeBytes(new byte[]{49, 121, 64, 113, 63, 43, -24, 62, 4, 48}, 2, 2, 32)); + Assert.assertEquals("6sg7---------6Bc0-0F699L-V----==", + Base64.encodeBytes(new byte[]{49, 121, 64, 113, 63, 43, -24, 62, 4, 48}, 2, 2, 34)); + } - @Test - public void testEncodeBytes2() throws IOException { - thrown.expect(IllegalArgumentException.class); - Base64.encodeBytes(new byte[0], -2, -2, -56); - } + @Test + public void testEncodeBytes2() throws IOException { + thrown.expect(IllegalArgumentException.class); + Base64.encodeBytes(new byte[0], -2, -2, -56); + } - @Test - public void testEncodeBytes3() throws IOException { - thrown.expect(IllegalArgumentException.class); - Base64.encodeBytes(new byte[] {64, -128, 32, 18, 16, 16, 0, 18, 16}, - 2064072977, -2064007440, 10); - } + @Test + public void testEncodeBytes3() throws IOException { + thrown.expect(IllegalArgumentException.class); + Base64.encodeBytes(new byte[]{64, -128, 32, 18, 16, 16, 0, 18, 16}, + 2064072977, -2064007440, 10); + } - @Test - public void testEncodeBytes4() { - thrown.expect(NullPointerException.class); - Base64.encodeBytes(null); - } + @Test + public void testEncodeBytes4() { + thrown.expect(NullPointerException.class); + Base64.encodeBytes(null); + } - @Test - public void testEncodeBytes5() throws IOException { - thrown.expect(IllegalArgumentException.class); - Base64.encodeBytes(null, 32766, 0, 8); - } + @Test + public void testEncodeBytes5() throws IOException { + thrown.expect(IllegalArgumentException.class); + Base64.encodeBytes(null, 32766, 0, 8); + } - @Test - public void testEncodeBytesToBytes1() throws IOException { - Assert.assertArrayEquals(new byte[] {95, 68, 111, 78, 55, 45, 61, 61}, - Base64.encodeBytesToBytes(new byte[] {-108, -19, 24, 32}, 0, 4, 32)); - Assert.assertArrayEquals(new byte[] {95, 68, 111, 78, 55, 67, 111, 61}, - Base64.encodeBytesToBytes(new byte[] {-108, -19, 24, 32, -35}, 0, 5, 40)); - Assert.assertArrayEquals(new byte[] {95, 68, 111, 78, 55, 67, 111, 61}, - Base64.encodeBytesToBytes(new byte[] {-108, -19, 24, 32, -35}, 0, 5, 32)); - Assert.assertArrayEquals(new byte[] {87, 50, 77, 61}, - Base64.encodeBytesToBytes(new byte[] {115, 42, 123, 99, 10, -33, 75, 30, 91, 99}, 8, 2, 48)); - Assert.assertArrayEquals(new byte[] {87, 50, 77, 61}, - Base64.encodeBytesToBytes(new byte[] {115, 42, 123, 99, 10, -33, 75, 30, 91, 99}, 8, 2, 56)); - Assert.assertArrayEquals(new byte[] {76, 53, 66, 61}, - Base64.encodeBytesToBytes(new byte[] {113, 42, 123, 99, 10, -33, 75, 30, 88, 99}, 8, 2, 36));Assert.assertArrayEquals(new byte[] {87, 71, 77, 61}, - Base64.encodeBytesToBytes(new byte[] {113, 42, 123, 99, 10, -33, 75, 30, 88, 99}, 8, 2, 4)); - } + @Test + public void testEncodeBytesToBytes1() throws IOException { + Assert.assertArrayEquals(new byte[]{95, 68, 111, 78, 55, 45, 61, 61}, + Base64.encodeBytesToBytes(new byte[]{-108, -19, 24, 32}, 0, 4, 32)); + Assert.assertArrayEquals(new byte[]{95, 68, 111, 78, 55, 67, 111, 61}, + Base64.encodeBytesToBytes(new byte[]{-108, -19, 24, 32, -35}, 0, 5, 40)); + Assert.assertArrayEquals(new byte[]{95, 68, 111, 78, 55, 67, 111, 61}, + Base64.encodeBytesToBytes(new byte[]{-108, -19, 24, 32, -35}, 0, 5, 32)); + Assert.assertArrayEquals(new byte[]{87, 50, 77, 61}, + Base64.encodeBytesToBytes(new byte[]{115, 42, 123, 99, 10, -33, 75, 30, 91, 99}, 8, 2, 48)); + Assert.assertArrayEquals(new byte[]{87, 50, 77, 61}, + Base64.encodeBytesToBytes(new byte[]{115, 42, 123, 99, 10, -33, 75, 30, 91, 99}, 8, 2, 56)); + Assert.assertArrayEquals(new byte[]{76, 53, 66, 61}, + Base64.encodeBytesToBytes(new byte[]{113, 42, 123, 99, 10, -33, 75, 30, 88, 99}, 8, 2, 36)); + Assert.assertArrayEquals(new byte[]{87, 71, 77, 61}, + Base64.encodeBytesToBytes(new byte[]{113, 42, 123, 99, 10, -33, 75, 30, 88, 99}, 8, 2, 4)); + } - @Test - public void testEncodeBytesToBytes2() throws IOException { - thrown.expect(IllegalArgumentException.class); - Base64.encodeBytesToBytes(new byte[] {83, 10, 91, 67, 42, -1, 107, 62, 91, 67}, 8, 6, 26); - } + @Test + public void testEncodeBytesToBytes2() throws IOException { + thrown.expect(IllegalArgumentException.class); + Base64.encodeBytesToBytes(new byte[]{83, 10, 91, 67, 42, -1, 107, 62, 91, 67}, 8, 6, 26); + } - @Test - public void testEncodeBytesToBytes3() throws IOException { - byte[] src = new byte[] { - 113, 42, 123, 99, 10, -33, 75, 30, 88, 99, - 113, 42, 123, 99, 10, -33, 75, 31, 88, 99, - 113, 42, 123, 99, 10, -33, 75, 32, 88, 99, - 113, 42, 123, 99, 10, -33, 75, 33, 88, 99, - 113, 42, 123, 99, 10, -33, 75, 34, 88, 99, - 113, 42, 123, 99, 10, -33, 75, 35, 88, 99, - 55, 60 - }; - byte[] excepted = new byte[] { - 99, 83, 112, 55, 89, 119, 114, 102, 83, 120, - 53, 89, 89, 51, 69, 113, 101, 50, 77, 75, 51, - 48, 115, 102, 87, 71, 78, 120, 75, 110, 116, 106, - 67, 116, 57, 76, 73, 70, 104, 106, 99, 83, 112, - 55, 89, 119, 114, 102, 83, 121, 70, 89, 89, - 51, 69, 113, 101, 50, 77, 75, 51, 48, 115, - 105, 87, 71, 78, 120, 75, 110, 116, 106, 67, - 116, 57, 76, 10, 73, 49, 104, 106, 78, 122, - 119, 61 - }; - - Assert.assertArrayEquals(excepted, Base64.encodeBytesToBytes(src, 0, 62, 8)); - } + @Test + public void testEncodeBytesToBytes3() throws IOException { + byte[] src = new byte[]{ + 113, 42, 123, 99, 10, -33, 75, 30, 88, 99, + 113, 42, 123, 99, 10, -33, 75, 31, 88, 99, + 113, 42, 123, 99, 10, -33, 75, 32, 88, 99, + 113, 42, 123, 99, 10, -33, 75, 33, 88, 99, + 113, 42, 123, 99, 10, -33, 75, 34, 88, 99, + 113, 42, 123, 99, 10, -33, 75, 35, 88, 99, + 55, 60 + }; + byte[] excepted = new byte[]{ + 99, 83, 112, 55, 89, 119, 114, 102, 83, 120, + 53, 89, 89, 51, 69, 113, 101, 50, 77, 75, 51, + 48, 115, 102, 87, 71, 78, 120, 75, 110, 116, 106, + 67, 116, 57, 76, 73, 70, 104, 106, 99, 83, 112, + 55, 89, 119, 114, 102, 83, 121, 70, 89, 89, + 51, 69, 113, 101, 50, 77, 75, 51, 48, 115, + 105, 87, 71, 78, 120, 75, 110, 116, 106, 67, + 116, 57, 76, 10, 73, 49, 104, 106, 78, 122, + 119, 61 + }; + + Assert.assertArrayEquals(excepted, Base64.encodeBytesToBytes(src, 0, 62, 8)); + } } diff --git a/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java b/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java index 12476b508..77b62c977 100644 --- a/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java +++ b/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java @@ -36,97 +36,97 @@ */ public class ByteBufferUtilsTest { - /** - * A small byte array with some data - */ - private static byte[] smallArray = {0, -1, -2, -3, -4}; + /** + * A small byte array with some data + */ + private static byte[] smallArray = {0, -1, -2, -3, -4}; - /** - * A big byte array with some data - */ - private static byte[] bigArray = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + /** + * A big byte array with some data + */ + private static byte[] bigArray = {1, 2, 3, 4, 5, 6, 7, 8, 9}; - @Test - public void testEmptyByteBufferCapacity() { - ByteBuffer byteBuffer = ByteBufferUtils.getEmptyByteBuffer(); - assertEquals("capacity must be 0", 0, byteBuffer.capacity()); - } + @Test + public void testEmptyByteBufferCapacity() { + ByteBuffer byteBuffer = ByteBufferUtils.getEmptyByteBuffer(); + assertEquals("capacity must be 0", 0, byteBuffer.capacity()); + } - @Test - public void testEmptyByteBufferNewObject() { - ByteBuffer byteBuffer0 = ByteBufferUtils.getEmptyByteBuffer(); - ByteBuffer byteBuffer1 = ByteBufferUtils.getEmptyByteBuffer(); - assertTrue("Allocated new object", byteBuffer0 != byteBuffer1); - } + @Test + public void testEmptyByteBufferNewObject() { + ByteBuffer byteBuffer0 = ByteBufferUtils.getEmptyByteBuffer(); + ByteBuffer byteBuffer1 = ByteBufferUtils.getEmptyByteBuffer(); + assertTrue("Allocated new object", byteBuffer0 != byteBuffer1); + } - @Test - public void testTransferByteBufferSmallToEmpty() { - ByteBuffer small = ByteBuffer.wrap(smallArray); - ByteBuffer empty = ByteBufferUtils.getEmptyByteBuffer(); - ByteBufferUtils.transferByteBuffer(small, empty); - assertArrayEquals("Small bytebuffer should not change", smallArray, small.array()); - assertEquals("Capacity of the empty bytebuffer should still be 0", 0, empty.capacity()); - } + @Test + public void testTransferByteBufferSmallToEmpty() { + ByteBuffer small = ByteBuffer.wrap(smallArray); + ByteBuffer empty = ByteBufferUtils.getEmptyByteBuffer(); + ByteBufferUtils.transferByteBuffer(small, empty); + assertArrayEquals("Small bytebuffer should not change", smallArray, small.array()); + assertEquals("Capacity of the empty bytebuffer should still be 0", 0, empty.capacity()); + } - @Test - public void testTransferByteBufferSmallToBig() { - ByteBuffer small = ByteBuffer.wrap(smallArray); - ByteBuffer big = ByteBuffer.wrap(bigArray); - ByteBufferUtils.transferByteBuffer(small, big); - assertArrayEquals("Small bytebuffer should not change", smallArray, small.array()); - assertEquals("Big bytebuffer not same to source 0", smallArray[0], big.get(0)); - assertEquals("Big bytebuffer not same to source 1", smallArray[1], big.get(1)); - assertEquals("Big bytebuffer not same to source 2", smallArray[2], big.get(2)); - assertEquals("Big bytebuffer not same to source 3", smallArray[3], big.get(3)); - assertEquals("Big bytebuffer not same to source 4", smallArray[4], big.get(4)); - assertEquals("Big bytebuffer not same to source 5", bigArray[5], big.get(5)); - assertEquals("Big bytebuffer not same to source 6", bigArray[6], big.get(6)); - assertEquals("Big bytebuffer not same to source 7", bigArray[7], big.get(7)); - assertEquals("Big bytebuffer not same to source 8", bigArray[8], big.get(8)); - } + @Test + public void testTransferByteBufferSmallToBig() { + ByteBuffer small = ByteBuffer.wrap(smallArray); + ByteBuffer big = ByteBuffer.wrap(bigArray); + ByteBufferUtils.transferByteBuffer(small, big); + assertArrayEquals("Small bytebuffer should not change", smallArray, small.array()); + assertEquals("Big bytebuffer not same to source 0", smallArray[0], big.get(0)); + assertEquals("Big bytebuffer not same to source 1", smallArray[1], big.get(1)); + assertEquals("Big bytebuffer not same to source 2", smallArray[2], big.get(2)); + assertEquals("Big bytebuffer not same to source 3", smallArray[3], big.get(3)); + assertEquals("Big bytebuffer not same to source 4", smallArray[4], big.get(4)); + assertEquals("Big bytebuffer not same to source 5", bigArray[5], big.get(5)); + assertEquals("Big bytebuffer not same to source 6", bigArray[6], big.get(6)); + assertEquals("Big bytebuffer not same to source 7", bigArray[7], big.get(7)); + assertEquals("Big bytebuffer not same to source 8", bigArray[8], big.get(8)); + } - @Test - public void testTransferByteBufferBigToSmall() { - ByteBuffer small = ByteBuffer.wrap(smallArray); - ByteBuffer big = ByteBuffer.wrap(bigArray); - ByteBufferUtils.transferByteBuffer(big, small); - assertArrayEquals("Big bytebuffer should not change", bigArray, big.array()); - assertEquals("Small bytebuffer not same to source 0", bigArray[0], small.get(0)); - assertEquals("Small bytebuffer not same to source 1", bigArray[1], small.get(1)); - assertEquals("Small bytebuffer not same to source 2", bigArray[2], small.get(2)); - assertEquals("Small bytebuffer not same to source 3", bigArray[3], small.get(3)); - assertEquals("Small bytebuffer not same to source 4", bigArray[4], small.get(4)); - } + @Test + public void testTransferByteBufferBigToSmall() { + ByteBuffer small = ByteBuffer.wrap(smallArray); + ByteBuffer big = ByteBuffer.wrap(bigArray); + ByteBufferUtils.transferByteBuffer(big, small); + assertArrayEquals("Big bytebuffer should not change", bigArray, big.array()); + assertEquals("Small bytebuffer not same to source 0", bigArray[0], small.get(0)); + assertEquals("Small bytebuffer not same to source 1", bigArray[1], small.get(1)); + assertEquals("Small bytebuffer not same to source 2", bigArray[2], small.get(2)); + assertEquals("Small bytebuffer not same to source 3", bigArray[3], small.get(3)); + assertEquals("Small bytebuffer not same to source 4", bigArray[4], small.get(4)); + } - @Test - public void testTransferByteBufferCheckNullDest() { - ByteBuffer source = ByteBuffer.wrap(smallArray); - try { - ByteBufferUtils.transferByteBuffer(source, null); - fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException e) { - //Fine - } + @Test + public void testTransferByteBufferCheckNullDest() { + ByteBuffer source = ByteBuffer.wrap(smallArray); + try { + ByteBufferUtils.transferByteBuffer(source, null); + fail("IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException e) { + //Fine } + } - @Test - public void testTransferByteBufferCheckNullSource() { - ByteBuffer dest = ByteBuffer.wrap(smallArray); - try { - ByteBufferUtils.transferByteBuffer(null, dest); - fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException e) { - //Fine - } + @Test + public void testTransferByteBufferCheckNullSource() { + ByteBuffer dest = ByteBuffer.wrap(smallArray); + try { + ByteBufferUtils.transferByteBuffer(null, dest); + fail("IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException e) { + //Fine } + } - @Test - public void testTransferByteBufferCheckNullBoth() { - try { - ByteBufferUtils.transferByteBuffer(null, null); - fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException e) { - //Fine - } + @Test + public void testTransferByteBufferCheckNullBoth() { + try { + ByteBufferUtils.transferByteBuffer(null, null); + fail("IllegalArgumentException should be thrown"); + } catch (IllegalArgumentException e) { + //Fine } + } } diff --git a/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java b/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java index 2ecc7b22c..3c36ea7b9 100644 --- a/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java +++ b/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java @@ -35,43 +35,46 @@ public class CharsetfunctionsTest { @Test public void testAsciiBytes() { - Assert.assertArrayEquals(new byte[] {102, 111, 111}, Charsetfunctions.asciiBytes("foo")); + Assert.assertArrayEquals(new byte[]{102, 111, 111}, Charsetfunctions.asciiBytes("foo")); } @Test public void testStringUtf8ByteBuffer() throws InvalidDataException { - Assert.assertEquals("foo", Charsetfunctions.stringUtf8(ByteBuffer.wrap(new byte[] {102, 111, 111}))); + Assert.assertEquals("foo", + Charsetfunctions.stringUtf8(ByteBuffer.wrap(new byte[]{102, 111, 111}))); } @Test public void testIsValidUTF8off() { - Assert.assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[] {100}), 2)); - Assert.assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[] {(byte) 128}), 0)); + Assert.assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{100}), 2)); + Assert.assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{(byte) 128}), 0)); - Assert.assertTrue(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[] {100}), 0)); + Assert.assertTrue(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{100}), 0)); } @Test public void testIsValidUTF8() { - Assert.assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[] {(byte) 128}))); + Assert.assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{(byte) 128}))); - Assert.assertTrue(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[] {100}))); + Assert.assertTrue(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{100}))); } @Test public void testStringAscii1() { - Assert.assertEquals("oBar", Charsetfunctions.stringAscii(new byte[] {102, 111, 111, 66, 97, 114}, 2, 4)); + Assert.assertEquals("oBar", + Charsetfunctions.stringAscii(new byte[]{102, 111, 111, 66, 97, 114}, 2, 4)); } @Test public void testStringAscii2() { - Assert.assertEquals("foo", Charsetfunctions.stringAscii(new byte[] {102, 111, 111})); + Assert.assertEquals("foo", Charsetfunctions.stringAscii(new byte[]{102, 111, 111})); } @Test public void testUtf8Bytes() { - Assert.assertArrayEquals(new byte[] {102, 111, 111, 66, 97, 114}, Charsetfunctions.utf8Bytes("fooBar")); + Assert.assertArrayEquals(new byte[]{102, 111, 111, 66, 97, 114}, + Charsetfunctions.utf8Bytes("fooBar")); } } diff --git a/src/test/java/org/java_websocket/util/KeyUtils.java b/src/test/java/org/java_websocket/util/KeyUtils.java index 8644d0098..ca5dbff14 100644 --- a/src/test/java/org/java_websocket/util/KeyUtils.java +++ b/src/test/java/org/java_websocket/util/KeyUtils.java @@ -30,26 +30,27 @@ import java.security.NoSuchAlgorithmException; public class KeyUtils { - /** - * Generate a final key from a input string - * - * @param in the input string - * @return a final key - */ - public static String generateFinalKey( String in ) { - String seckey = in.trim(); - String acc = seckey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; - MessageDigest sh1; - try { - sh1 = MessageDigest.getInstance( "SHA1" ); - } catch ( NoSuchAlgorithmException e ) { - throw new IllegalStateException( e ); - } - return Base64.encodeBytes( sh1.digest( acc.getBytes() ) ); - } - public static String getSecKey( String seckey ) { - return "Sec-WebSocket-Accept: " + KeyUtils.generateFinalKey( seckey ) + "\r\n"; + /** + * Generate a final key from a input string + * + * @param in the input string + * @return a final key + */ + public static String generateFinalKey(String in) { + String seckey = in.trim(); + String acc = seckey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + MessageDigest sh1; + try { + sh1 = MessageDigest.getInstance("SHA1"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); } + return Base64.encodeBytes(sh1.digest(acc.getBytes())); + } + + public static String getSecKey(String seckey) { + return "Sec-WebSocket-Accept: " + KeyUtils.generateFinalKey(seckey) + "\r\n"; + } } diff --git a/src/test/java/org/java_websocket/util/SSLContextUtil.java b/src/test/java/org/java_websocket/util/SSLContextUtil.java index 49caf0cba..e8d45b6fb 100644 --- a/src/test/java/org/java_websocket/util/SSLContextUtil.java +++ b/src/test/java/org/java_websocket/util/SSLContextUtil.java @@ -38,47 +38,52 @@ public class SSLContextUtil { - public static SSLContext getContext() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException { - // load up the key store - String STORETYPE = "JKS"; - String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks").toString(); - String STOREPASSWORD = "storepassword"; - String KEYPASSWORD = "keypassword"; + public static SSLContext getContext() + throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException { + // load up the key store + String STORETYPE = "JKS"; + String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks") + .toString(); + String STOREPASSWORD = "storepassword"; + String KEYPASSWORD = "keypassword"; - KeyStore ks = KeyStore.getInstance(STORETYPE); - File kf = new File(KEYSTORE); - ks.load(new FileInputStream(kf), STOREPASSWORD.toCharArray()); + KeyStore ks = KeyStore.getInstance(STORETYPE); + File kf = new File(KEYSTORE); + ks.load(new FileInputStream(kf), STOREPASSWORD.toCharArray()); - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, KEYPASSWORD.toCharArray()); - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ks); + KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); + kmf.init(ks, KEYPASSWORD.toCharArray()); + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(ks); - SSLContext sslContext = null; - sslContext = SSLContext.getInstance("TLS"); - sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - return sslContext; - } + SSLContext sslContext = null; + sslContext = SSLContext.getInstance("TLS"); + sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + return sslContext; + } - public static SSLContext getLocalhostOnlyContext() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException { - // load up the key store - String STORETYPE = "JKS"; - String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore_localhost_only.jks").toString(); - String STOREPASSWORD = "storepassword"; - String KEYPASSWORD = "keypassword"; + public static SSLContext getLocalhostOnlyContext() + throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException { + // load up the key store + String STORETYPE = "JKS"; + String KEYSTORE = Paths + .get("src", "test", "java", "org", "java_websocket", "keystore_localhost_only.jks") + .toString(); + String STOREPASSWORD = "storepassword"; + String KEYPASSWORD = "keypassword"; - KeyStore ks = KeyStore.getInstance(STORETYPE); - File kf = new File(KEYSTORE); - ks.load(new FileInputStream(kf), STOREPASSWORD.toCharArray()); + KeyStore ks = KeyStore.getInstance(STORETYPE); + File kf = new File(KEYSTORE); + ks.load(new FileInputStream(kf), STOREPASSWORD.toCharArray()); - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, KEYPASSWORD.toCharArray()); - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ks); + KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); + kmf.init(ks, KEYPASSWORD.toCharArray()); + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(ks); - SSLContext sslContext = null; - sslContext = SSLContext.getInstance("TLS"); - sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - return sslContext; - } + SSLContext sslContext = null; + sslContext = SSLContext.getInstance("TLS"); + sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + return sslContext; + } } diff --git a/src/test/java/org/java_websocket/util/SocketUtil.java b/src/test/java/org/java_websocket/util/SocketUtil.java index 65ca57bd7..e43c7fe3d 100644 --- a/src/test/java/org/java_websocket/util/SocketUtil.java +++ b/src/test/java/org/java_websocket/util/SocketUtil.java @@ -24,19 +24,21 @@ */ package org.java_websocket.util; + import java.io.IOException; import java.net.ServerSocket; public class SocketUtil { - public static int getAvailablePort() throws IOException { - ServerSocket srv = null; - try { - srv = new ServerSocket( 0 ); - return srv.getLocalPort(); - } finally { - if( srv != null ) { - srv.close(); - } - } - } + + public static int getAvailablePort() throws IOException { + ServerSocket srv = null; + try { + srv = new ServerSocket(0); + return srv.getLocalPort(); + } finally { + if (srv != null) { + srv.close(); + } + } + } } diff --git a/src/test/java/org/java_websocket/util/ThreadCheck.java b/src/test/java/org/java_websocket/util/ThreadCheck.java index a23f72b86..6ee37348d 100644 --- a/src/test/java/org/java_websocket/util/ThreadCheck.java +++ b/src/test/java/org/java_websocket/util/ThreadCheck.java @@ -24,68 +24,75 @@ */ package org.java_websocket.util; + import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.LockSupport; import org.junit.Assert; import org.junit.rules.ExternalResource; + /** * Makes test fail if new threads are still alive after tear-down. */ public class ThreadCheck extends ExternalResource { - private Map map = new HashMap(); - @Override protected void before() throws Throwable { - map = getThreadMap(); - } + private Map map = new HashMap(); + + @Override + protected void before() throws Throwable { + map = getThreadMap(); + } - @Override protected void after() { - long time = System.currentTimeMillis(); - do { - LockSupport.parkNanos( 10000000 ); - } while ( checkZombies( true ) && System.currentTimeMillis() - time < 1000 ); + @Override + protected void after() { + long time = System.currentTimeMillis(); + do { + LockSupport.parkNanos(10000000); + } while (checkZombies(true) && System.currentTimeMillis() - time < 1000); - checkZombies( false ); - } + checkZombies(false); + } - private boolean checkZombies( boolean testOnly ) { - Map newMap = getThreadMap(); + private boolean checkZombies(boolean testOnly) { + Map newMap = getThreadMap(); - int zombies = 0; - for( Thread t : newMap.values() ) { - Thread prev = map.get( t.getId() ); - if( prev == null ) { - zombies++; - if( testOnly ) - return true; + int zombies = 0; + for (Thread t : newMap.values()) { + Thread prev = map.get(t.getId()); + if (prev == null) { + zombies++; + if (testOnly) { + return true; + } - StringBuilder b = new StringBuilder( 4096 ); - appendStack( t, b.append( "\n" ).append( t.getName() ) ); - System.err.println( b ); - } - } - if( zombies > 0 && ! testOnly ) - Assert.fail( "Found " + zombies + " zombie thread(s) " ); + StringBuilder b = new StringBuilder(4096); + appendStack(t, b.append("\n").append(t.getName())); + System.err.println(b); + } + } + if (zombies > 0 && !testOnly) { + Assert.fail("Found " + zombies + " zombie thread(s) "); + } - return zombies > 0; - } + return zombies > 0; + } - public static Map getThreadMap() { - Map map = new HashMap(); - Thread[] threads = new Thread[ Thread.activeCount() * 2 ]; - int actualNb = Thread.enumerate( threads ); - for( int i = 0; i < actualNb; i++ ) { - map.put( threads[ i ].getId(), threads[ i ] ); - } - return map; - } + public static Map getThreadMap() { + Map map = new HashMap(); + Thread[] threads = new Thread[Thread.activeCount() * 2]; + int actualNb = Thread.enumerate(threads); + for (int i = 0; i < actualNb; i++) { + map.put(threads[i].getId(), threads[i]); + } + return map; + } - private static void appendStack( Thread th, StringBuilder s ) { - StackTraceElement[] st = th.getStackTrace(); - for( int i = 0; i < st.length; i++ ) { - s.append( "\n at " ); - s.append( st[ i ] ); - } - } + private static void appendStack(Thread th, StringBuilder s) { + StackTraceElement[] st = th.getStackTrace(); + for (int i = 0; i < st.length; i++) { + s.append("\n at "); + s.append(st[i]); + } + } } From 982dabd77d5d3d312822f83591c9b31bdd96be80 Mon Sep 17 00:00:00 2001 From: dota17 Date: Thu, 13 Aug 2020 20:05:07 +0800 Subject: [PATCH 071/165] The source code in src : optimize imports --- src/main/example/ChatClient.java | 3 -- src/main/example/ChatServer.java | 4 -- .../example/ChatServerAttachmentExample.java | 9 ++-- .../example/CustomHeaderClientExample.java | 2 - src/main/example/ExampleClient.java | 3 -- src/main/example/FragmentedFramesExample.java | 1 - .../example/PerMessageDeflateExample.java | 9 ++-- src/main/example/ReconnectClientExample.java | 2 - src/main/example/SSLClientExample.java | 3 -- ...SLServerCustomWebsocketFactoryExample.java | 12 ++--- src/main/example/SSLServerExample.java | 3 -- .../example/SSLServerLetsEncryptExample.java | 12 ++--- .../SecWebSocketProtocolClientExample.java | 10 ++-- .../SecWebSocketProtocolServerExample.java | 8 ++- .../ServerAdditionalHeaderExample.java | 11 ++-- .../example/ServerRejectHandshakeExample.java | 10 ++-- src/main/example/ServerStressTest.java | 2 - src/main/example/TwoWaySSLServerExample.java | 11 ++-- .../org/java_websocket/AbstractWebSocket.java | 9 ++-- .../org/java_websocket/SSLSocketChannel.java | 19 ++++--- .../org/java_websocket/SSLSocketChannel2.java | 19 ++++--- .../java_websocket/SocketChannelIOHelper.java | 1 - .../java/org/java_websocket/WebSocket.java | 4 +- .../org/java_websocket/WebSocketFactory.java | 1 - .../org/java_websocket/WebSocketImpl.java | 45 ++++++++++------- .../org/java_websocket/WebSocketListener.java | 1 - .../WebSocketServerFactory.java | 3 +- .../client/WebSocketClient.java | 9 ++-- .../java/org/java_websocket/drafts/Draft.java | 8 ++- .../org/java_websocket/drafts/Draft_6455.java | 50 ++++++++++++++----- .../exceptions/WrappedIOException.java | 3 +- .../PerMessageDeflateExtension.java | 15 +++--- .../java_websocket/framing/CloseFrame.java | 3 +- .../org/java_websocket/framing/Framedata.java | 2 +- .../framing/FramedataImpl1.java | 3 +- .../CustomSSLWebSocketServerFactory.java | 7 ++- .../DefaultSSLWebSocketServerFactory.java | 7 +-- .../server/DefaultWebSocketServerFactory.java | 3 +- .../SSLParametersWebSocketServerFactory.java | 9 ++-- .../server/WebSocketServer.java | 25 ++++++++-- .../java_websocket/util/Charsetfunctions.java | 7 ++- .../autobahn/AutobahnServerResultsTest.java | 11 ++-- .../java_websocket/client/AttachmentTest.java | 9 ++-- .../java_websocket/client/HeadersTest.java | 9 ++-- .../client/SchemaCheckTest.java | 9 ++-- .../java_websocket/drafts/Draft_6455Test.java | 18 ++++--- .../example/AutobahnClientTest.java | 5 -- .../example/AutobahnSSLServerTest.java | 23 ++++----- .../example/AutobahnServerTest.java | 9 ++-- .../exceptions/IncompleteExceptionTest.java | 7 +-- .../IncompleteHandshakeExceptionTest.java | 4 +- .../exceptions/InvalidDataExceptionTest.java | 5 +- .../InvalidEncodingExceptionTest.java | 7 ++- .../exceptions/InvalidFrameExceptionTest.java | 4 +- .../InvalidHandshakeExceptionTest.java | 4 +- .../LimitExceededExceptionTest.java | 8 +-- .../exceptions/NotSendableExceptionTest.java | 5 +- .../WebsocketNotConnectedExceptionTest.java | 6 +-- .../extensions/CompressionExtensionTest.java | 4 +- .../extensions/DefaultExtensionTest.java | 10 ++-- .../PerMessageDeflateExtensionTest.java | 19 ++++--- .../framing/BinaryFrameTest.java | 6 +-- .../framing/CloseFrameTest.java | 6 +-- .../framing/ContinuousFrameTest.java | 6 +-- .../framing/FramedataImpl1Test.java | 9 ++-- .../java_websocket/framing/PingFrameTest.java | 6 +-- .../java_websocket/framing/PongFrameTest.java | 9 ++-- .../java_websocket/framing/TextFrameTest.java | 9 ++-- .../java_websocket/issues/Issue256Test.java | 27 +++++----- .../java_websocket/issues/Issue580Test.java | 14 +++--- .../java_websocket/issues/Issue598Test.java | 15 +++--- .../java_websocket/issues/Issue609Test.java | 11 ++-- .../java_websocket/issues/Issue621Test.java | 15 +++--- .../java_websocket/issues/Issue661Test.java | 15 +++--- .../java_websocket/issues/Issue666Test.java | 9 ++-- .../java_websocket/issues/Issue677Test.java | 11 ++-- .../java_websocket/issues/Issue713Test.java | 20 +++----- .../java_websocket/issues/Issue732Test.java | 12 ++--- .../java_websocket/issues/Issue764Test.java | 24 ++++----- .../java_websocket/issues/Issue765Test.java | 11 ++-- .../java_websocket/issues/Issue811Test.java | 7 ++- .../java_websocket/issues/Issue825Test.java | 24 ++++----- .../java_websocket/issues/Issue834Test.java | 7 ++- .../java_websocket/issues/Issue847Test.java | 25 +++++----- .../java_websocket/issues/Issue855Test.java | 7 ++- .../java_websocket/issues/Issue879Test.java | 21 ++++---- .../java_websocket/issues/Issue890Test.java | 33 ++++++------ .../java_websocket/issues/Issue900Test.java | 13 +++-- .../java_websocket/issues/Issue941Test.java | 13 +++-- .../java_websocket/issues/Issue997Test.java | 32 ++++++------ .../misc/OpeningHandshakeRejectionTest.java | 17 +++---- .../ProtoclHandshakeRejectionTest.java | 27 +++++----- .../protocols/ProtocolTest.java | 8 ++- .../CustomSSLWebSocketServerFactoryTest.java | 21 ++++---- .../DefaultSSLWebSocketServerFactoryTest.java | 26 ++++------ .../DefaultWebSocketServerFactoryTest.java | 17 +++---- ...LParametersWebSocketServerFactoryTest.java | 23 ++++----- .../server/WebSocketServerTest.java | 18 +++---- .../org/java_websocket/util/Base64Test.java | 3 +- .../util/ByteBufferUtilsTest.java | 8 +-- .../util/CharsetfunctionsTest.java | 3 +- .../java_websocket/util/SSLContextUtil.java | 12 +++-- .../org/java_websocket/util/ThreadCheck.java | 1 - 103 files changed, 548 insertions(+), 597 deletions(-) diff --git a/src/main/example/ChatClient.java b/src/main/example/ChatClient.java index 7368a062f..6ff01d9d5 100644 --- a/src/main/example/ChatClient.java +++ b/src/main/example/ChatClient.java @@ -30,15 +30,12 @@ import java.awt.event.WindowEvent; import java.net.URI; import java.net.URISyntaxException; - import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; - -import org.java_websocket.WebSocketImpl; import org.java_websocket.client.WebSocketClient; import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_6455; diff --git a/src/main/example/ChatServer.java b/src/main/example/ChatServer.java index de847adec..a9441ca3c 100644 --- a/src/main/example/ChatServer.java +++ b/src/main/example/ChatServer.java @@ -30,14 +30,10 @@ import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.Collections; - import org.java_websocket.WebSocket; -import org.java_websocket.WebSocketImpl; import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_6455; -import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ClientHandshake; -import org.java_websocket.protocols.IProtocol; import org.java_websocket.server.WebSocketServer; /** diff --git a/src/main/example/ChatServerAttachmentExample.java b/src/main/example/ChatServerAttachmentExample.java index 3439bcbdf..d05a7781d 100644 --- a/src/main/example/ChatServerAttachmentExample.java +++ b/src/main/example/ChatServerAttachmentExample.java @@ -23,18 +23,15 @@ * OTHER DEALINGS IN THE SOFTWARE. */ -import org.java_websocket.WebSocket; -import org.java_websocket.WebSocketImpl; -import org.java_websocket.framing.Framedata; -import org.java_websocket.handshake.ClientHandshake; -import org.java_websocket.server.WebSocketServer; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; +import org.java_websocket.WebSocket; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.server.WebSocketServer; /** * A simple WebSocketServer implementation. Keeps track of a "chatroom". diff --git a/src/main/example/CustomHeaderClientExample.java b/src/main/example/CustomHeaderClientExample.java index eab1e474c..e35012968 100644 --- a/src/main/example/CustomHeaderClientExample.java +++ b/src/main/example/CustomHeaderClientExample.java @@ -23,8 +23,6 @@ * OTHER DEALINGS IN THE SOFTWARE. */ -import org.java_websocket.WebSocketImpl; - import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; diff --git a/src/main/example/ExampleClient.java b/src/main/example/ExampleClient.java index a9d32c4d0..089afe822 100644 --- a/src/main/example/ExampleClient.java +++ b/src/main/example/ExampleClient.java @@ -26,11 +26,8 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.Map; - import org.java_websocket.client.WebSocketClient; import org.java_websocket.drafts.Draft; -import org.java_websocket.drafts.Draft_6455; -import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ServerHandshake; /** diff --git a/src/main/example/FragmentedFramesExample.java b/src/main/example/FragmentedFramesExample.java index 52fce6ef5..dcf658553 100644 --- a/src/main/example/FragmentedFramesExample.java +++ b/src/main/example/FragmentedFramesExample.java @@ -29,7 +29,6 @@ import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; - import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.enums.Opcode; diff --git a/src/main/example/PerMessageDeflateExample.java b/src/main/example/PerMessageDeflateExample.java index b557029d5..49cd64eca 100644 --- a/src/main/example/PerMessageDeflateExample.java +++ b/src/main/example/PerMessageDeflateExample.java @@ -1,3 +1,7 @@ +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Collections; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.drafts.Draft; @@ -7,11 +11,6 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; -import java.net.InetSocketAddress; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Collections; - /** * This class only serves the purpose of showing how to enable PerMessageDeflateExtension for both * server and client sockets.
      Extensions are required to be registered in diff --git a/src/main/example/ReconnectClientExample.java b/src/main/example/ReconnectClientExample.java index 1eaebe1b3..efe958d54 100644 --- a/src/main/example/ReconnectClientExample.java +++ b/src/main/example/ReconnectClientExample.java @@ -23,8 +23,6 @@ * OTHER DEALINGS IN THE SOFTWARE. */ -import org.java_websocket.WebSocketImpl; - import java.net.URI; import java.net.URISyntaxException; diff --git a/src/main/example/SSLClientExample.java b/src/main/example/SSLClientExample.java index 98746e36b..52790caff 100644 --- a/src/main/example/SSLClientExample.java +++ b/src/main/example/SSLClientExample.java @@ -30,13 +30,10 @@ import java.net.URI; import java.nio.file.Paths; import java.security.KeyStore; - import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; - -import org.java_websocket.WebSocketImpl; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; diff --git a/src/main/example/SSLServerCustomWebsocketFactoryExample.java b/src/main/example/SSLServerCustomWebsocketFactoryExample.java index 2c98dac5b..e9c5d7c1e 100644 --- a/src/main/example/SSLServerCustomWebsocketFactoryExample.java +++ b/src/main/example/SSLServerCustomWebsocketFactoryExample.java @@ -23,13 +23,6 @@ * OTHER DEALINGS IN THE SOFTWARE. */ -import org.java_websocket.WebSocketImpl; -import org.java_websocket.server.CustomSSLWebSocketServerFactory; - -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLEngine; -import javax.net.ssl.TrustManagerFactory; import java.io.File; import java.io.FileInputStream; import java.nio.file.Paths; @@ -37,6 +30,11 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.TrustManagerFactory; +import org.java_websocket.server.CustomSSLWebSocketServerFactory; /** * Example for using the CustomSSLWebSocketServerFactory to allow just specific cipher suites diff --git a/src/main/example/SSLServerExample.java b/src/main/example/SSLServerExample.java index 9d1f714ad..ca599f703 100644 --- a/src/main/example/SSLServerExample.java +++ b/src/main/example/SSLServerExample.java @@ -29,12 +29,9 @@ import java.io.FileInputStream; import java.nio.file.Paths; import java.security.KeyStore; - import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; - -import org.java_websocket.WebSocketImpl; import org.java_websocket.server.DefaultSSLWebSocketServerFactory; public class SSLServerExample { diff --git a/src/main/example/SSLServerLetsEncryptExample.java b/src/main/example/SSLServerLetsEncryptExample.java index 5f32d1a50..a048dd2eb 100644 --- a/src/main/example/SSLServerLetsEncryptExample.java +++ b/src/main/example/SSLServerLetsEncryptExample.java @@ -23,13 +23,6 @@ * OTHER DEALINGS IN THE SOFTWARE. */ -import org.java_websocket.WebSocketImpl; -import org.java_websocket.server.DefaultSSLWebSocketServerFactory; - -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.xml.bind.DatatypeConverter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; @@ -44,6 +37,11 @@ import java.security.interfaces.RSAPrivateKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.xml.bind.DatatypeConverter; +import org.java_websocket.server.DefaultSSLWebSocketServerFactory; /** diff --git a/src/main/example/SecWebSocketProtocolClientExample.java b/src/main/example/SecWebSocketProtocolClientExample.java index 9f12f2d20..d9645f800 100644 --- a/src/main/example/SecWebSocketProtocolClientExample.java +++ b/src/main/example/SecWebSocketProtocolClientExample.java @@ -23,16 +23,14 @@ * OTHER DEALINGS IN THE SOFTWARE. */ -import org.java_websocket.WebSocketImpl; -import org.java_websocket.drafts.Draft_6455; -import org.java_websocket.extensions.IExtension; -import org.java_websocket.protocols.IProtocol; -import org.java_websocket.protocols.Protocol; - import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; +import org.java_websocket.drafts.Draft_6455; +import org.java_websocket.extensions.IExtension; +import org.java_websocket.protocols.IProtocol; +import org.java_websocket.protocols.Protocol; /** * This example demonstrates how to use a specific Sec-WebSocket-Protocol for your connection. diff --git a/src/main/example/SecWebSocketProtocolServerExample.java b/src/main/example/SecWebSocketProtocolServerExample.java index 9a2790d36..01ba44b02 100644 --- a/src/main/example/SecWebSocketProtocolServerExample.java +++ b/src/main/example/SecWebSocketProtocolServerExample.java @@ -23,16 +23,14 @@ * OTHER DEALINGS IN THE SOFTWARE. */ +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collections; import org.java_websocket.drafts.Draft_6455; import org.java_websocket.extensions.IExtension; import org.java_websocket.protocols.IProtocol; import org.java_websocket.protocols.Protocol; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collections; - /** * This example demonstrates how to use a specific Sec-WebSocket-Protocol for your connection. */ diff --git a/src/main/example/ServerAdditionalHeaderExample.java b/src/main/example/ServerAdditionalHeaderExample.java index 1aa99c499..205c77f67 100644 --- a/src/main/example/ServerAdditionalHeaderExample.java +++ b/src/main/example/ServerAdditionalHeaderExample.java @@ -23,19 +23,16 @@ * OTHER DEALINGS IN THE SOFTWARE. */ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.InetSocketAddress; import org.java_websocket.WebSocket; -import org.java_websocket.WebSocketImpl; import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.InvalidDataException; -import org.java_websocket.framing.CloseFrame; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.ServerHandshakeBuilder; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.InetSocketAddress; - /** * This example shows how to add additional headers to your server handshake response *

      diff --git a/src/main/example/ServerRejectHandshakeExample.java b/src/main/example/ServerRejectHandshakeExample.java index 9c53eb38b..ee7081f15 100644 --- a/src/main/example/ServerRejectHandshakeExample.java +++ b/src/main/example/ServerRejectHandshakeExample.java @@ -23,19 +23,17 @@ * OTHER DEALINGS IN THE SOFTWARE. */ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.InetSocketAddress; import org.java_websocket.WebSocket; -import org.java_websocket.WebSocketImpl; import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.framing.CloseFrame; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.ServerHandshakeBuilder; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.InetSocketAddress; - /** * This example shows how to reject a handshake as a server from a client. *

      diff --git a/src/main/example/ServerStressTest.java b/src/main/example/ServerStressTest.java index c15907da4..bb973b63c 100644 --- a/src/main/example/ServerStressTest.java +++ b/src/main/example/ServerStressTest.java @@ -34,7 +34,6 @@ import java.util.List; import java.util.Timer; import java.util.TimerTask; - import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; @@ -44,7 +43,6 @@ import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; - import org.java_websocket.client.WebSocketClient; import org.java_websocket.exceptions.WebsocketNotConnectedException; diff --git a/src/main/example/TwoWaySSLServerExample.java b/src/main/example/TwoWaySSLServerExample.java index 1ee488089..2e52f7aa2 100644 --- a/src/main/example/TwoWaySSLServerExample.java +++ b/src/main/example/TwoWaySSLServerExample.java @@ -25,16 +25,15 @@ * OTHER DEALINGS IN THE SOFTWARE. */ -import org.java_websocket.server.SSLParametersWebSocketServerFactory; - -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLParameters; -import javax.net.ssl.TrustManagerFactory; import java.io.File; import java.io.FileInputStream; import java.nio.file.Paths; import java.security.KeyStore; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.TrustManagerFactory; +import org.java_websocket.server.SSLParametersWebSocketServerFactory; /** * Copy of SSLServerExample except we use @link SSLEngineWebSocketServerFactory to customize diff --git a/src/main/java/org/java_websocket/AbstractWebSocket.java b/src/main/java/org/java_websocket/AbstractWebSocket.java index a5dcb39d8..a6709f0aa 100644 --- a/src/main/java/org/java_websocket/AbstractWebSocket.java +++ b/src/main/java/org/java_websocket/AbstractWebSocket.java @@ -25,17 +25,16 @@ package org.java_websocket; -import org.java_websocket.framing.CloseFrame; -import org.java_websocket.util.NamedThreadFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import org.java_websocket.framing.CloseFrame; +import org.java_websocket.util.NamedThreadFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** diff --git a/src/main/java/org/java_websocket/SSLSocketChannel.java b/src/main/java/org/java_websocket/SSLSocketChannel.java index 11fc2eab7..0c1f0c413 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel.java @@ -25,16 +25,6 @@ package org.java_websocket; -import org.java_websocket.interfaces.ISSLChannel; -import org.java_websocket.util.ByteBufferUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLEngineResult; -import javax.net.ssl.SSLEngineResult.HandshakeStatus; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLSession; import java.io.IOException; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; @@ -42,6 +32,15 @@ import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.concurrent.ExecutorService; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLEngineResult; +import javax.net.ssl.SSLEngineResult.HandshakeStatus; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLSession; +import org.java_websocket.interfaces.ISSLChannel; +import org.java_websocket.util.ByteBufferUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** diff --git a/src/main/java/org/java_websocket/SSLSocketChannel2.java b/src/main/java/org/java_websocket/SSLSocketChannel2.java index 9689ae2d1..983d64c34 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel2.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel2.java @@ -24,16 +24,6 @@ */ package org.java_websocket; -import org.java_websocket.interfaces.ISSLChannel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLEngineResult; -import javax.net.ssl.SSLEngineResult.HandshakeStatus; -import javax.net.ssl.SSLEngineResult.Status; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLSession; import java.io.EOFException; import java.io.IOException; import java.net.Socket; @@ -49,6 +39,15 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLEngineResult; +import javax.net.ssl.SSLEngineResult.HandshakeStatus; +import javax.net.ssl.SSLEngineResult.Status; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLSession; +import org.java_websocket.interfaces.ISSLChannel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Implements the relevant portions of the SocketChannel interface with the SSLEngine wrapper. diff --git a/src/main/java/org/java_websocket/SocketChannelIOHelper.java b/src/main/java/org/java_websocket/SocketChannelIOHelper.java index 14fb58b7c..987ce4093 100644 --- a/src/main/java/org/java_websocket/SocketChannelIOHelper.java +++ b/src/main/java/org/java_websocket/SocketChannelIOHelper.java @@ -28,7 +28,6 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; - import org.java_websocket.enums.Role; public class SocketChannelIOHelper { diff --git a/src/main/java/org/java_websocket/WebSocket.java b/src/main/java/org/java_websocket/WebSocket.java index 3c23b8c20..6c7e9effc 100644 --- a/src/main/java/org/java_websocket/WebSocket.java +++ b/src/main/java/org/java_websocket/WebSocket.java @@ -28,7 +28,7 @@ import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.Collection; - +import javax.net.ssl.SSLSession; import org.java_websocket.drafts.Draft; import org.java_websocket.enums.Opcode; import org.java_websocket.enums.ReadyState; @@ -36,8 +36,6 @@ import org.java_websocket.framing.Framedata; import org.java_websocket.protocols.IProtocol; -import javax.net.ssl.SSLSession; - public interface WebSocket { /** diff --git a/src/main/java/org/java_websocket/WebSocketFactory.java b/src/main/java/org/java_websocket/WebSocketFactory.java index 65de7c550..eed6e5ad3 100644 --- a/src/main/java/org/java_websocket/WebSocketFactory.java +++ b/src/main/java/org/java_websocket/WebSocketFactory.java @@ -26,7 +26,6 @@ package org.java_websocket; import java.util.List; - import org.java_websocket.drafts.Draft; public interface WebSocketFactory { diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index 28041d49b..9832ee316 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -25,19 +25,6 @@ package org.java_websocket; -import org.java_websocket.interfaces.ISSLChannel; -import org.java_websocket.drafts.Draft; -import org.java_websocket.drafts.Draft_6455; -import org.java_websocket.enums.*; -import org.java_websocket.exceptions.*; -import org.java_websocket.framing.CloseFrame; -import org.java_websocket.framing.Framedata; -import org.java_websocket.framing.PingFrame; -import org.java_websocket.handshake.*; -import org.java_websocket.protocols.IProtocol; -import org.java_websocket.server.WebSocketServer.WebSocketWorker; -import org.java_websocket.util.Charsetfunctions; - import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; @@ -49,12 +36,34 @@ import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; - +import javax.net.ssl.SSLSession; +import org.java_websocket.drafts.Draft; +import org.java_websocket.drafts.Draft_6455; +import org.java_websocket.enums.CloseHandshakeType; +import org.java_websocket.enums.HandshakeState; +import org.java_websocket.enums.Opcode; +import org.java_websocket.enums.ReadyState; +import org.java_websocket.enums.Role; +import org.java_websocket.exceptions.IncompleteHandshakeException; +import org.java_websocket.exceptions.InvalidDataException; +import org.java_websocket.exceptions.InvalidHandshakeException; +import org.java_websocket.exceptions.LimitExceededException; +import org.java_websocket.exceptions.WebsocketNotConnectedException; +import org.java_websocket.framing.CloseFrame; +import org.java_websocket.framing.Framedata; +import org.java_websocket.framing.PingFrame; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.handshake.ClientHandshakeBuilder; +import org.java_websocket.handshake.Handshakedata; +import org.java_websocket.handshake.ServerHandshake; +import org.java_websocket.handshake.ServerHandshakeBuilder; +import org.java_websocket.interfaces.ISSLChannel; +import org.java_websocket.protocols.IProtocol; +import org.java_websocket.server.WebSocketServer.WebSocketWorker; +import org.java_websocket.util.Charsetfunctions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.net.ssl.SSLSession; - /** * Represents one end (client or server) of a single WebSocketImpl connection. Takes care of the * "handshake" phase, then allows for easy sending of text frames, and receiving frames through an @@ -507,8 +516,8 @@ public void close(int code, String message) { * @param message the closing message * @param remote Indicates who "generated" code.
      * true means that this endpoint received the code from - * the other endpoint.
      - * false means this endpoint decided to send the given code,
      + * the other endpoint.
      false means this endpoint decided to send the given + * code,
      * remote may also be true if this endpoint started the closing * handshake since the other endpoint may not simply echo the code but * close the connection the same time this endpoint does do but with an other diff --git a/src/main/java/org/java_websocket/WebSocketListener.java b/src/main/java/org/java_websocket/WebSocketListener.java index 2150e23ec..6d2bfdd92 100644 --- a/src/main/java/org/java_websocket/WebSocketListener.java +++ b/src/main/java/org/java_websocket/WebSocketListener.java @@ -27,7 +27,6 @@ import java.net.InetSocketAddress; import java.nio.ByteBuffer; - import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.framing.CloseFrame; diff --git a/src/main/java/org/java_websocket/WebSocketServerFactory.java b/src/main/java/org/java_websocket/WebSocketServerFactory.java index d6d5cce82..825aa2165 100644 --- a/src/main/java/org/java_websocket/WebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/WebSocketServerFactory.java @@ -25,13 +25,12 @@ package org.java_websocket; -import org.java_websocket.drafts.Draft; - import java.io.IOException; import java.nio.channels.ByteChannel; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.List; +import org.java_websocket.drafts.Draft; /** * Interface to encapsulate the required methods for a websocket factory diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 91288f080..8ab3684b8 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -42,10 +42,13 @@ import java.util.TreeMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; - import javax.net.SocketFactory; -import javax.net.ssl.*; - +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; import org.java_websocket.AbstractWebSocket; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketImpl; diff --git a/src/main/java/org/java_websocket/drafts/Draft.java b/src/main/java/org/java_websocket/drafts/Draft.java index 68cc49c69..7ba1ee4b3 100644 --- a/src/main/java/org/java_websocket/drafts/Draft.java +++ b/src/main/java/org/java_websocket/drafts/Draft.java @@ -30,7 +30,6 @@ import java.util.Iterator; import java.util.List; import java.util.Locale; - import org.java_websocket.WebSocketImpl; import org.java_websocket.enums.CloseHandshakeType; import org.java_websocket.enums.HandshakeState; @@ -39,7 +38,12 @@ import org.java_websocket.exceptions.IncompleteHandshakeException; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.InvalidHandshakeException; -import org.java_websocket.framing.*; +import org.java_websocket.framing.BinaryFrame; +import org.java_websocket.framing.CloseFrame; +import org.java_websocket.framing.ContinuousFrame; +import org.java_websocket.framing.DataFrame; +import org.java_websocket.framing.Framedata; +import org.java_websocket.framing.TextFrame; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.ClientHandshakeBuilder; import org.java_websocket.handshake.HandshakeBuilder; diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index 8898babb0..e81ebe4fa 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -25,26 +25,50 @@ package org.java_websocket.drafts; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.Random; +import java.util.TimeZone; import org.java_websocket.WebSocketImpl; -import org.java_websocket.enums.*; -import org.java_websocket.exceptions.*; -import org.java_websocket.extensions.*; -import org.java_websocket.framing.*; -import org.java_websocket.handshake.*; +import org.java_websocket.enums.CloseHandshakeType; +import org.java_websocket.enums.HandshakeState; +import org.java_websocket.enums.Opcode; +import org.java_websocket.enums.ReadyState; +import org.java_websocket.enums.Role; +import org.java_websocket.exceptions.IncompleteException; +import org.java_websocket.exceptions.InvalidDataException; +import org.java_websocket.exceptions.InvalidFrameException; +import org.java_websocket.exceptions.InvalidHandshakeException; +import org.java_websocket.exceptions.LimitExceededException; +import org.java_websocket.exceptions.NotSendableException; +import org.java_websocket.extensions.DefaultExtension; +import org.java_websocket.extensions.IExtension; +import org.java_websocket.framing.BinaryFrame; +import org.java_websocket.framing.CloseFrame; +import org.java_websocket.framing.Framedata; +import org.java_websocket.framing.FramedataImpl1; +import org.java_websocket.framing.TextFrame; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.handshake.ClientHandshakeBuilder; +import org.java_websocket.handshake.HandshakeBuilder; +import org.java_websocket.handshake.ServerHandshake; +import org.java_websocket.handshake.ServerHandshakeBuilder; import org.java_websocket.protocols.IProtocol; import org.java_websocket.protocols.Protocol; -import org.java_websocket.util.*; import org.java_websocket.util.Base64; +import org.java_websocket.util.Charsetfunctions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.math.BigInteger; -import java.nio.ByteBuffer; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.text.SimpleDateFormat; -import java.util.*; - /** * Implementation for the RFC 6455 websocket protocol This is the recommended class for your * websocket connection diff --git a/src/main/java/org/java_websocket/exceptions/WrappedIOException.java b/src/main/java/org/java_websocket/exceptions/WrappedIOException.java index f8f1b1a1c..fbcaddeaa 100644 --- a/src/main/java/org/java_websocket/exceptions/WrappedIOException.java +++ b/src/main/java/org/java_websocket/exceptions/WrappedIOException.java @@ -26,9 +26,8 @@ package org.java_websocket.exceptions; -import org.java_websocket.WebSocket; - import java.io.IOException; +import org.java_websocket.WebSocket; /** * Exception to wrap an IOException and include information about the websocket which had the diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index 6e414636f..41f4bbb72 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -1,5 +1,12 @@ package org.java_websocket.extensions.permessage_deflate; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.zip.DataFormatException; +import java.util.zip.Deflater; +import java.util.zip.Inflater; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.InvalidFrameException; @@ -14,14 +21,6 @@ import org.java_websocket.framing.FramedataImpl1; import org.java_websocket.framing.TextFrame; -import java.io.ByteArrayOutputStream; -import java.nio.ByteBuffer; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.zip.DataFormatException; -import java.util.zip.Deflater; -import java.util.zip.Inflater; - /** * PerMessage Deflate Extension (7. The * "permessage-deflate" Extension in diff --git a/src/main/java/org/java_websocket/framing/CloseFrame.java b/src/main/java/org/java_websocket/framing/CloseFrame.java index 15cd8cc41..5a63d8ae5 100644 --- a/src/main/java/org/java_websocket/framing/CloseFrame.java +++ b/src/main/java/org/java_websocket/framing/CloseFrame.java @@ -25,14 +25,13 @@ package org.java_websocket.framing; +import java.nio.ByteBuffer; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.InvalidFrameException; import org.java_websocket.util.ByteBufferUtils; import org.java_websocket.util.Charsetfunctions; -import java.nio.ByteBuffer; - /** * Class to represent a close frame */ diff --git a/src/main/java/org/java_websocket/framing/Framedata.java b/src/main/java/org/java_websocket/framing/Framedata.java index 11c4e01ce..d3e8f3cbe 100644 --- a/src/main/java/org/java_websocket/framing/Framedata.java +++ b/src/main/java/org/java_websocket/framing/Framedata.java @@ -25,8 +25,8 @@ package org.java_websocket.framing; -import org.java_websocket.enums.Opcode; import java.nio.ByteBuffer; +import org.java_websocket.enums.Opcode; /** * The interface for the frame diff --git a/src/main/java/org/java_websocket/framing/FramedataImpl1.java b/src/main/java/org/java_websocket/framing/FramedataImpl1.java index 5dc30cf8a..fc74f7aa2 100644 --- a/src/main/java/org/java_websocket/framing/FramedataImpl1.java +++ b/src/main/java/org/java_websocket/framing/FramedataImpl1.java @@ -25,12 +25,11 @@ package org.java_websocket.framing; +import java.nio.ByteBuffer; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.util.ByteBufferUtils; -import java.nio.ByteBuffer; - /** * Abstract implementation of a frame */ diff --git a/src/main/java/org/java_websocket/server/CustomSSLWebSocketServerFactory.java b/src/main/java/org/java_websocket/server/CustomSSLWebSocketServerFactory.java index 6fc0c6970..1246b22d9 100644 --- a/src/main/java/org/java_websocket/server/CustomSSLWebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/server/CustomSSLWebSocketServerFactory.java @@ -25,16 +25,15 @@ package org.java_websocket.server; -import org.java_websocket.SSLSocketChannel2; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLEngine; import java.io.IOException; import java.nio.channels.ByteChannel; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import org.java_websocket.SSLSocketChannel2; /** * WebSocketFactory that can be configured to only support specific protocols and cipher suites. diff --git a/src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java b/src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java index 0af105e3c..be5c8e678 100644 --- a/src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java @@ -34,11 +34,12 @@ import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; - import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; - -import org.java_websocket.*; +import org.java_websocket.SSLSocketChannel2; +import org.java_websocket.WebSocketAdapter; +import org.java_websocket.WebSocketImpl; +import org.java_websocket.WebSocketServerFactory; import org.java_websocket.drafts.Draft; public class DefaultSSLWebSocketServerFactory implements WebSocketServerFactory { diff --git a/src/main/java/org/java_websocket/server/DefaultWebSocketServerFactory.java b/src/main/java/org/java_websocket/server/DefaultWebSocketServerFactory.java index 8e9c7a197..80527e8e7 100644 --- a/src/main/java/org/java_websocket/server/DefaultWebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/server/DefaultWebSocketServerFactory.java @@ -28,11 +28,10 @@ import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.List; - import org.java_websocket.WebSocketAdapter; import org.java_websocket.WebSocketImpl; -import org.java_websocket.drafts.Draft; import org.java_websocket.WebSocketServerFactory; +import org.java_websocket.drafts.Draft; public class DefaultWebSocketServerFactory implements WebSocketServerFactory { diff --git a/src/main/java/org/java_websocket/server/SSLParametersWebSocketServerFactory.java b/src/main/java/org/java_websocket/server/SSLParametersWebSocketServerFactory.java index a98474dd5..d7685bfd8 100644 --- a/src/main/java/org/java_websocket/server/SSLParametersWebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/server/SSLParametersWebSocketServerFactory.java @@ -25,17 +25,16 @@ package org.java_websocket.server; -import org.java_websocket.SSLSocketChannel2; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLParameters; import java.io.IOException; import java.nio.channels.ByteChannel; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLParameters; +import org.java_websocket.SSLSocketChannel2; /** * WebSocketFactory that can be configured to only support specific protocols and cipher suites. diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index d46e46065..b55ed3b7c 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -26,7 +26,10 @@ package org.java_websocket.server; import java.io.IOException; -import java.net.*; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedByInterruptException; @@ -35,14 +38,28 @@ import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; - -import org.java_websocket.*; +import org.java_websocket.AbstractWebSocket; +import org.java_websocket.SocketChannelIOHelper; +import org.java_websocket.WebSocket; +import org.java_websocket.WebSocketFactory; +import org.java_websocket.WebSocketImpl; +import org.java_websocket.WebSocketServerFactory; +import org.java_websocket.WrappedByteChannel; import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.WebsocketNotConnectedException; import org.java_websocket.exceptions.WrappedIOException; diff --git a/src/main/java/org/java_websocket/util/Charsetfunctions.java b/src/main/java/org/java_websocket/util/Charsetfunctions.java index 43cde55cc..78fd8b552 100644 --- a/src/main/java/org/java_websocket/util/Charsetfunctions.java +++ b/src/main/java/org/java_websocket/util/Charsetfunctions.java @@ -25,16 +25,15 @@ package org.java_websocket.util; -import org.java_websocket.exceptions.InvalidDataException; -import org.java_websocket.exceptions.InvalidEncodingException; -import org.java_websocket.framing.CloseFrame; - import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; +import org.java_websocket.exceptions.InvalidDataException; +import org.java_websocket.exceptions.InvalidEncodingException; +import org.java_websocket.framing.CloseFrame; public class Charsetfunctions { diff --git a/src/test/java/org/java_websocket/autobahn/AutobahnServerResultsTest.java b/src/test/java/org/java_websocket/autobahn/AutobahnServerResultsTest.java index ecebd18cf..807714049 100644 --- a/src/test/java/org/java_websocket/autobahn/AutobahnServerResultsTest.java +++ b/src/test/java/org/java_websocket/autobahn/AutobahnServerResultsTest.java @@ -25,16 +25,15 @@ package org.java_websocket.autobahn; -import org.json.JSONObject; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; - -import static org.junit.Assert.assertEquals; +import org.json.JSONObject; +import org.junit.Assume; +import org.junit.BeforeClass; +import org.junit.Test; public class AutobahnServerResultsTest { diff --git a/src/test/java/org/java_websocket/client/AttachmentTest.java b/src/test/java/org/java_websocket/client/AttachmentTest.java index 068b239d3..3a094816e 100644 --- a/src/test/java/org/java_websocket/client/AttachmentTest.java +++ b/src/test/java/org/java_websocket/client/AttachmentTest.java @@ -25,14 +25,13 @@ package org.java_websocket.client; -import org.java_websocket.handshake.ServerHandshake; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import java.net.URI; import java.net.URISyntaxException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import org.java_websocket.handshake.ServerHandshake; +import org.junit.Test; public class AttachmentTest { diff --git a/src/test/java/org/java_websocket/client/HeadersTest.java b/src/test/java/org/java_websocket/client/HeadersTest.java index e5d7426e9..7d31422b5 100644 --- a/src/test/java/org/java_websocket/client/HeadersTest.java +++ b/src/test/java/org/java_websocket/client/HeadersTest.java @@ -25,16 +25,15 @@ package org.java_websocket.client; -import org.java_websocket.handshake.ServerHandshake; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import org.java_websocket.handshake.ServerHandshake; +import org.junit.Test; public class HeadersTest { diff --git a/src/test/java/org/java_websocket/client/SchemaCheckTest.java b/src/test/java/org/java_websocket/client/SchemaCheckTest.java index 141b27f43..30f13e6f9 100644 --- a/src/test/java/org/java_websocket/client/SchemaCheckTest.java +++ b/src/test/java/org/java_websocket/client/SchemaCheckTest.java @@ -1,13 +1,12 @@ package org.java_websocket.client; -import org.java_websocket.handshake.ServerHandshake; -import org.junit.Test; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.net.URI; import java.net.URISyntaxException; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.java_websocket.handshake.ServerHandshake; +import org.junit.Test; public class SchemaCheckTest { diff --git a/src/test/java/org/java_websocket/drafts/Draft_6455Test.java b/src/test/java/org/java_websocket/drafts/Draft_6455Test.java index a297b9bc9..d272de7fe 100644 --- a/src/test/java/org/java_websocket/drafts/Draft_6455Test.java +++ b/src/test/java/org/java_websocket/drafts/Draft_6455Test.java @@ -25,6 +25,17 @@ package org.java_websocket.drafts; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import org.java_websocket.enums.CloseHandshakeType; import org.java_websocket.enums.HandshakeState; import org.java_websocket.exceptions.InvalidHandshakeException; @@ -40,13 +51,6 @@ import org.java_websocket.util.Charsetfunctions; import org.junit.Test; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import static org.junit.Assert.*; - public class Draft_6455Test { HandshakeImpl1Client handshakedataProtocolExtension; diff --git a/src/test/java/org/java_websocket/example/AutobahnClientTest.java b/src/test/java/org/java_websocket/example/AutobahnClientTest.java index 1d90685f5..9a3ce5235 100644 --- a/src/test/java/org/java_websocket/example/AutobahnClientTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnClientTest.java @@ -30,14 +30,9 @@ import java.io.InputStreamReader; import java.net.URI; import java.nio.ByteBuffer; - -import org.java_websocket.WebSocket; -import org.java_websocket.WebSocketImpl; import org.java_websocket.client.WebSocketClient; import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_6455; -import org.java_websocket.framing.Framedata; -import org.java_websocket.framing.FramedataImpl1; import org.java_websocket.handshake.ServerHandshake; public class AutobahnClientTest extends WebSocketClient { diff --git a/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java b/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java index d5938eeab..7d3fa79b7 100644 --- a/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java @@ -25,19 +25,6 @@ package org.java_websocket.example; -import org.java_websocket.WebSocket; -import org.java_websocket.WebSocketImpl; -import org.java_websocket.drafts.Draft; -import org.java_websocket.drafts.Draft_6455; -import org.java_websocket.framing.Framedata; -import org.java_websocket.framing.FramedataImpl1; -import org.java_websocket.handshake.ClientHandshake; -import org.java_websocket.server.DefaultSSLWebSocketServerFactory; -import org.java_websocket.server.WebSocketServer; - -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManagerFactory; import java.io.File; import java.io.FileInputStream; import java.net.InetSocketAddress; @@ -45,8 +32,16 @@ import java.nio.ByteBuffer; import java.nio.file.Paths; import java.security.KeyStore; -import java.security.spec.ECField; import java.util.Collections; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; +import org.java_websocket.WebSocket; +import org.java_websocket.drafts.Draft; +import org.java_websocket.drafts.Draft_6455; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.server.DefaultSSLWebSocketServerFactory; +import org.java_websocket.server.WebSocketServer; public class AutobahnSSLServerTest extends WebSocketServer { diff --git a/src/test/java/org/java_websocket/example/AutobahnServerTest.java b/src/test/java/org/java_websocket/example/AutobahnServerTest.java index 77995eb96..0f6bc84df 100644 --- a/src/test/java/org/java_websocket/example/AutobahnServerTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnServerTest.java @@ -25,6 +25,10 @@ package org.java_websocket.example; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.nio.ByteBuffer; +import java.util.Collections; import org.java_websocket.WebSocket; import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_6455; @@ -32,11 +36,6 @@ import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; -import java.net.InetSocketAddress; -import java.net.UnknownHostException; -import java.nio.ByteBuffer; -import java.util.Collections; - public class AutobahnServerTest extends WebSocketServer { private static int openCounter = 0; diff --git a/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java b/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java index 439531d3b..9a9916dea 100644 --- a/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java @@ -25,12 +25,9 @@ package org.java_websocket.exceptions; -import org.junit.Test; - -import java.io.UnsupportedEncodingException; - import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; + +import org.junit.Test; /** * JUnit Test for the IncompleteException class diff --git a/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java b/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java index 30352a24f..9cf1829fd 100644 --- a/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java @@ -25,10 +25,10 @@ package org.java_websocket.exceptions; -import org.junit.Test; - import static org.junit.Assert.assertEquals; +import org.junit.Test; + /** * JUnit Test for the IncompleteHandshakeException class */ diff --git a/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java index 45bf81e5f..c9c4e5849 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java @@ -25,11 +25,10 @@ package org.java_websocket.exceptions; -import org.java_websocket.framing.CloseFrame; -import org.junit.Test; - import static org.junit.Assert.assertEquals; +import org.junit.Test; + /** * JUnit Test for the InvalidDataException class */ diff --git a/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java index 144b4a4da..96e005be5 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java @@ -25,13 +25,12 @@ package org.java_websocket.exceptions; -import org.junit.Test; - -import java.io.UnsupportedEncodingException; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; +import java.io.UnsupportedEncodingException; +import org.junit.Test; + /** * JUnit Test for the InvalidEncodingException class */ diff --git a/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java index 5337e333b..27a2e0dbd 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java @@ -25,11 +25,11 @@ package org.java_websocket.exceptions; +import static org.junit.Assert.assertEquals; + import org.java_websocket.framing.CloseFrame; import org.junit.Test; -import static org.junit.Assert.assertEquals; - /** * JUnit Test for the InvalidFrameException class */ diff --git a/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java index 3832e77b5..da9fdc94b 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java @@ -25,11 +25,11 @@ package org.java_websocket.exceptions; +import static org.junit.Assert.assertEquals; + import org.java_websocket.framing.CloseFrame; import org.junit.Test; -import static org.junit.Assert.assertEquals; - /** * JUnit Test for the InvalidHandshakeException class */ diff --git a/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java b/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java index a5ef5c4a8..4cc6ca9a6 100644 --- a/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java @@ -25,15 +25,11 @@ package org.java_websocket.exceptions; +import static org.junit.Assert.assertEquals; + import org.java_websocket.framing.CloseFrame; -import org.java_websocket.framing.ControlFrame; import org.junit.Test; -import java.io.UnsupportedEncodingException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - /** * JUnit Test for the InvalidEncodingException class */ diff --git a/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java b/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java index 4d5087129..0fb2440fd 100644 --- a/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java @@ -25,11 +25,10 @@ package org.java_websocket.exceptions; -import org.java_websocket.framing.CloseFrame; -import org.junit.Test; - import static org.junit.Assert.assertEquals; +import org.junit.Test; + /** * JUnit Test for the NotSendableException class */ diff --git a/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java b/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java index e1c681da1..e163b2260 100644 --- a/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java @@ -25,11 +25,9 @@ package org.java_websocket.exceptions; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; + +import org.junit.Test; /** * JUnit Test for the WebsocketNotConnectedException class diff --git a/src/test/java/org/java_websocket/extensions/CompressionExtensionTest.java b/src/test/java/org/java_websocket/extensions/CompressionExtensionTest.java index d2c468936..946e28ce7 100644 --- a/src/test/java/org/java_websocket/extensions/CompressionExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/CompressionExtensionTest.java @@ -1,11 +1,11 @@ package org.java_websocket.extensions; +import static org.junit.Assert.fail; + import org.java_websocket.framing.PingFrame; import org.java_websocket.framing.TextFrame; import org.junit.Test; -import static org.junit.Assert.fail; - public class CompressionExtensionTest { diff --git a/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java b/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java index 7aa66f7f4..6d373f15f 100644 --- a/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java @@ -25,14 +25,16 @@ package org.java_websocket.extensions; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.nio.ByteBuffer; import org.java_websocket.framing.BinaryFrame; import org.java_websocket.framing.TextFrame; import org.junit.Test; -import java.nio.ByteBuffer; - -import static org.junit.Assert.*; - public class DefaultExtensionTest { @Test diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index dbbd63497..624748318 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -1,21 +1,20 @@ package org.java_websocket.extensions; -import org.java_websocket.exceptions.InvalidDataException; -import org.java_websocket.extensions.permessage_deflate.PerMessageDeflateExtension; -import org.java_websocket.framing.ContinuousFrame; -import org.java_websocket.framing.TextFrame; -import org.junit.Test; - -import java.nio.ByteBuffer; -import java.util.zip.Deflater; -import java.util.zip.Inflater; - import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.nio.ByteBuffer; +import java.util.zip.Deflater; +import java.util.zip.Inflater; +import org.java_websocket.exceptions.InvalidDataException; +import org.java_websocket.extensions.permessage_deflate.PerMessageDeflateExtension; +import org.java_websocket.framing.ContinuousFrame; +import org.java_websocket.framing.TextFrame; +import org.junit.Test; + public class PerMessageDeflateExtensionTest { @Test diff --git a/src/test/java/org/java_websocket/framing/BinaryFrameTest.java b/src/test/java/org/java_websocket/framing/BinaryFrameTest.java index 364b3cf61..a14e4ef25 100644 --- a/src/test/java/org/java_websocket/framing/BinaryFrameTest.java +++ b/src/test/java/org/java_websocket/framing/BinaryFrameTest.java @@ -25,13 +25,13 @@ package org.java_websocket.framing; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - /** * JUnit Test for the BinaryFrame class */ diff --git a/src/test/java/org/java_websocket/framing/CloseFrameTest.java b/src/test/java/org/java_websocket/framing/CloseFrameTest.java index 2932e29cf..4000b2c9d 100644 --- a/src/test/java/org/java_websocket/framing/CloseFrameTest.java +++ b/src/test/java/org/java_websocket/framing/CloseFrameTest.java @@ -25,13 +25,13 @@ package org.java_websocket.framing; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - /** * JUnit Test for the CloseFrame class */ diff --git a/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java b/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java index a39b6be10..db0f6f4b9 100644 --- a/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java +++ b/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java @@ -25,13 +25,13 @@ package org.java_websocket.framing; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - /** * JUnit Test for the ContinuousFrame class */ diff --git a/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java b/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java index 8c099f0dc..9e7db85a3 100644 --- a/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java +++ b/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java @@ -25,15 +25,14 @@ package org.java_websocket.framing; -import org.java_websocket.enums.Opcode; -import org.junit.Test; - -import java.nio.ByteBuffer; - import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; +import java.nio.ByteBuffer; +import org.java_websocket.enums.Opcode; +import org.junit.Test; + /** * JUnit Test for the FramedataImpl1 class */ diff --git a/src/test/java/org/java_websocket/framing/PingFrameTest.java b/src/test/java/org/java_websocket/framing/PingFrameTest.java index 9c5177bbe..e5c90d4dd 100644 --- a/src/test/java/org/java_websocket/framing/PingFrameTest.java +++ b/src/test/java/org/java_websocket/framing/PingFrameTest.java @@ -25,13 +25,13 @@ package org.java_websocket.framing; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - /** * JUnit Test for the PingFrame class */ diff --git a/src/test/java/org/java_websocket/framing/PongFrameTest.java b/src/test/java/org/java_websocket/framing/PongFrameTest.java index 6fb9490b3..c98c09ccc 100644 --- a/src/test/java/org/java_websocket/framing/PongFrameTest.java +++ b/src/test/java/org/java_websocket/framing/PongFrameTest.java @@ -25,15 +25,14 @@ package org.java_websocket.framing; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.nio.ByteBuffer; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; import org.junit.Test; -import java.nio.ByteBuffer; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - /** * JUnit Test for the PongFrame class */ diff --git a/src/test/java/org/java_websocket/framing/TextFrameTest.java b/src/test/java/org/java_websocket/framing/TextFrameTest.java index fc7d5041a..d4e0dabc6 100644 --- a/src/test/java/org/java_websocket/framing/TextFrameTest.java +++ b/src/test/java/org/java_websocket/framing/TextFrameTest.java @@ -25,15 +25,14 @@ package org.java_websocket.framing; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.nio.ByteBuffer; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; import org.junit.Test; -import java.nio.ByteBuffer; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - /** * JUnit Test for the TextFrame class */ diff --git a/src/test/java/org/java_websocket/issues/Issue256Test.java b/src/test/java/org/java_websocket/issues/Issue256Test.java index 314185d12..4faf1fa14 100644 --- a/src/test/java/org/java_websocket/issues/Issue256Test.java +++ b/src/test/java/org/java_websocket/issues/Issue256Test.java @@ -25,29 +25,30 @@ package org.java_websocket.issues; +import static org.hamcrest.core.Is.is; +import static org.junit.Assume.assumeThat; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.CountDownLatch; import org.java_websocket.WebSocket; -import org.java_websocket.WebSocketImpl; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; import org.java_websocket.util.ThreadCheck; -import org.junit.*; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.URI; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.CountDownLatch; - -import static org.hamcrest.core.Is.is; -import static org.junit.Assume.assumeThat; - @RunWith(Parameterized.class) public class Issue256Test { diff --git a/src/test/java/org/java_websocket/issues/Issue580Test.java b/src/test/java/org/java_websocket/issues/Issue580Test.java index 64e445f37..4a2e31848 100644 --- a/src/test/java/org/java_websocket/issues/Issue580Test.java +++ b/src/test/java/org/java_websocket/issues/Issue580Test.java @@ -25,9 +25,14 @@ package org.java_websocket.issues; +import java.net.InetSocketAddress; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.CountDownLatch; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; -import org.java_websocket.framing.CloseFrame; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; @@ -38,13 +43,6 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import java.net.InetSocketAddress; -import java.net.URI; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.CountDownLatch; - @RunWith(Parameterized.class) public class Issue580Test { diff --git a/src/test/java/org/java_websocket/issues/Issue598Test.java b/src/test/java/org/java_websocket/issues/Issue598Test.java index c6705a7c4..c45f228cb 100644 --- a/src/test/java/org/java_websocket/issues/Issue598Test.java +++ b/src/test/java/org/java_websocket/issues/Issue598Test.java @@ -25,6 +25,12 @@ package org.java_websocket.issues; +import java.net.InetSocketAddress; +import java.net.URI; +import java.nio.ByteBuffer; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.drafts.Draft; @@ -40,15 +46,6 @@ import org.java_websocket.util.SocketUtil; import org.junit.Test; -import java.net.InetSocketAddress; -import java.net.URI; -import java.nio.ByteBuffer; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CountDownLatch; - -import static org.junit.Assert.assertTrue; - public class Issue598Test { private static List protocolList = Collections.singletonList( diff --git a/src/test/java/org/java_websocket/issues/Issue609Test.java b/src/test/java/org/java_websocket/issues/Issue609Test.java index 51b7f58b7..b84e3cfd9 100644 --- a/src/test/java/org/java_websocket/issues/Issue609Test.java +++ b/src/test/java/org/java_websocket/issues/Issue609Test.java @@ -25,6 +25,11 @@ package org.java_websocket.issues; +import static org.junit.Assert.assertTrue; + +import java.net.InetSocketAddress; +import java.net.URI; +import java.util.concurrent.CountDownLatch; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ClientHandshake; @@ -33,12 +38,6 @@ import org.java_websocket.util.SocketUtil; import org.junit.Test; -import java.net.InetSocketAddress; -import java.net.URI; -import java.util.concurrent.CountDownLatch; - -import static org.junit.Assert.assertTrue; - public class Issue609Test { CountDownLatch countDownLatch = new CountDownLatch(1); diff --git a/src/test/java/org/java_websocket/issues/Issue621Test.java b/src/test/java/org/java_websocket/issues/Issue621Test.java index 11cca8e9f..1a6a173ad 100644 --- a/src/test/java/org/java_websocket/issues/Issue621Test.java +++ b/src/test/java/org/java_websocket/issues/Issue621Test.java @@ -25,6 +25,13 @@ package org.java_websocket.issues; +import static org.junit.Assert.assertTrue; + +import java.io.OutputStream; +import java.io.PrintStream; +import java.net.InetSocketAddress; +import java.net.URI; +import java.util.concurrent.CountDownLatch; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ClientHandshake; @@ -33,14 +40,6 @@ import org.java_websocket.util.SocketUtil; import org.junit.Test; -import java.io.OutputStream; -import java.io.PrintStream; -import java.net.InetSocketAddress; -import java.net.URI; -import java.util.concurrent.CountDownLatch; - -import static org.junit.Assert.assertTrue; - public class Issue621Test { CountDownLatch countDownLatch = new CountDownLatch(1); diff --git a/src/test/java/org/java_websocket/issues/Issue661Test.java b/src/test/java/org/java_websocket/issues/Issue661Test.java index 0c8965e84..bda984431 100644 --- a/src/test/java/org/java_websocket/issues/Issue661Test.java +++ b/src/test/java/org/java_websocket/issues/Issue661Test.java @@ -25,6 +25,13 @@ package org.java_websocket.issues; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.net.BindException; +import java.net.InetSocketAddress; +import java.util.concurrent.CountDownLatch; import org.java_websocket.WebSocket; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; @@ -33,14 +40,6 @@ import org.junit.Rule; import org.junit.Test; -import java.io.OutputStream; -import java.io.PrintStream; -import java.net.BindException; -import java.net.InetSocketAddress; -import java.util.concurrent.CountDownLatch; - -import static org.junit.Assert.*; - public class Issue661Test { @Rule diff --git a/src/test/java/org/java_websocket/issues/Issue666Test.java b/src/test/java/org/java_websocket/issues/Issue666Test.java index 8c0fdb200..a4f2523b5 100644 --- a/src/test/java/org/java_websocket/issues/Issue666Test.java +++ b/src/test/java/org/java_websocket/issues/Issue666Test.java @@ -25,6 +25,10 @@ package org.java_websocket.issues; +import java.net.InetSocketAddress; +import java.net.URI; +import java.util.Map; +import java.util.concurrent.CountDownLatch; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ClientHandshake; @@ -35,11 +39,6 @@ import org.junit.Assert; import org.junit.Test; -import java.net.InetSocketAddress; -import java.net.URI; -import java.util.Map; -import java.util.concurrent.CountDownLatch; - public class Issue666Test { private CountDownLatch countServerDownLatch = new CountDownLatch(1); diff --git a/src/test/java/org/java_websocket/issues/Issue677Test.java b/src/test/java/org/java_websocket/issues/Issue677Test.java index 39d8d16f1..d35fed8a3 100644 --- a/src/test/java/org/java_websocket/issues/Issue677Test.java +++ b/src/test/java/org/java_websocket/issues/Issue677Test.java @@ -25,6 +25,11 @@ package org.java_websocket.issues; +import static org.junit.Assert.assertTrue; + +import java.net.InetSocketAddress; +import java.net.URI; +import java.util.concurrent.CountDownLatch; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.framing.CloseFrame; @@ -34,12 +39,6 @@ import org.java_websocket.util.SocketUtil; import org.junit.Test; -import java.net.InetSocketAddress; -import java.net.URI; -import java.util.concurrent.CountDownLatch; - -import static org.junit.Assert.assertTrue; - public class Issue677Test { CountDownLatch countDownLatch0 = new CountDownLatch(1); diff --git a/src/test/java/org/java_websocket/issues/Issue713Test.java b/src/test/java/org/java_websocket/issues/Issue713Test.java index 3121aa059..1b752aaf8 100644 --- a/src/test/java/org/java_websocket/issues/Issue713Test.java +++ b/src/test/java/org/java_websocket/issues/Issue713Test.java @@ -25,15 +25,7 @@ package org.java_websocket.issues; -import org.java_websocket.WebSocket; -import org.java_websocket.client.WebSocketClient; -import org.java_websocket.framing.CloseFrame; -import org.java_websocket.handshake.ClientHandshake; -import org.java_websocket.handshake.ServerHandshake; -import org.java_websocket.server.WebSocketServer; -import org.java_websocket.util.SocketUtil; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.Assert.fail; import java.io.IOException; import java.net.InetSocketAddress; @@ -42,9 +34,13 @@ import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import org.java_websocket.WebSocket; +import org.java_websocket.client.WebSocketClient; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.handshake.ServerHandshake; +import org.java_websocket.server.WebSocketServer; +import org.java_websocket.util.SocketUtil; +import org.junit.Test; public class Issue713Test { diff --git a/src/test/java/org/java_websocket/issues/Issue732Test.java b/src/test/java/org/java_websocket/issues/Issue732Test.java index 7a21ae51f..e811f8aa0 100644 --- a/src/test/java/org/java_websocket/issues/Issue732Test.java +++ b/src/test/java/org/java_websocket/issues/Issue732Test.java @@ -25,8 +25,12 @@ package org.java_websocket.issues; +import static org.junit.Assert.fail; + +import java.net.InetSocketAddress; +import java.net.URI; +import java.util.concurrent.CountDownLatch; import org.java_websocket.WebSocket; -import org.java_websocket.WebSocketImpl; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.ServerHandshake; @@ -37,12 +41,6 @@ import org.junit.Rule; import org.junit.Test; -import java.net.InetSocketAddress; -import java.net.URI; -import java.util.concurrent.CountDownLatch; - -import static org.junit.Assert.fail; - public class Issue732Test { @Rule diff --git a/src/test/java/org/java_websocket/issues/Issue764Test.java b/src/test/java/org/java_websocket/issues/Issue764Test.java index ff84c2176..40be7ef6c 100644 --- a/src/test/java/org/java_websocket/issues/Issue764Test.java +++ b/src/test/java/org/java_websocket/issues/Issue764Test.java @@ -26,6 +26,17 @@ package org.java_websocket.issues; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.util.concurrent.CountDownLatch; +import javax.net.ssl.SSLContext; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ClientHandshake; @@ -36,19 +47,6 @@ import org.java_websocket.util.SocketUtil; import org.junit.Test; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManagerFactory; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.*; -import java.security.cert.CertificateException; -import java.util.concurrent.CountDownLatch; - public class Issue764Test { private CountDownLatch countClientDownLatch = new CountDownLatch(2); diff --git a/src/test/java/org/java_websocket/issues/Issue765Test.java b/src/test/java/org/java_websocket/issues/Issue765Test.java index 44a43ccfa..a7a6188cd 100644 --- a/src/test/java/org/java_websocket/issues/Issue765Test.java +++ b/src/test/java/org/java_websocket/issues/Issue765Test.java @@ -26,6 +26,11 @@ package org.java_websocket.issues; +import java.io.IOException; +import java.nio.channels.ByteChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.SocketChannel; +import java.util.List; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketAdapter; import org.java_websocket.WebSocketImpl; @@ -36,12 +41,6 @@ import org.junit.Assert; import org.junit.Test; -import java.io.IOException; -import java.nio.channels.ByteChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.SocketChannel; -import java.util.List; - public class Issue765Test { boolean isClosedCalled = false; diff --git a/src/test/java/org/java_websocket/issues/Issue811Test.java b/src/test/java/org/java_websocket/issues/Issue811Test.java index e54e5e7c7..d438aa685 100644 --- a/src/test/java/org/java_websocket/issues/Issue811Test.java +++ b/src/test/java/org/java_websocket/issues/Issue811Test.java @@ -26,16 +26,15 @@ package org.java_websocket.issues; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.concurrent.CountDownLatch; import org.java_websocket.WebSocket; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; import org.junit.Test; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.concurrent.CountDownLatch; - public class Issue811Test { private CountDownLatch countServerDownLatch = new CountDownLatch(1); diff --git a/src/test/java/org/java_websocket/issues/Issue825Test.java b/src/test/java/org/java_websocket/issues/Issue825Test.java index c56481da5..d878dddde 100644 --- a/src/test/java/org/java_websocket/issues/Issue825Test.java +++ b/src/test/java/org/java_websocket/issues/Issue825Test.java @@ -26,6 +26,17 @@ package org.java_websocket.issues; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.util.concurrent.CountDownLatch; +import javax.net.ssl.SSLContext; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ClientHandshake; @@ -36,19 +47,6 @@ import org.java_websocket.util.SocketUtil; import org.junit.Test; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManagerFactory; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.*; -import java.security.cert.CertificateException; -import java.util.concurrent.CountDownLatch; - public class Issue825Test { diff --git a/src/test/java/org/java_websocket/issues/Issue834Test.java b/src/test/java/org/java_websocket/issues/Issue834Test.java index 434f53d05..350acf456 100644 --- a/src/test/java/org/java_websocket/issues/Issue834Test.java +++ b/src/test/java/org/java_websocket/issues/Issue834Test.java @@ -1,5 +1,8 @@ package org.java_websocket.issues; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.Set; import org.java_websocket.WebSocket; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; @@ -7,10 +10,6 @@ import org.junit.Assert; import org.junit.Test; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.Set; - public class Issue834Test { @Test(timeout = 1000) diff --git a/src/test/java/org/java_websocket/issues/Issue847Test.java b/src/test/java/org/java_websocket/issues/Issue847Test.java index 46b882cc6..f47e4fec5 100644 --- a/src/test/java/org/java_websocket/issues/Issue847Test.java +++ b/src/test/java/org/java_websocket/issues/Issue847Test.java @@ -26,6 +26,18 @@ package org.java_websocket.issues; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.URI; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Scanner; import org.java_websocket.client.WebSocketClient; import org.java_websocket.drafts.Draft_6455; import org.java_websocket.framing.BinaryFrame; @@ -39,19 +51,6 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import java.io.IOException; -import java.io.OutputStream; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.URI; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Scanner; - -import static org.junit.Assert.fail; - @RunWith(Parameterized.class) public class Issue847Test { diff --git a/src/test/java/org/java_websocket/issues/Issue855Test.java b/src/test/java/org/java_websocket/issues/Issue855Test.java index 15abaa84f..9f919b87e 100644 --- a/src/test/java/org/java_websocket/issues/Issue855Test.java +++ b/src/test/java/org/java_websocket/issues/Issue855Test.java @@ -26,6 +26,9 @@ package org.java_websocket.issues; +import java.net.InetSocketAddress; +import java.net.URI; +import java.util.concurrent.CountDownLatch; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ClientHandshake; @@ -34,10 +37,6 @@ import org.java_websocket.util.SocketUtil; import org.junit.Test; -import java.net.InetSocketAddress; -import java.net.URI; -import java.util.concurrent.CountDownLatch; - public class Issue855Test { CountDownLatch countServerDownLatch = new CountDownLatch(1); diff --git a/src/test/java/org/java_websocket/issues/Issue879Test.java b/src/test/java/org/java_websocket/issues/Issue879Test.java index 5e4f978de..bdd6fa1c0 100644 --- a/src/test/java/org/java_websocket/issues/Issue879Test.java +++ b/src/test/java/org/java_websocket/issues/Issue879Test.java @@ -26,15 +26,7 @@ package org.java_websocket.issues; -import org.java_websocket.WebSocket; -import org.java_websocket.client.WebSocketClient; -import org.java_websocket.handshake.ClientHandshake; -import org.java_websocket.handshake.ServerHandshake; -import org.java_websocket.server.WebSocketServer; -import org.java_websocket.util.SocketUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import static org.junit.Assert.assertFalse; import java.io.IOException; import java.net.BindException; @@ -47,8 +39,15 @@ import java.util.ConcurrentModificationException; import java.util.List; import java.util.concurrent.CountDownLatch; - -import static org.junit.Assert.assertFalse; +import org.java_websocket.WebSocket; +import org.java_websocket.client.WebSocketClient; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.handshake.ServerHandshake; +import org.java_websocket.server.WebSocketServer; +import org.java_websocket.util.SocketUtil; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class Issue879Test { diff --git a/src/test/java/org/java_websocket/issues/Issue890Test.java b/src/test/java/org/java_websocket/issues/Issue890Test.java index 877ab3574..7f05a23a4 100644 --- a/src/test/java/org/java_websocket/issues/Issue890Test.java +++ b/src/test/java/org/java_websocket/issues/Issue890Test.java @@ -26,6 +26,23 @@ package org.java_websocket.issues; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.util.concurrent.CountDownLatch; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ClientHandshake; @@ -36,22 +53,6 @@ import org.java_websocket.util.SocketUtil; import org.junit.Test; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManagerFactory; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.*; -import java.security.cert.CertificateException; -import java.util.concurrent.CountDownLatch; - -import static org.junit.Assert.*; - public class Issue890Test { diff --git a/src/test/java/org/java_websocket/issues/Issue900Test.java b/src/test/java/org/java_websocket/issues/Issue900Test.java index db606140d..952dca8ee 100644 --- a/src/test/java/org/java_websocket/issues/Issue900Test.java +++ b/src/test/java/org/java_websocket/issues/Issue900Test.java @@ -26,6 +26,12 @@ package org.java_websocket.issues; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.URI; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.concurrent.CountDownLatch; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketImpl; import org.java_websocket.WrappedByteChannel; @@ -36,13 +42,6 @@ import org.java_websocket.util.SocketUtil; import org.junit.Test; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.URI; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.concurrent.CountDownLatch; - public class Issue900Test { CountDownLatch serverStartLatch = new CountDownLatch(1); diff --git a/src/test/java/org/java_websocket/issues/Issue941Test.java b/src/test/java/org/java_websocket/issues/Issue941Test.java index 9553cd6a7..a9aedbaef 100644 --- a/src/test/java/org/java_websocket/issues/Issue941Test.java +++ b/src/test/java/org/java_websocket/issues/Issue941Test.java @@ -25,6 +25,12 @@ package org.java_websocket.issues; +import static org.junit.Assert.assertArrayEquals; + +import java.net.InetSocketAddress; +import java.net.URI; +import java.nio.ByteBuffer; +import java.util.concurrent.CountDownLatch; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.framing.Framedata; @@ -35,13 +41,6 @@ import org.java_websocket.util.SocketUtil; import org.junit.Test; -import java.net.InetSocketAddress; -import java.net.URI; -import java.nio.ByteBuffer; -import java.util.concurrent.CountDownLatch; - -import static org.junit.Assert.assertArrayEquals; - public class Issue941Test { private CountDownLatch pingLatch = new CountDownLatch(1); diff --git a/src/test/java/org/java_websocket/issues/Issue997Test.java b/src/test/java/org/java_websocket/issues/Issue997Test.java index 93f8cefe4..3c3b80641 100644 --- a/src/test/java/org/java_websocket/issues/Issue997Test.java +++ b/src/test/java/org/java_websocket/issues/Issue997Test.java @@ -27,21 +27,13 @@ */ -import org.java_websocket.WebSocket; -import org.java_websocket.client.WebSocketClient; -import org.java_websocket.handshake.ClientHandshake; -import org.java_websocket.handshake.ServerHandshake; -import org.java_websocket.server.DefaultSSLWebSocketServerFactory; -import org.java_websocket.server.WebSocketServer; -import org.java_websocket.util.SSLContextUtil; -import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLHandshakeException; -import javax.net.ssl.SSLParameters; import java.io.IOException; -import java.net.*; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URISyntaxException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; @@ -49,8 +41,18 @@ import java.security.cert.CertificateException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; - -import static org.junit.Assert.*; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLParameters; +import org.java_websocket.WebSocket; +import org.java_websocket.client.WebSocketClient; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.handshake.ServerHandshake; +import org.java_websocket.server.DefaultSSLWebSocketServerFactory; +import org.java_websocket.server.WebSocketServer; +import org.java_websocket.util.SSLContextUtil; +import org.java_websocket.util.SocketUtil; +import org.junit.Test; public class Issue997Test { diff --git a/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java b/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java index 11cbb0133..fe1805c1e 100644 --- a/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java +++ b/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java @@ -25,6 +25,14 @@ package org.java_websocket.misc; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.URI; +import java.util.Scanner; import org.java_websocket.client.WebSocketClient; import org.java_websocket.framing.CloseFrame; import org.java_websocket.handshake.ServerHandshake; @@ -34,15 +42,6 @@ import org.junit.BeforeClass; import org.junit.Test; -import java.io.IOException; -import java.io.OutputStream; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.URI; -import java.util.Scanner; - -import static org.junit.Assert.fail; - public class OpeningHandshakeRejectionTest { private static final String additionalHandshake = "Upgrade: websocket\r\nConnection: Upgrade\r\n\r\n"; diff --git a/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java b/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java index f0bf82fcb..270fab805 100644 --- a/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java +++ b/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java @@ -25,17 +25,9 @@ package org.java_websocket.protocols; -import org.java_websocket.client.WebSocketClient; -import org.java_websocket.drafts.Draft_6455; -import org.java_websocket.extensions.IExtension; -import org.java_websocket.framing.CloseFrame; -import org.java_websocket.handshake.ServerHandshake; -import org.java_websocket.util.Base64; -import org.java_websocket.util.Charsetfunctions; -import org.java_websocket.util.SocketUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; import java.io.IOException; import java.io.OutputStream; @@ -47,8 +39,17 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; - -import static org.junit.Assert.*; +import org.java_websocket.client.WebSocketClient; +import org.java_websocket.drafts.Draft_6455; +import org.java_websocket.extensions.IExtension; +import org.java_websocket.framing.CloseFrame; +import org.java_websocket.handshake.ServerHandshake; +import org.java_websocket.util.Base64; +import org.java_websocket.util.Charsetfunctions; +import org.java_websocket.util.SocketUtil; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; public class ProtoclHandshakeRejectionTest { diff --git a/src/test/java/org/java_websocket/protocols/ProtocolTest.java b/src/test/java/org/java_websocket/protocols/ProtocolTest.java index 23dd4d485..e07119535 100644 --- a/src/test/java/org/java_websocket/protocols/ProtocolTest.java +++ b/src/test/java/org/java_websocket/protocols/ProtocolTest.java @@ -25,9 +25,13 @@ package org.java_websocket.protocols; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; -import static org.junit.Assert.*; +import org.junit.Test; public class ProtocolTest { diff --git a/src/test/java/org/java_websocket/server/CustomSSLWebSocketServerFactoryTest.java b/src/test/java/org/java_websocket/server/CustomSSLWebSocketServerFactoryTest.java index 1222026ef..1fa2d8a9a 100644 --- a/src/test/java/org/java_websocket/server/CustomSSLWebSocketServerFactoryTest.java +++ b/src/test/java/org/java_websocket/server/CustomSSLWebSocketServerFactoryTest.java @@ -1,14 +1,8 @@ package org.java_websocket.server; -import org.java_websocket.WebSocket; -import org.java_websocket.WebSocketAdapter; -import org.java_websocket.WebSocketImpl; -import org.java_websocket.drafts.Draft; -import org.java_websocket.drafts.Draft_6455; -import org.java_websocket.handshake.Handshakedata; -import org.junit.Test; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; -import javax.net.ssl.SSLContext; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; @@ -18,9 +12,14 @@ import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.concurrent.Executors; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import javax.net.ssl.SSLContext; +import org.java_websocket.WebSocket; +import org.java_websocket.WebSocketAdapter; +import org.java_websocket.WebSocketImpl; +import org.java_websocket.drafts.Draft; +import org.java_websocket.drafts.Draft_6455; +import org.java_websocket.handshake.Handshakedata; +import org.junit.Test; public class CustomSSLWebSocketServerFactoryTest { diff --git a/src/test/java/org/java_websocket/server/DefaultSSLWebSocketServerFactoryTest.java b/src/test/java/org/java_websocket/server/DefaultSSLWebSocketServerFactoryTest.java index d2dd8f73f..7872697ba 100644 --- a/src/test/java/org/java_websocket/server/DefaultSSLWebSocketServerFactoryTest.java +++ b/src/test/java/org/java_websocket/server/DefaultSSLWebSocketServerFactoryTest.java @@ -1,29 +1,25 @@ package org.java_websocket.server; -import org.java_websocket.WebSocket; -import org.java_websocket.WebSocketAdapter; -import org.java_websocket.WebSocketImpl; -import org.java_websocket.drafts.Draft; -import org.java_websocket.drafts.Draft_6455; -import org.java_websocket.handshake.Handshakedata; -import org.junit.Test; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; -import javax.net.ssl.SSLContext; import java.io.IOException; -import java.net.*; +import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.NotYetConnectedException; import java.nio.channels.SocketChannel; -import java.nio.channels.spi.SelectorProvider; import java.security.NoSuchAlgorithmException; import java.util.Collections; -import java.util.Set; import java.util.concurrent.Executors; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +import javax.net.ssl.SSLContext; +import org.java_websocket.WebSocket; +import org.java_websocket.WebSocketAdapter; +import org.java_websocket.WebSocketImpl; +import org.java_websocket.drafts.Draft; +import org.java_websocket.drafts.Draft_6455; +import org.java_websocket.handshake.Handshakedata; +import org.junit.Test; public class DefaultSSLWebSocketServerFactoryTest { diff --git a/src/test/java/org/java_websocket/server/DefaultWebSocketServerFactoryTest.java b/src/test/java/org/java_websocket/server/DefaultWebSocketServerFactoryTest.java index 13a65bfcc..a5c07ea43 100644 --- a/src/test/java/org/java_websocket/server/DefaultWebSocketServerFactoryTest.java +++ b/src/test/java/org/java_websocket/server/DefaultWebSocketServerFactoryTest.java @@ -1,6 +1,13 @@ package org.java_websocket.server; -import org.java_websocket.SocketChannelIOHelper; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; + +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.util.Collections; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketAdapter; import org.java_websocket.WebSocketImpl; @@ -9,14 +16,6 @@ import org.java_websocket.handshake.Handshakedata; import org.junit.Test; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.nio.ByteBuffer; -import java.nio.channels.SocketChannel; -import java.util.Collections; - -import static org.junit.Assert.*; - public class DefaultWebSocketServerFactoryTest { @Test diff --git a/src/test/java/org/java_websocket/server/SSLParametersWebSocketServerFactoryTest.java b/src/test/java/org/java_websocket/server/SSLParametersWebSocketServerFactoryTest.java index 5b6300dd5..5ac83337d 100644 --- a/src/test/java/org/java_websocket/server/SSLParametersWebSocketServerFactoryTest.java +++ b/src/test/java/org/java_websocket/server/SSLParametersWebSocketServerFactoryTest.java @@ -1,15 +1,8 @@ package org.java_websocket.server; -import org.java_websocket.WebSocket; -import org.java_websocket.WebSocketAdapter; -import org.java_websocket.WebSocketImpl; -import org.java_websocket.drafts.Draft; -import org.java_websocket.drafts.Draft_6455; -import org.java_websocket.handshake.Handshakedata; -import org.junit.Test; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLParameters; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; @@ -19,9 +12,15 @@ import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.concurrent.Executors; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import org.java_websocket.WebSocket; +import org.java_websocket.WebSocketAdapter; +import org.java_websocket.WebSocketImpl; +import org.java_websocket.drafts.Draft; +import org.java_websocket.drafts.Draft_6455; +import org.java_websocket.handshake.Handshakedata; +import org.junit.Test; public class SSLParametersWebSocketServerFactoryTest { diff --git a/src/test/java/org/java_websocket/server/WebSocketServerTest.java b/src/test/java/org/java_websocket/server/WebSocketServerTest.java index 1f45a9e1f..decac6c28 100644 --- a/src/test/java/org/java_websocket/server/WebSocketServerTest.java +++ b/src/test/java/org/java_websocket/server/WebSocketServerTest.java @@ -26,15 +26,11 @@ package org.java_websocket.server; -import org.java_websocket.WebSocket; -import org.java_websocket.drafts.Draft; -import org.java_websocket.drafts.Draft_6455; -import org.java_websocket.handshake.ClientHandshake; -import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.fail; import java.io.IOException; -import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.Collection; @@ -42,8 +38,12 @@ import java.util.HashSet; import java.util.List; import java.util.concurrent.CountDownLatch; - -import static org.junit.Assert.*; +import org.java_websocket.WebSocket; +import org.java_websocket.drafts.Draft; +import org.java_websocket.drafts.Draft_6455; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.util.SocketUtil; +import org.junit.Test; public class WebSocketServerTest { diff --git a/src/test/java/org/java_websocket/util/Base64Test.java b/src/test/java/org/java_websocket/util/Base64Test.java index a45ddb9be..41122d779 100644 --- a/src/test/java/org/java_websocket/util/Base64Test.java +++ b/src/test/java/org/java_websocket/util/Base64Test.java @@ -25,13 +25,12 @@ package org.java_websocket.util; +import java.io.IOException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.io.IOException; - public class Base64Test { @Rule diff --git a/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java b/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java index 77b62c977..40523418e 100644 --- a/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java +++ b/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java @@ -25,11 +25,13 @@ package org.java_websocket.util; -import org.junit.Test; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.nio.ByteBuffer; - -import static org.junit.Assert.*; +import org.junit.Test; /** * JUnit Test for the new ByteBufferUtils class diff --git a/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java b/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java index 3c36ea7b9..4d8ef3ae9 100644 --- a/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java +++ b/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java @@ -25,12 +25,11 @@ package org.java_websocket.util; +import java.nio.ByteBuffer; import org.java_websocket.exceptions.InvalidDataException; import org.junit.Assert; import org.junit.Test; -import java.nio.ByteBuffer; - public class CharsetfunctionsTest { @Test diff --git a/src/test/java/org/java_websocket/util/SSLContextUtil.java b/src/test/java/org/java_websocket/util/SSLContextUtil.java index e8d45b6fb..87b20ecb1 100644 --- a/src/test/java/org/java_websocket/util/SSLContextUtil.java +++ b/src/test/java/org/java_websocket/util/SSLContextUtil.java @@ -26,15 +26,19 @@ package org.java_websocket.util; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManagerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Paths; -import java.security.*; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; public class SSLContextUtil { diff --git a/src/test/java/org/java_websocket/util/ThreadCheck.java b/src/test/java/org/java_websocket/util/ThreadCheck.java index 6ee37348d..449a2b69d 100644 --- a/src/test/java/org/java_websocket/util/ThreadCheck.java +++ b/src/test/java/org/java_websocket/util/ThreadCheck.java @@ -28,7 +28,6 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.LockSupport; - import org.junit.Assert; import org.junit.rules.ExternalResource; From a797dfb6519a8eb34ceb260ec14b0a39a03f315b Mon Sep 17 00:00:00 2001 From: dota17 Date: Thu, 13 Aug 2020 21:08:28 +0800 Subject: [PATCH 072/165] adjust indent --- .github/workflows/ci.yml | 30 +++++++++++++++--------------- build.gradle | 2 +- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 544d474cd..7c81f7ff0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,21 +6,21 @@ jobs: Build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 - with: - java-version: 1.8 - - name: Build - run: mvn -DskipTests package --file pom.xml - + - uses: actions/checkout@v1 + - name: Set up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: Build + run: mvn -DskipTests package --file pom.xml + Test: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 - with: - java-version: 1.8 - - name: Test - run: mvn test --file pom.xml + - uses: actions/checkout@v1 + - name: Set up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: Test + run: mvn test --file pom.xml diff --git a/build.gradle b/build.gradle index 7a1a0108f..e18733fae 100644 --- a/build.gradle +++ b/build.gradle @@ -24,7 +24,7 @@ configure(install.repositories.mavenInstaller) { } dependencies { - deployerJars "org.apache.maven.wagon:wagon-webdav:1.0-beta-2" + deployerJars "org.apache.maven.wagon:wagon-webdav:1.0-beta-2" compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25' testCompile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25' testCompile group: 'junit', name: 'junit', version: '4.12' From b04a5adfb58a6f46d6313a7a26dee1f9ce0eeef9 Mon Sep 17 00:00:00 2001 From: dota17 Date: Fri, 14 Aug 2020 11:51:40 +0800 Subject: [PATCH 073/165] optimize code and remove empty line --- .../PerMessageDeflateExtension.java | 2 +- .../java_websocket/util/Charsetfunctions.java | 24 ++++--------------- .../java_websocket/issues/Issue997Test.java | 2 -- 3 files changed, 6 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index 41f4bbb72..40a74b797 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -196,7 +196,7 @@ public void encodeFrame(Framedata inputFrame) { output.write(buffer, 0, bytesCompressed); } - byte outputBytes[] = output.toByteArray(); + byte[] outputBytes = output.toByteArray(); int outputLength = outputBytes.length; /* diff --git a/src/main/java/org/java_websocket/util/Charsetfunctions.java b/src/main/java/org/java_websocket/util/Charsetfunctions.java index 78fd8b552..0cea88ec4 100644 --- a/src/main/java/org/java_websocket/util/Charsetfunctions.java +++ b/src/main/java/org/java_websocket/util/Charsetfunctions.java @@ -25,14 +25,12 @@ package org.java_websocket.util; -import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; import org.java_websocket.exceptions.InvalidDataException; -import org.java_websocket.exceptions.InvalidEncodingException; import org.java_websocket.framing.CloseFrame; public class Charsetfunctions { @@ -49,22 +47,14 @@ private Charsetfunctions() { * @return UTF-8 encoding in bytes */ public static byte[] utf8Bytes(String s) { - try { - return s.getBytes("UTF8"); - } catch (UnsupportedEncodingException e) { - throw new InvalidEncodingException(e); - } + return s.getBytes(StandardCharsets.UTF_8); } /* * @return ASCII encoding in bytes */ public static byte[] asciiBytes(String s) { - try { - return s.getBytes("ASCII"); - } catch (UnsupportedEncodingException e) { - throw new InvalidEncodingException(e); - } + return s.getBytes(StandardCharsets.US_ASCII); } public static String stringAscii(byte[] bytes) { @@ -72,11 +62,7 @@ public static String stringAscii(byte[] bytes) { } public static String stringAscii(byte[] bytes, int offset, int length) { - try { - return new String(bytes, offset, length, "ASCII"); - } catch (UnsupportedEncodingException e) { - throw new InvalidEncodingException(e); - } + return new String(bytes, offset, length, StandardCharsets.US_ASCII); } public static String stringUtf8(byte[] bytes) throws InvalidDataException { @@ -84,7 +70,7 @@ public static String stringUtf8(byte[] bytes) throws InvalidDataException { } public static String stringUtf8(ByteBuffer bytes) throws InvalidDataException { - CharsetDecoder decode = Charset.forName("UTF8").newDecoder(); + CharsetDecoder decode = StandardCharsets.UTF_8.newDecoder(); decode.onMalformedInput(codingErrorAction); decode.onUnmappableCharacter(codingErrorAction); String s; diff --git a/src/test/java/org/java_websocket/issues/Issue997Test.java b/src/test/java/org/java_websocket/issues/Issue997Test.java index 3c3b80641..be227cef7 100644 --- a/src/test/java/org/java_websocket/issues/Issue997Test.java +++ b/src/test/java/org/java_websocket/issues/Issue997Test.java @@ -175,8 +175,6 @@ protected void onSetSSLParameters(SSLParameters sslParameters) { } - ; - private static class SSLWebSocketServer extends WebSocketServer { From b727da4b82adcfcd1a5f0c843b837cb538979718 Mon Sep 17 00:00:00 2001 From: dota17 Date: Fri, 14 Aug 2020 11:20:03 +0800 Subject: [PATCH 074/165] add checkstyle.xml, update pom.xml to use maven checkstyle plugin --- checkstyle-suppressions.xml | 10 ++++++++++ pom.xml | 22 ++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 checkstyle-suppressions.xml diff --git a/checkstyle-suppressions.xml b/checkstyle-suppressions.xml new file mode 100644 index 000000000..fae46ec02 --- /dev/null +++ b/checkstyle-suppressions.xml @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 70999a245..bc1ff18b3 100644 --- a/pom.xml +++ b/pom.xml @@ -19,6 +19,7 @@ 4.3.1 + 3.1.1 3.7.0 1.6 3.0.2 @@ -174,6 +175,27 @@ org.apache.maven.plugins maven-compiler-plugin + + org.apache.maven.plugins + maven-checkstyle-plugin + ${maven.checkstyle.plugin.version} + + google_checks.xml + checkstyle-suppressions.xml + checkstyle.suppressions.file + true + true + + + + validate + validate + + check + + + + From 183234658cbf6ace467e5af53f03f6b0307c7a3c Mon Sep 17 00:00:00 2001 From: dota17 Date: Sat, 15 Aug 2020 10:47:54 +0800 Subject: [PATCH 075/165] cleanup code --- checkstyle-suppressions.xml | 4 + .../org/java_websocket/SSLSocketChannel2.java | 18 +- .../java_websocket/SocketChannelIOHelper.java | 2 +- .../client/WebSocketClient.java | 2 +- .../org/java_websocket/drafts/Draft_6455.java | 15 +- .../PerMessageDeflateExtension.java | 28 +-- .../java/org/java_websocket/util/Base64.java | 182 +++++++++--------- 7 files changed, 128 insertions(+), 123 deletions(-) diff --git a/checkstyle-suppressions.xml b/checkstyle-suppressions.xml index fae46ec02..abfbc7857 100644 --- a/checkstyle-suppressions.xml +++ b/checkstyle-suppressions.xml @@ -7,4 +7,8 @@ + + + + \ No newline at end of file diff --git a/src/main/java/org/java_websocket/SSLSocketChannel2.java b/src/main/java/org/java_websocket/SSLSocketChannel2.java index 983d64c34..d9b9a4c31 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel2.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel2.java @@ -22,6 +22,7 @@ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ + package org.java_websocket; import java.io.EOFException; @@ -275,10 +276,10 @@ public int write(ByteBuffer src) throws IOException { processHandshake(); return 0; } - // assert ( bufferallocations > 1 ); //see #190 - //if( bufferallocations <= 1 ) { - // createBuffers( sslEngine.getSession() ); - //} + // assert(bufferallocations > 1); // see #190 + // if(bufferallocations <= 1) { + // createBuffers(sslEngine.getSession()); + // } int num = socketChannel.write(wrap(src)); if (writeEngineResult.getStatus() == SSLEngineResult.Status.CLOSED) { throw new EOFException("Connection is closed"); @@ -311,10 +312,11 @@ public int read(ByteBuffer dst) throws IOException { } } } - // assert ( bufferallocations > 1 ); //see #190 - //if( bufferallocations <= 1 ) { - // createBuffers( sslEngine.getSession() ); - //} + // assert(bufferallocations > 1); // see #190 + // if (bufferallocations <= 1) { + // createBuffers(sslEngine.getSession()); + // } + /* 1. When "dst" is smaller than "inData" readRemaining will fill "dst" with data decoded in a previous read call. * 2. When "inCrypt" contains more data than "inData" has remaining space, unwrap has to be called on more time(readRemaining) */ diff --git a/src/main/java/org/java_websocket/SocketChannelIOHelper.java b/src/main/java/org/java_websocket/SocketChannelIOHelper.java index 987ce4093..2d919344a 100644 --- a/src/main/java/org/java_websocket/SocketChannelIOHelper.java +++ b/src/main/java/org/java_websocket/SocketChannelIOHelper.java @@ -107,7 +107,7 @@ public static boolean batch(WebSocketImpl ws, ByteChannel sockchannel) throws IO } if (ws.outQueue.isEmpty() && ws.isFlushAndClose() && ws.getDraft() != null - && ws.getDraft().getRole() != null && ws.getDraft().getRole() == Role.SERVER) {// + && ws.getDraft().getRole() != null && ws.getDraft().getRole() == Role.SERVER) { ws.closeConnection(); } return c == null || !((WrappedByteChannel) sockchannel).isNeedWrite(); diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 8ab3684b8..992eb9670 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -498,7 +498,7 @@ public void run() { ostream = socket.getOutputStream(); sendHandshake(); - } catch ( /*IOException | SecurityException | UnresolvedAddressException | InvalidHandshakeException | ClosedByInterruptException | SocketTimeoutException */Exception e) { + } catch (/*IOException | SecurityException | UnresolvedAddressException | InvalidHandshakeException | ClosedByInterruptException | SocketTimeoutException */Exception e) { onWebsocketError(engine, e); engine.closeConnection(CloseFrame.NEVER_CONNECTED, e.getMessage()); return; diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index e81ebe4fa..35660f713 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -522,12 +522,12 @@ private Framedata translateSingleFrame(ByteBuffer buffer) int maxpacketsize = buffer.remaining(); int realpacketsize = 2; translateSingleFrameCheckPacketSize(maxpacketsize, realpacketsize); - byte b1 = buffer.get( /*0*/); + byte b1 = buffer.get(/*0*/); boolean fin = b1 >> 8 != 0; boolean rsv1 = (b1 & 0x40) != 0; boolean rsv2 = (b1 & 0x20) != 0; boolean rsv3 = (b1 & 0x10) != 0; - byte b2 = buffer.get( /*1*/); + byte b2 = buffer.get(/*1*/); boolean mask = (b2 & -128) != 0; int payloadlength = (byte) (b2 & ~(byte) 128); Opcode optcode = toOpcode((byte) (b1 & 15)); @@ -548,7 +548,7 @@ private Framedata translateSingleFrame(ByteBuffer buffer) byte[] maskskey = new byte[4]; buffer.get(maskskey); for (int i = 0; i < payloadlength; i++) { - payload.put((byte) (buffer.get( /*payloadstart + i*/) ^ maskskey[i % 4])); + payload.put((byte) (buffer.get(/*payloadstart + i*/) ^ maskskey[i % 4])); } } else { payload.put(buffer.array(), buffer.position(), payload.limit()); @@ -599,15 +599,15 @@ private TranslatedPayloadMetaData translateSingleFramePayloadLength(ByteBuffer b realpacketsize += 2; // additional length bytes translateSingleFrameCheckPacketSize(maxpacketsize, realpacketsize); byte[] sizebytes = new byte[3]; - sizebytes[1] = buffer.get( /*1 + 1*/); - sizebytes[2] = buffer.get( /*1 + 2*/); + sizebytes[1] = buffer.get(/*1 + 1*/); + sizebytes[2] = buffer.get(/*1 + 2*/); payloadlength = new BigInteger(sizebytes).intValue(); } else { realpacketsize += 8; // additional length bytes translateSingleFrameCheckPacketSize(maxpacketsize, realpacketsize); byte[] bytes = new byte[8]; for (int i = 0; i < 8; i++) { - bytes[i] = buffer.get( /*1 + i*/); + bytes[i] = buffer.get(/*1 + i*/); } long length = new BigInteger(bytes).longValue(); translateSingleFrameCheckLengthLimit(length); @@ -735,7 +735,8 @@ public List translateFrame(ByteBuffer buffer) throws InvalidDataExcep } } - while (buffer.hasRemaining()) {// Read as much as possible full frames + // Read as much as possible full frames + while (buffer.hasRemaining()) { buffer.mark(); try { cur = translateSingleFrame(buffer); diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index 40a74b797..c0346b88b 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -123,14 +123,14 @@ public void decodeFrame(Framedata inputFrame) throws InvalidDataException { try { decompress(inputFrame.getPayloadData().array(), output); - /* - If a message is "first fragmented and then compressed", as this project does, then the inflater - can not inflate fragments except the first one. - This behavior occurs most likely because those fragments end with "final deflate blocks". - We can check the getRemaining() method to see whether the data we supplied has been decompressed or not. - And if not, we just reset the inflater and decompress again. - Note that this behavior doesn't occur if the message is "first compressed and then fragmented". - */ + /* + If a message is "first fragmented and then compressed", as this project does, then the inflater + can not inflate fragments except the first one. + This behavior occurs most likely because those fragments end with "final deflate blocks". + We can check the getRemaining() method to see whether the data we supplied has been decompressed or not. + And if not, we just reset the inflater and decompress again. + Note that this behavior doesn't occur if the message is "first compressed and then fragmented". + */ if (inflater.getRemaining() > 0) { inflater = new Inflater(true); decompress(inputFrame.getPayloadData().array(), output); @@ -199,12 +199,12 @@ public void encodeFrame(Framedata inputFrame) { byte[] outputBytes = output.toByteArray(); int outputLength = outputBytes.length; - /* - https://tools.ietf.org/html/rfc7692#section-7.2.1 states that if the final fragment's compressed - payload ends with 0x00 0x00 0xff 0xff, they should be removed. - To simulate removal, we just pass 4 bytes less to the new payload - if the frame is final and outputBytes ends with 0x00 0x00 0xff 0xff. - */ + /* + https://tools.ietf.org/html/rfc7692#section-7.2.1 states that if the final fragment's compressed + payload ends with 0x00 0x00 0xff 0xff, they should be removed. + To simulate removal, we just pass 4 bytes less to the new payload + if the frame is final and outputBytes ends with 0x00 0x00 0xff 0xff. + */ if (inputFrame.isFin()) { if (endsWithTail(outputBytes)) { outputLength -= TAIL_BYTES.length; diff --git a/src/main/java/org/java_websocket/util/Base64.java b/src/main/java/org/java_websocket/util/Base64.java index 175016327..1a39e9c9e 100644 --- a/src/main/java/org/java_websocket/util/Base64.java +++ b/src/main/java/org/java_websocket/util/Base64.java @@ -177,22 +177,22 @@ public class Base64 { /** * No options specified. Value is zero. */ - public final static int NO_OPTIONS = 0; + public static final int NO_OPTIONS = 0; /** * Specify encoding in first bit. Value is one. */ - public final static int ENCODE = 1; + public static final int ENCODE = 1; /** * Specify that data should be gzip-compressed in second bit. Value is two. */ - public final static int GZIP = 2; + public static final int GZIP = 2; /** * Do break lines when encoding. Value is 8. */ - public final static int DO_BREAK_LINES = 8; + public static final int DO_BREAK_LINES = 8; /** * Encode using Base64-like encoding that is URL- and Filename-safe as described in Section 4 of @@ -202,14 +202,14 @@ public class Base64 { * at the very least should not be called Base64 without also specifying that is was encoded using * the URL- and Filename-safe dialect. */ - public final static int URL_SAFE = 16; + public static final int URL_SAFE = 16; /** * Encode using the special "ordered" dialect of Base64 described here: * http://www.faqs.org/qa/rfcc-1940.html. */ - public final static int ORDERED = 32; + public static final int ORDERED = 32; /* ******** P R I V A T E F I E L D S ******** */ @@ -218,28 +218,28 @@ public class Base64 { /** * Maximum line length (76) of Base64 output. */ - private final static int MAX_LINE_LENGTH = 76; + private static final int MAX_LINE_LENGTH = 76; /** * The equals sign (=) as a byte. */ - private final static byte EQUALS_SIGN = (byte) '='; + private static final byte EQUALS_SIGN = (byte) '='; /** * The new line character (\n) as a byte. */ - private final static byte NEW_LINE = (byte) '\n'; + private static final byte NEW_LINE = (byte) '\n'; /** * Preferred encoding. */ - private final static String PREFERRED_ENCODING = "US-ASCII"; + private static final String PREFERRED_ENCODING = "US-ASCII"; - private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding + private static final byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ @@ -248,7 +248,7 @@ public class Base64 { * The 64 valid Base64 values. */ /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ - private final static byte[] _STANDARD_ALPHABET = { + private static final byte[] _STANDARD_ALPHABET = { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', @@ -266,29 +266,29 @@ public class Base64 { * Translates a Base64 value to either its 6-bit reconstruction value or a negative number * indicating some other meaning. **/ - private final static byte[] _STANDARD_DECODABET = { - -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 - -5, -5, // Whitespace: Tab and Linefeed - -9, -9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return + private static final byte[] _STANDARD_DECODABET = { + -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 + -5, -5, // Whitespace: Tab and Linefeed + -9, -9, // Decimal 11 - 12 + -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 - -9, -9, -9, -9, -9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 - 62, // Plus sign at decimal 43 - -9, -9, -9, // Decimal 44 - 46 - 63, // Slash at decimal 47 - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine - -9, -9, -9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9, -9, -9, // Decimal 62 - 64 - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' - -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 + -9, -9, -9, -9, -9, // Decimal 27 - 31 + -5, // Whitespace: Space + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 + 62, // Plus sign at decimal 43 + -9, -9, -9, // Decimal 44 - 46 + 63, // Slash at decimal 47 + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine + -9, -9, -9, // Decimal 58 - 60 + -1, // Equals sign at decimal 61 + -9, -9, -9, // Decimal 62 - 64 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' + -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' - -9, -9, -9, -9, -9 // Decimal 123 - 127 - , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 + -9, -9, -9, -9, -9, // Decimal 123 - 127 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 @@ -297,7 +297,7 @@ public class Base64 { -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 }; @@ -308,7 +308,7 @@ public class Base64 { * http://www.faqs.org/rfcs/rfc3548.html. * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." */ - private final static byte[] _URL_SAFE_ALPHABET = { + private static final byte[] _URL_SAFE_ALPHABET = { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', @@ -324,33 +324,33 @@ public class Base64 { /** * Used in decoding URL- and Filename-safe dialects of Base64. */ - private final static byte[] _URL_SAFE_DECODABET = { - -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 - -5, -5, // Whitespace: Tab and Linefeed - -9, -9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return + private static final byte[] _URL_SAFE_DECODABET = { + -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 + -5, -5, // Whitespace: Tab and Linefeed + -9, -9, // Decimal 11 - 12 + -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 - -9, -9, -9, -9, -9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 - -9, // Plus sign at decimal 43 - -9, // Decimal 44 - 62, // Minus sign at decimal 45 - -9, // Decimal 46 - -9, // Slash at decimal 47 - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine - -9, -9, -9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9, -9, -9, // Decimal 62 - 64 - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' - -9, -9, -9, -9, // Decimal 91 - 94 - 63, // Underscore at decimal 95 - -9, // Decimal 96 + -9, -9, -9, -9, -9, // Decimal 27 - 31 + -5, // Whitespace: Space + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 + -9, // Plus sign at decimal 43 + -9, // Decimal 44 + 62, // Minus sign at decimal 45 + -9, // Decimal 46 + -9, // Slash at decimal 47 + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine + -9, -9, -9, // Decimal 58 - 60 + -1, // Equals sign at decimal 61 + -9, -9, -9, // Decimal 62 - 64 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' + -9, -9, -9, -9, // Decimal 91 - 94 + 63, // Underscore at decimal 95 + -9, // Decimal 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' - -9, -9, -9, -9, -9 // Decimal 123 - 127 - , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 + -9, -9, -9, -9, -9, // Decimal 123 - 127 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 @@ -359,7 +359,7 @@ public class Base64 { -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 }; @@ -370,7 +370,7 @@ public class Base64 { * I don't get the point of this technique, but someone requested it, and it is described here: * http://www.faqs.org/qa/rfcc-1940.html. */ - private final static byte[] _ORDERED_ALPHABET = { + private static final byte[] _ORDERED_ALPHABET = { (byte) '-', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', @@ -388,33 +388,33 @@ public class Base64 { /** * Used in decoding the "ordered" dialect of Base64. */ - private final static byte[] _ORDERED_DECODABET = { - -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 - -5, -5, // Whitespace: Tab and Linefeed - -9, -9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return + private static final byte[] _ORDERED_DECODABET = { + -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 + -5, -5, // Whitespace: Tab and Linefeed + -9, -9, // Decimal 11 - 12 + -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 - -9, -9, -9, -9, -9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 - -9, // Plus sign at decimal 43 - -9, // Decimal 44 - 0, // Minus sign at decimal 45 - -9, // Decimal 46 - -9, // Slash at decimal 47 - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Numbers zero through nine - -9, -9, -9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9, -9, -9, // Decimal 62 - 64 + -9, -9, -9, -9, -9, // Decimal 27 - 31 + -5, // Whitespace: Space + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 + -9, // Plus sign at decimal 43 + -9, // Decimal 44 + 0, // Minus sign at decimal 45 + -9, // Decimal 46 + -9, // Slash at decimal 47 + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Numbers zero through nine + -9, -9, -9, // Decimal 58 - 60 + -1, // Equals sign at decimal 61 + -9, -9, -9, // Decimal 62 - 64 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, // Letters 'A' through 'M' 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, // Letters 'N' through 'Z' - -9, -9, -9, -9, // Decimal 91 - 94 - 37, // Underscore at decimal 95 - -9, // Decimal 96 + -9, -9, -9, -9, // Decimal 91 - 94 + 37, // Underscore at decimal 95 + -9, // Decimal 96 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, // Letters 'a' through 'm' 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // Letters 'n' through 'z' - -9, -9, -9, -9, -9 // Decimal 123 - 127 - , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 + -9, -9, -9, -9, -9, // Decimal 123 - 127 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 @@ -423,7 +423,7 @@ public class Base64 { -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 }; @@ -435,7 +435,7 @@ public class Base64 { * possible, though silly, to specify ORDERED and URLSAFE in which case one of them will be * picked, though there is no guarantee as to which one will be picked. */ - private final static byte[] getAlphabet(int options) { + private static final byte[] getAlphabet(int options) { if ((options & URL_SAFE) == URL_SAFE) { return _URL_SAFE_ALPHABET; } else if ((options & ORDERED) == ORDERED) { @@ -451,7 +451,7 @@ private final static byte[] getAlphabet(int options) { * possible, though silly, to specify ORDERED and URL_SAFE in which case one of them will be * picked, though there is no guarantee as to which one will be picked. */ - private final static byte[] getDecodabet(int options) { + private static final byte[] getDecodabet(int options) { if ((options & URL_SAFE) == URL_SAFE) { return _URL_SAFE_DECODABET; } else if ((options & ORDERED) == ORDERED) { @@ -622,8 +622,7 @@ public static String encodeBytes(byte[] source, int off, int len, int options) // Return value according to relevant encoding. try { return new String(encoded, PREFERRED_ENCODING); - } // end try - catch (java.io.UnsupportedEncodingException uue) { + } catch (java.io.UnsupportedEncodingException uue) { return new String(encoded); } // end catch @@ -682,13 +681,11 @@ public static byte[] encodeBytesToBytes(byte[] source, int off, int len, int opt gzos.write(source, off, len); gzos.close(); - } // end try - catch (java.io.IOException e) { + } catch (java.io.IOException e) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; - } // end catch - finally { + } finally { try { if (gzos != null) { gzos.close(); @@ -720,6 +717,7 @@ public static byte[] encodeBytesToBytes(byte[] source, int off, int len, int opt //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines + // Try to determine more precisely how big the array needs to be. // If we get it right, we don't have to do an array copy, and // we save a bunch of memory. @@ -742,7 +740,7 @@ public static byte[] encodeBytesToBytes(byte[] source, int off, int len, int opt e++; lineLength = 0; } // end if: end of line - } // en dfor: each piece of array + } // end for: each piece of array if (d < len) { encode3to4(source, d + off, len - d, outBuff, e, options); From 9f2e3f4542059e964e9f74a7e1e3d194a0fff744 Mon Sep 17 00:00:00 2001 From: dota17 <50514813+dota17@users.noreply.github.com> Date: Tue, 25 Aug 2020 16:32:30 +0800 Subject: [PATCH 076/165] add workflow to check code style and modify violationSeverity --- .github/workflows/checkstyle.yml | 20 ++++++++++++++++++++ pom.xml | 3 ++- 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/checkstyle.yml diff --git a/.github/workflows/checkstyle.yml b/.github/workflows/checkstyle.yml new file mode 100644 index 000000000..18827fd61 --- /dev/null +++ b/.github/workflows/checkstyle.yml @@ -0,0 +1,20 @@ +# This workflow will build a Java project with Maven +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven + +name: Java Code Style Check with Maven + +on: [push] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: Code Style Check + run: mvn -B validate --file pom.xml diff --git a/pom.xml b/pom.xml index bc1ff18b3..529bc45e7 100644 --- a/pom.xml +++ b/pom.xml @@ -181,10 +181,11 @@ ${maven.checkstyle.plugin.version} google_checks.xml + warning checkstyle-suppressions.xml checkstyle.suppressions.file true - true + false From a29d16663d2a2f59b316571ea1a804ae22d6f183 Mon Sep 17 00:00:00 2001 From: dota17 <50514813+dota17@users.noreply.github.com> Date: Tue, 25 Aug 2020 16:53:14 +0800 Subject: [PATCH 077/165] remove the phase of checksytle --- .github/workflows/checkstyle.yml | 2 +- pom.xml | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/checkstyle.yml b/.github/workflows/checkstyle.yml index 18827fd61..589829fa9 100644 --- a/.github/workflows/checkstyle.yml +++ b/.github/workflows/checkstyle.yml @@ -17,4 +17,4 @@ jobs: with: java-version: 1.8 - name: Code Style Check - run: mvn -B validate --file pom.xml + run: mvn -B checkstyle:check --file pom.xml diff --git a/pom.xml b/pom.xml index 529bc45e7..99f5c2701 100644 --- a/pom.xml +++ b/pom.xml @@ -189,8 +189,7 @@ - validate - validate + check check From b8e95f989d1eb151cc04723be6d6b738aafc8e40 Mon Sep 17 00:00:00 2001 From: dota17 <50514813+dota17@users.noreply.github.com> Date: Tue, 25 Aug 2020 17:07:14 +0800 Subject: [PATCH 078/165] add event - pull_request --- .github/workflows/checkstyle.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/checkstyle.yml b/.github/workflows/checkstyle.yml index 589829fa9..8b74e7db5 100644 --- a/.github/workflows/checkstyle.yml +++ b/.github/workflows/checkstyle.yml @@ -3,7 +3,7 @@ name: Java Code Style Check with Maven -on: [push] +on: [push, pull_request] jobs: build: From 9518c2a80037c90dd9a46296db89eea2dc38951f Mon Sep 17 00:00:00 2001 From: dota17 Date: Sat, 29 Aug 2020 11:17:20 +0800 Subject: [PATCH 079/165] update suppressions and cleanup code --- checkstyle-suppressions.xml | 5 ++- .../java_websocket/SocketChannelIOHelper.java | 3 +- .../org/java_websocket/WebSocketImpl.java | 5 ++- .../org/java_websocket/drafts/Draft_6455.java | 12 +++---- .../server/WebSocketServer.java | 34 +++++++++---------- 5 files changed, 31 insertions(+), 28 deletions(-) diff --git a/checkstyle-suppressions.xml b/checkstyle-suppressions.xml index abfbc7857..25cfc5a9d 100644 --- a/checkstyle-suppressions.xml +++ b/checkstyle-suppressions.xml @@ -11,4 +11,7 @@ - \ No newline at end of file + + + + diff --git a/src/main/java/org/java_websocket/SocketChannelIOHelper.java b/src/main/java/org/java_websocket/SocketChannelIOHelper.java index 2d919344a..9a6cfbc51 100644 --- a/src/main/java/org/java_websocket/SocketChannelIOHelper.java +++ b/src/main/java/org/java_websocket/SocketChannelIOHelper.java @@ -94,7 +94,8 @@ public static boolean batch(WebSocketImpl ws, ByteChannel sockchannel) throws IO } } } else { - do {// FIXME writing as much as possible is unfair!! + do { + // FIXME writing as much as possible is unfair!! /*int written = */ sockchannel.write(buffer); if (buffer.remaining() > 0) { diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index 9832ee316..2fc312e64 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -204,9 +204,8 @@ public WebSocketImpl(WebSocketListener listener, List drafts) { * @param draft The draft which should be used */ public WebSocketImpl(WebSocketListener listener, Draft draft) { - if (listener == null || (draft == null && role - == Role.SERVER))// socket can be null because we want do be able to create the object without already having a bound channel - { + // socket can be null because we want do be able to create the object without already having a bound channel + if (listener == null || (draft == null && role == Role.SERVER)) { throw new IllegalArgumentException("parameters must not be null"); } this.outQueue = new LinkedBlockingQueue(); diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index 35660f713..7b4743f8a 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -443,12 +443,12 @@ public HandshakeBuilder postProcessHandshakeResponseAsServer(ClientHandshake req @Override public Draft copyInstance() { ArrayList newExtensions = new ArrayList(); - for (IExtension iExtension : getKnownExtensions()) { - newExtensions.add(iExtension.copyInstance()); + for (IExtension extension : getKnownExtensions()) { + newExtensions.add(extension.copyInstance()); } ArrayList newProtocols = new ArrayList(); - for (IProtocol iProtocol : getKnownProtocols()) { - newProtocols.add(iProtocol.copyInstance()); + for (IProtocol protocol : getKnownProtocols()) { + newProtocols.add(protocol.copyInstance()); } return new Draft_6455(newExtensions, newProtocols, maxFrameSize); } @@ -589,8 +589,8 @@ private Framedata translateSingleFrame(ByteBuffer buffer) private TranslatedPayloadMetaData translateSingleFramePayloadLength(ByteBuffer buffer, Opcode optcode, int oldPayloadlength, int maxpacketsize, int oldRealpacketsize) throws InvalidFrameException, IncompleteException, LimitExceededException { - int payloadlength = oldPayloadlength, - realpacketsize = oldRealpacketsize; + int payloadlength = oldPayloadlength; + int realpacketsize = oldRealpacketsize; if (optcode == Opcode.PING || optcode == Opcode.PONG || optcode == Opcode.CLOSING) { log.trace("Invalid frame: more than 125 octets"); throw new InvalidFrameException("more than 125 octets"); diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index b55ed3b7c..71f8728ba 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -361,9 +361,9 @@ public void run() { return; } try { - int iShutdownCount = 5; + int shutdownCount = 5; int selectTimeout = 0; - while (!selectorthread.isInterrupted() && iShutdownCount != 0) { + while (!selectorthread.isInterrupted() && shutdownCount != 0) { SelectionKey key = null; try { if (isclosed.get()) { @@ -371,7 +371,7 @@ public void run() { } int keyCount = selector.select(selectTimeout); if (keyCount == 0 && isclosed.get()) { - iShutdownCount--; + shutdownCount--; } Set keys = selector.selectedKeys(); Iterator i = keys.iterator(); @@ -993,15 +993,15 @@ public void broadcast(String text, Collection clients) { * @param clients the clients to send the message to */ private void doBroadcast(Object data, Collection clients) { - String sData = null; + String strData = null; if (data instanceof String) { - sData = (String) data; + strData = (String) data; } - ByteBuffer bData = null; + ByteBuffer byteData = null; if (data instanceof ByteBuffer) { - bData = (ByteBuffer) data; + byteData = (ByteBuffer) data; } - if (sData == null && bData == null) { + if (strData == null && byteData == null) { return; } Map> draftFrames = new HashMap>(); @@ -1012,7 +1012,7 @@ private void doBroadcast(Object data, Collection clients) { for (WebSocket client : clientCopy) { if (client != null) { Draft draft = client.getDraft(); - fillFrames(draft, draftFrames, sData, bData); + fillFrames(draft, draftFrames, strData, byteData); try { client.sendFrame(draftFrames.get(draft)); } catch (WebsocketNotConnectedException e) { @@ -1027,18 +1027,18 @@ private void doBroadcast(Object data, Collection clients) { * * @param draft The draft to use * @param draftFrames The list of frames per draft to fill - * @param sData the string data, can be null - * @param bData the byte buffer data, can be null + * @param strData the string data, can be null + * @param byteData the byte buffer data, can be null */ - private void fillFrames(Draft draft, Map> draftFrames, String sData, - ByteBuffer bData) { + private void fillFrames(Draft draft, Map> draftFrames, String strData, + ByteBuffer byteData) { if (!draftFrames.containsKey(draft)) { List frames = null; - if (sData != null) { - frames = draft.createFrames(sData, false); + if (strData != null) { + frames = draft.createFrames(strData, false); } - if (bData != null) { - frames = draft.createFrames(bData, false); + if (byteData != null) { + frames = draft.createFrames(byteData, false); } if (frames != null) { draftFrames.put(draft, frames); From d06cff20b6e18fd42f3b3ef154e7b9a72200f4e8 Mon Sep 17 00:00:00 2001 From: dota17 Date: Sat, 29 Aug 2020 11:20:51 +0800 Subject: [PATCH 080/165] update code : change if to switch case --- .../org/java_websocket/drafts/Draft_6455.java | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index 7b4743f8a..f7e59fc41 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -660,19 +660,16 @@ private void translateSingleFrameCheckPacketSize(int maxpacketsize, int realpack * @return byte that represents which RSV bit is set. */ private byte getRSVByte(int rsv) { - if (rsv == 1) // 0100 0000 - { - return 0x40; - } - if (rsv == 2) // 0010 0000 - { - return 0x20; - } - if (rsv == 3) // 0001 0000 - { - return 0x10; + switch (rsv) { + case 1 : // 0100 0000 + return 0x40; + case 2 : // 0010 0000 + return 0x20; + case 3 : // 0001 0000 + return 0x10; + default: + return 0; } - return 0; } /** From d649f4b337f17fa17f0b9ead9fc4aa0ecaae514b Mon Sep 17 00:00:00 2001 From: dota17 Date: Sat, 29 Aug 2020 11:41:45 +0800 Subject: [PATCH 081/165] update Base64.java : cleanup code, fix EmptyCatchBlock and LocalVariableName --- src/main/java/org/java_websocket/util/Base64.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/java_websocket/util/Base64.java b/src/main/java/org/java_websocket/util/Base64.java index 1a39e9c9e..e9ff7b87a 100644 --- a/src/main/java/org/java_websocket/util/Base64.java +++ b/src/main/java/org/java_websocket/util/Base64.java @@ -517,7 +517,7 @@ private static byte[] encode3to4( byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, int options) { - byte[] ALPHABET = getAlphabet(options); + final byte[] ALPHABET = getAlphabet(options); // 1 2 3 // 01234567890123456789012345678901 Bit position @@ -691,18 +691,21 @@ public static byte[] encodeBytesToBytes(byte[] source, int off, int len, int opt gzos.close(); } } catch (Exception e) { + // do nothing } try { if (b64os != null) { b64os.close(); } } catch (Exception e) { + // do nothing } try { if (baos != null) { baos.close(); } } catch (Exception e) { + // do nothing } } // end finally @@ -818,7 +821,7 @@ private static int decode4to3( destination.length, destOffset)); } // end if - byte[] DECODABET = getDecodabet(options); + final byte[] DECODABET = getDecodabet(options); // Example: Dk== if (source[srcOffset + 2] == EQUALS_SIGN) { From b0baf6cd4f6801d14e22e9665a4ceaf27880f50a Mon Sep 17 00:00:00 2001 From: dota17 Date: Sat, 29 Aug 2020 11:48:08 +0800 Subject: [PATCH 082/165] update suppressions : Ignore RightCurly for Base64.java, original is great --- checkstyle-suppressions.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/checkstyle-suppressions.xml b/checkstyle-suppressions.xml index 25cfc5a9d..afa6e1544 100644 --- a/checkstyle-suppressions.xml +++ b/checkstyle-suppressions.xml @@ -14,4 +14,5 @@ + From 48cbb46eb86153e21a008a3fc9c814809d8a6e81 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sat, 19 Sep 2020 13:15:05 +0200 Subject: [PATCH 083/165] Prioritise using provided socket factory when creating socket with proxy #1058 --- .../client/WebSocketClient.java | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 992eb9670..fa1bfb3b4 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -461,12 +461,16 @@ public void sendPing() { public void run() { InputStream istream; try { - boolean isNewSocket = false; - if (socketFactory != null) { + boolean upgradeSocketToSSLSocket = false; + // Prioritise a proxy over a socket factory and apply the socketfactory later + if (proxy != Proxy.NO_PROXY) { + socket = new Socket(proxy); + upgradeSocketToSSLSocket = true; + } else if (socketFactory != null) { socket = socketFactory.createSocket(); } else if (socket == null) { socket = new Socket(proxy); - isNewSocket = true; + upgradeSocketToSSLSocket = true; } else if (socket.isClosed()) { throw new IOException(); } @@ -480,10 +484,17 @@ public void run() { } // if the socket is set by others we don't apply any TLS wrapper - if (isNewSocket && "wss".equals(uri.getScheme())) { - SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); - sslContext.init(null, null, null); - SSLSocketFactory factory = sslContext.getSocketFactory(); + if (upgradeSocketToSSLSocket && "wss".equals(uri.getScheme())) { + SSLSocketFactory factory = null; + // Prioritise the provided socketfactory + // Helps when using web debuggers like Fiddler Classic + if (socketFactory != null && (socketFactory instanceof SSLSocketFactory)) { + factory = (SSLSocketFactory) socketFactory; + } else { + SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); + sslContext.init(null, null, null); + factory = sslContext.getSocketFactory(); + } socket = factory.createSocket(socket, uri.getHost(), getPort(), true); } From 2f56b70f976315557896eff15143a97f30457c0f Mon Sep 17 00:00:00 2001 From: marci4 Date: Sat, 19 Sep 2020 13:22:12 +0200 Subject: [PATCH 084/165] Fix formatting --- src/main/java/org/java_websocket/client/WebSocketClient.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index fa1bfb3b4..f28fd6304 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -488,8 +488,8 @@ public void run() { SSLSocketFactory factory = null; // Prioritise the provided socketfactory // Helps when using web debuggers like Fiddler Classic - if (socketFactory != null && (socketFactory instanceof SSLSocketFactory)) { - factory = (SSLSocketFactory) socketFactory; + if (socketFactory != null && (socketFactory instanceof SSLSocketFactory)) { + factory = (SSLSocketFactory) socketFactory; } else { SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, null); From e1061aebee7fef587032a14da5d71e6a54900535 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 20 Sep 2020 11:25:45 +0200 Subject: [PATCH 085/165] Update WebSocketClient.java Rework after review --- src/main/java/org/java_websocket/client/WebSocketClient.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index f28fd6304..d97fab079 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -485,7 +485,7 @@ public void run() { // if the socket is set by others we don't apply any TLS wrapper if (upgradeSocketToSSLSocket && "wss".equals(uri.getScheme())) { - SSLSocketFactory factory = null; + SSLSocketFactory factory; // Prioritise the provided socketfactory // Helps when using web debuggers like Fiddler Classic if (socketFactory != null && (socketFactory instanceof SSLSocketFactory)) { From 67ff5f8ff04b78442284c17d763c4cf17d87d4ea Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 20 Sep 2020 16:52:52 +0200 Subject: [PATCH 086/165] Replace the type specification in this constructor call with the diamond operator Some javadoc stuff --- .../org/java_websocket/AbstractWebSocket.java | 11 ++++++---- .../org/java_websocket/WebSocketImpl.java | 8 +++---- .../client/WebSocketClient.java | 4 ++-- .../org/java_websocket/drafts/Draft_6455.java | 20 ++++++++--------- .../exceptions/LimitExceededException.java | 3 +++ .../exceptions/WrappedIOException.java | 2 +- .../extensions/ExtensionRequestData.java | 4 ++-- .../PerMessageDeflateExtension.java | 22 ++++++++++++++----- .../handshake/HandshakedataImpl1.java | 2 +- .../DefaultSSLWebSocketServerFactory.java | 2 +- .../server/WebSocketServer.java | 18 ++++++++------- 11 files changed, 57 insertions(+), 39 deletions(-) diff --git a/src/main/java/org/java_websocket/AbstractWebSocket.java b/src/main/java/org/java_websocket/AbstractWebSocket.java index a6709f0aa..c3e77a089 100644 --- a/src/main/java/org/java_websocket/AbstractWebSocket.java +++ b/src/main/java/org/java_websocket/AbstractWebSocket.java @@ -74,7 +74,7 @@ public abstract class AbstractWebSocket extends WebSocketAdapter { * * @since 1.4.1 */ - private ScheduledFuture connectionLostCheckerFuture; + private ScheduledFuture connectionLostCheckerFuture; /** * Attribute for the lost connection check interval in nanoseconds @@ -126,7 +126,7 @@ public void setConnectionLostTimeout(int connectionLostTimeout) { log.trace("Connection lost timer restarted"); //Reset all the pings try { - ArrayList connections = new ArrayList(getConnections()); + ArrayList connections = new ArrayList<>(getConnections()); WebSocketImpl webSocketImpl; for (WebSocket conn : connections) { if (conn instanceof WebSocketImpl) { @@ -188,14 +188,17 @@ private void restartConnectionLostTimer() { /** * Keep the connections in a separate list to not cause deadlocks */ - private ArrayList connections = new ArrayList(); + private ArrayList connections = new ArrayList<>(); @Override public void run() { connections.clear(); try { connections.addAll(getConnections()); - long minimumPongTime = (long) (System.nanoTime() - (connectionLostTimeout * 1.5)); + long minimumPongTime; + synchronized (syncConnectionLost) { + minimumPongTime = (long) (System.nanoTime() - (connectionLostTimeout * 1.5)); + } for (WebSocket conn : connections) { executeConnectionLostDetection(conn, minimumPongTime); } diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index 2fc312e64..8a6f96027 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -190,7 +190,7 @@ public WebSocketImpl(WebSocketListener listener, List drafts) { this.role = Role.SERVER; // draft.copyInstance will be called when the draft is first needed if (drafts == null || drafts.isEmpty()) { - knownDrafts = new ArrayList(); + knownDrafts = new ArrayList<>(); knownDrafts.add(new Draft_6455()); } else { knownDrafts = drafts; @@ -208,8 +208,8 @@ public WebSocketImpl(WebSocketListener listener, Draft draft) { if (listener == null || (draft == null && role == Role.SERVER)) { throw new IllegalArgumentException("parameters must not be null"); } - this.outQueue = new LinkedBlockingQueue(); - inQueue = new LinkedBlockingQueue(); + this.outQueue = new LinkedBlockingQueue<>(); + inQueue = new LinkedBlockingQueue<>(); this.wsl = listener; this.role = Role.CLIENT; if (draft != null) { @@ -666,7 +666,7 @@ private void send(Collection frames) { if (frames == null) { throw new IllegalArgumentException(); } - ArrayList outgoingFrames = new ArrayList(); + ArrayList outgoingFrames = new ArrayList<>(); for (Framedata f : frames) { log.trace("send frame: {}", f); outgoingFrames.add(draft.createBinaryFrame(f)); diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index d97fab079..4d37b5682 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -223,7 +223,7 @@ public InetAddress resolve(URI uri) throws UnknownHostException { } }; if (httpHeaders != null) { - headers = new TreeMap(String.CASE_INSENSITIVE_ORDER); + headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); headers.putAll(httpHeaders); } this.connectTimeout = connectTimeout; @@ -269,7 +269,7 @@ public Socket getSocket() { */ public void addHeader(String key, String value) { if (headers == null) { - headers = new TreeMap(String.CASE_INSENSITIVE_ORDER); + headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); } headers.put(key, value); } diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index f7e59fc41..06c964d88 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -229,10 +229,10 @@ public Draft_6455(List inputExtensions, List inputProtoco if (inputExtensions == null || inputProtocols == null || inputMaxFrameSize < 1) { throw new IllegalArgumentException(); } - knownExtensions = new ArrayList(inputExtensions.size()); - knownProtocols = new ArrayList(inputProtocols.size()); + knownExtensions = new ArrayList<>(inputExtensions.size()); + knownProtocols = new ArrayList<>(inputProtocols.size()); boolean hasDefault = false; - byteBufferList = new ArrayList(); + byteBufferList = new ArrayList<>(); for (IExtension inputExtension : inputExtensions) { if (inputExtension.getClass().equals(DefaultExtension.class)) { hasDefault = true; @@ -442,13 +442,13 @@ public HandshakeBuilder postProcessHandshakeResponseAsServer(ClientHandshake req @Override public Draft copyInstance() { - ArrayList newExtensions = new ArrayList(); - for (IExtension extension : getKnownExtensions()) { - newExtensions.add(extension.copyInstance()); + ArrayList newExtensions = new ArrayList<>(); + for (IExtension knownExtension : getKnownExtensions()) { + newExtensions.add(knownExtension.copyInstance()); } - ArrayList newProtocols = new ArrayList(); - for (IProtocol protocol : getKnownProtocols()) { - newProtocols.add(protocol.copyInstance()); + ArrayList newProtocols = new ArrayList<>(); + for (IProtocol knownProtocol : getKnownProtocols()) { + newProtocols.add(knownProtocol.copyInstance()); } return new Draft_6455(newExtensions, newProtocols, maxFrameSize); } @@ -700,7 +700,7 @@ private int getSizeBytes(ByteBuffer mes) { @Override public List translateFrame(ByteBuffer buffer) throws InvalidDataException { while (true) { - List frames = new LinkedList(); + List frames = new LinkedList<>(); Framedata cur; if (incompleteframe != null) { // complete an incomplete frame diff --git a/src/main/java/org/java_websocket/exceptions/LimitExceededException.java b/src/main/java/org/java_websocket/exceptions/LimitExceededException.java index 9f76d442f..0d4a81825 100644 --- a/src/main/java/org/java_websocket/exceptions/LimitExceededException.java +++ b/src/main/java/org/java_websocket/exceptions/LimitExceededException.java @@ -55,6 +55,7 @@ public LimitExceededException() { * constructor for a LimitExceededException *

      * calling InvalidDataException with closecode TOOBIG + * @param limit the allowed size which was not enough */ public LimitExceededException(int limit) { super(CloseFrame.TOOBIG); @@ -65,6 +66,8 @@ public LimitExceededException(int limit) { * constructor for a LimitExceededException *

      * calling InvalidDataException with closecode TOOBIG + * @param s the detail message. + * @param limit the allowed size which was not enough */ public LimitExceededException(String s, int limit) { super(CloseFrame.TOOBIG, s); diff --git a/src/main/java/org/java_websocket/exceptions/WrappedIOException.java b/src/main/java/org/java_websocket/exceptions/WrappedIOException.java index fbcaddeaa..3ec31773d 100644 --- a/src/main/java/org/java_websocket/exceptions/WrappedIOException.java +++ b/src/main/java/org/java_websocket/exceptions/WrappedIOException.java @@ -40,7 +40,7 @@ public class WrappedIOException extends Exception { /** * The websocket where the IOException happened */ - private final WebSocket connection; + private final transient WebSocket connection; /** * The IOException diff --git a/src/main/java/org/java_websocket/extensions/ExtensionRequestData.java b/src/main/java/org/java_websocket/extensions/ExtensionRequestData.java index 8d46d9566..37bc9de20 100644 --- a/src/main/java/org/java_websocket/extensions/ExtensionRequestData.java +++ b/src/main/java/org/java_websocket/extensions/ExtensionRequestData.java @@ -5,13 +5,13 @@ public class ExtensionRequestData { - public static String EMPTY_VALUE = ""; + public static final String EMPTY_VALUE = ""; private Map extensionParameters; private String extensionName; private ExtensionRequestData() { - extensionParameters = new LinkedHashMap(); + extensionParameters = new LinkedHashMap<>(); } public static ExtensionRequestData parseExtensionRequest(String extensionRequest) { diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index c0346b88b..6da4a0c98 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -49,7 +49,7 @@ public class PerMessageDeflateExtension extends CompressionExtension { // For WebSocketServers, this variable holds the extension parameters that the peer client has requested. // For WebSocketClients, this variable holds the extension parameters that client himself has requested. - private Map requestedParameters = new LinkedHashMap(); + private Map requestedParameters = new LinkedHashMap<>(); private Inflater inflater = new Inflater(true); private Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); @@ -71,28 +71,38 @@ public void setDeflater(Deflater deflater) { } /** - * @return serverNoContextTakeover + * Access the "server_no_context_takeover" extension parameter + * + * @see The "server_no_context_takeover" Extension Parameter + * @return serverNoContextTakeover is the server no context parameter active */ public boolean isServerNoContextTakeover() { return serverNoContextTakeover; } /** - * @param serverNoContextTakeover + * Setter for the "server_no_context_takeover" extension parameter + * @see The "server_no_context_takeover" Extension Parameter + * @param serverNoContextTakeover set the server no context parameter */ public void setServerNoContextTakeover(boolean serverNoContextTakeover) { this.serverNoContextTakeover = serverNoContextTakeover; } /** - * @return clientNoContextTakeover + * Access the "client_no_context_takeover" extension parameter + * + * @see The "client_no_context_takeover" Extension Parameter + * @return clientNoContextTakeover is the client no context parameter active */ public boolean isClientNoContextTakeover() { return clientNoContextTakeover; } /** - * @param clientNoContextTakeover + * Setter for the "client_no_context_takeover" extension parameter + * @see The "client_no_context_takeover" Extension Parameter + * @param clientNoContextTakeover set the client no context parameter */ public void setClientNoContextTakeover(boolean clientNoContextTakeover) { this.clientNoContextTakeover = clientNoContextTakeover; @@ -224,7 +234,7 @@ public void encodeFrame(Framedata inputFrame) { * @param data the bytes of data * @return true if the data is OK */ - private boolean endsWithTail(byte[] data) { + private static boolean endsWithTail(byte[] data) { if (data.length < 4) { return false; } diff --git a/src/main/java/org/java_websocket/handshake/HandshakedataImpl1.java b/src/main/java/org/java_websocket/handshake/HandshakedataImpl1.java index bc59993c6..62824cdd2 100644 --- a/src/main/java/org/java_websocket/handshake/HandshakedataImpl1.java +++ b/src/main/java/org/java_websocket/handshake/HandshakedataImpl1.java @@ -48,7 +48,7 @@ public class HandshakedataImpl1 implements HandshakeBuilder { * Constructor for handshake implementation */ public HandshakedataImpl1() { - map = new TreeMap(String.CASE_INSENSITIVE_ORDER); + map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); } @Override diff --git a/src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java b/src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java index be5c8e678..f2732030c 100644 --- a/src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java +++ b/src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java @@ -68,7 +68,7 @@ public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws I * We remove TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 from the enabled ciphers since it is just available when you patch your java installation directly. * E.g. firefox requests this cipher and this causes some dcs/instable connections */ - List ciphers = new ArrayList(Arrays.asList(e.getEnabledCipherSuites())); + List ciphers = new ArrayList<>(Arrays.asList(e.getEnabledCipherSuites())); ciphers.remove("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"); e.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()])); e.setUseClientMode(false); diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 71f8728ba..1c67ee70e 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -221,10 +221,10 @@ public WebSocketServer(InetSocketAddress address, int decodercount, List this.connections = connectionscontainer; setTcpNoDelay(false); setReuseAddr(false); - iqueue = new LinkedList(); + iqueue = new LinkedList<>(); - decoders = new ArrayList(decodercount); - buffers = new LinkedBlockingQueue(); + decoders = new ArrayList<>(decodercount); + buffers = new LinkedBlockingQueue<>(); for (int i = 0; i < decodercount; i++) { WebSocketWorker ex = new WebSocketWorker(); decoders.add(ex); @@ -270,7 +270,7 @@ public void stop(int timeout) throws InterruptedException { // copy the connections in a list (prevent callback deadlocks) synchronized (connections) { - socketsToClose = new ArrayList(connections); + socketsToClose = new ArrayList<>(connections); } for (WebSocket ws : socketsToClose) { @@ -300,7 +300,7 @@ public void stop() throws IOException, InterruptedException { */ public Collection getConnections() { synchronized (connections) { - return Collections.unmodifiableCollection(new ArrayList(connections)); + return Collections.unmodifiableCollection(new ArrayList<>(connections)); } } @@ -337,6 +337,7 @@ public List getDraft() { * "backlog" parameter to {@link ServerSocket#bind(SocketAddress, int)} * * @since 1.5.0 + * @param numberOfConnections the new number of allowed pending connections */ public void setMaxPendingConnections(int numberOfConnections) { maxPendingConnections = numberOfConnections; @@ -347,6 +348,7 @@ public void setMaxPendingConnections(int numberOfConnections) { * * @see #setMaxPendingConnections(int) * @since 1.5.0 + * @return the maximum number of pending connections */ public int getMaxPendingConnections() { return maxPendingConnections; @@ -1004,10 +1006,10 @@ private void doBroadcast(Object data, Collection clients) { if (strData == null && byteData == null) { return; } - Map> draftFrames = new HashMap>(); + Map> draftFrames = new HashMap<>(); List clientCopy; synchronized (clients) { - clientCopy = new ArrayList(clients); + clientCopy = new ArrayList<>(clients); } for (WebSocket client : clientCopy) { if (client != null) { @@ -1054,7 +1056,7 @@ public class WebSocketWorker extends Thread { private BlockingQueue iqueue; public WebSocketWorker() { - iqueue = new LinkedBlockingQueue(); + iqueue = new LinkedBlockingQueue<>(); setName("WebSocketWorker-" + getId()); setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override From d33b7b8f8cc80c06c8b224cb067209bdd9d8d0f4 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 20 Sep 2020 17:42:46 +0200 Subject: [PATCH 087/165] Add SonarQube Action --- .github/workflows/sonar.yml | 36 ++++++++++++++++++++++++++++++++++++ pom.xml | 4 +++- 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/sonar.yml diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml new file mode 100644 index 000000000..66e4370a5 --- /dev/null +++ b/.github/workflows/sonar.yml @@ -0,0 +1,36 @@ +name: SonarQube +on: + push: + branches: + - master + pull_request: + types: [opened, synchronize, reopened] +jobs: + build: + name: SonarQube + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + - name: Set up JDK 11 + uses: actions/setup-java@v1 + with: + java-version: 11 + - name: Cache SonarCloud packages + uses: actions/cache@v1 + with: + path: ~/.sonar/cache + key: ${{ runner.os }}-sonar + restore-keys: ${{ runner.os }}-sonar + - name: Cache Maven packages + uses: actions/cache@v1 + with: + path: ~/.m2 + key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} + restore-keys: ${{ runner.os }}-m2 + - name: Build and analyze + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + run: mvn -B org.jacoco:jacoco-maven-plugin:prepare-agent install org.jacoco:jacoco-maven-plugin:report verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar \ No newline at end of file diff --git a/pom.xml b/pom.xml index 99f5c2701..af362d909 100644 --- a/pom.xml +++ b/pom.xml @@ -27,7 +27,9 @@ 3.1.0 3.0.0 1.6.8 - + org.java-websocket:Java-WebSocket + marci4-github + https://sonarcloud.io From 08be8690b3e332c4133864e7d8bbcf9959609bb3 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sat, 26 Sep 2020 17:57:00 +0200 Subject: [PATCH 088/165] Code Quality Reduce complexity Fix broken test --- .../client/WebSocketClient.java | 60 +++++++++++-------- .../server/WebSocketServer.java | 11 +--- .../protocols/AllProtocolTests.java | 2 +- ...va => ProtocolHandshakeRejectionTest.java} | 39 ++++++++---- .../java_websocket/server/AllServerTests.java | 3 +- .../server/WebSocketServerTest.java | 8 +++ 6 files changed, 77 insertions(+), 46 deletions(-) rename src/test/java/org/java_websocket/protocols/{ProtoclHandshakeRejectionTest.java => ProtocolHandshakeRejectionTest.java} (96%) diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 4d37b5682..203c9b67d 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -36,6 +36,8 @@ import java.net.URI; import java.net.UnknownHostException; import java.nio.ByteBuffer; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; import java.util.Collection; import java.util.Collections; import java.util.Map; @@ -461,19 +463,7 @@ public void sendPing() { public void run() { InputStream istream; try { - boolean upgradeSocketToSSLSocket = false; - // Prioritise a proxy over a socket factory and apply the socketfactory later - if (proxy != Proxy.NO_PROXY) { - socket = new Socket(proxy); - upgradeSocketToSSLSocket = true; - } else if (socketFactory != null) { - socket = socketFactory.createSocket(); - } else if (socket == null) { - socket = new Socket(proxy); - upgradeSocketToSSLSocket = true; - } else if (socket.isClosed()) { - throw new IOException(); - } + boolean upgradeSocketToSSLSocket = prepareSocket(); socket.setTcpNoDelay(isTcpNoDelay()); socket.setReuseAddress(isReuseAddr()); @@ -485,17 +475,7 @@ public void run() { // if the socket is set by others we don't apply any TLS wrapper if (upgradeSocketToSSLSocket && "wss".equals(uri.getScheme())) { - SSLSocketFactory factory; - // Prioritise the provided socketfactory - // Helps when using web debuggers like Fiddler Classic - if (socketFactory != null && (socketFactory instanceof SSLSocketFactory)) { - factory = (SSLSocketFactory) socketFactory; - } else { - SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); - sslContext.init(null, null, null); - factory = sslContext.getSocketFactory(); - } - socket = factory.createSocket(socket, uri.getHost(), getPort(), true); + upgradeSocketToSSL(); } if (socket instanceof SSLSocket) { @@ -546,6 +526,38 @@ public void run() { connectReadThread = null; } + private void upgradeSocketToSSL() + throws NoSuchAlgorithmException, KeyManagementException, IOException { + SSLSocketFactory factory; + // Prioritise the provided socketfactory + // Helps when using web debuggers like Fiddler Classic + if (socketFactory instanceof SSLSocketFactory) { + factory = (SSLSocketFactory) socketFactory; + } else { + SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); + sslContext.init(null, null, null); + factory = sslContext.getSocketFactory(); + } + socket = factory.createSocket(socket, uri.getHost(), getPort(), true); + } + + private boolean prepareSocket() throws IOException { + boolean upgradeSocketToSSLSocket = false; + // Prioritise a proxy over a socket factory and apply the socketfactory later + if (proxy != Proxy.NO_PROXY) { + socket = new Socket(proxy); + upgradeSocketToSSLSocket = true; + } else if (socketFactory != null) { + socket = socketFactory.createSocket(); + } else if (socket == null) { + socket = new Socket(proxy); + upgradeSocketToSSLSocket = true; + } else if (socket.isClosed()) { + throw new IOException(); + } + return upgradeSocketToSSLSocket; + } + /** * Apply specific SSLParameters If you override this method make sure to always call * super.onSetSSLParameters() to ensure the hostname validation is active diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 1c67ee70e..11073619c 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -287,7 +287,7 @@ public void stop(int timeout) throws InterruptedException { } } - public void stop() throws IOException, InterruptedException { + public void stop() throws InterruptedException { stop(0); } @@ -538,10 +538,8 @@ private boolean doRead(SelectionKey key, Iterator i) private void doWrite(SelectionKey key) throws WrappedIOException { WebSocketImpl conn = (WebSocketImpl) key.attachment(); try { - if (SocketChannelIOHelper.batch(conn, conn.getChannel())) { - if (key.isValid()) { - key.interestOps(SelectionKey.OP_READ); - } + if (SocketChannelIOHelper.batch(conn, conn.getChannel()) && key.isValid()) { + key.interestOps(SelectionKey.OP_READ); } } catch (IOException e) { throw new WrappedIOException(conn, e); @@ -693,9 +691,6 @@ private void handleFatal(WebSocket conn, Exception e) { } try { stop(); - } catch (IOException e1) { - log.error("Error during shutdown", e1); - onError(null, e1); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); log.error("Interrupt during stop", e); diff --git a/src/test/java/org/java_websocket/protocols/AllProtocolTests.java b/src/test/java/org/java_websocket/protocols/AllProtocolTests.java index ae403d7ba..60c31ae02 100644 --- a/src/test/java/org/java_websocket/protocols/AllProtocolTests.java +++ b/src/test/java/org/java_websocket/protocols/AllProtocolTests.java @@ -32,7 +32,7 @@ @RunWith(Suite.class) @Suite.SuiteClasses({ org.java_websocket.protocols.ProtocolTest.class, - org.java_websocket.protocols.ProtoclHandshakeRejectionTest.class + ProtocolHandshakeRejectionTest.class }) /** * Start all tests for protocols diff --git a/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java b/src/test/java/org/java_websocket/protocols/ProtocolHandshakeRejectionTest.java similarity index 96% rename from src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java rename to src/test/java/org/java_websocket/protocols/ProtocolHandshakeRejectionTest.java index 270fab805..f1249ff11 100644 --- a/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java +++ b/src/test/java/org/java_websocket/protocols/ProtocolHandshakeRejectionTest.java @@ -51,7 +51,7 @@ import org.junit.BeforeClass; import org.junit.Test; -public class ProtoclHandshakeRejectionTest { +public class ProtocolHandshakeRejectionTest { private static final String additionalHandshake = "HTTP/1.1 101 Websocket Connection Upgrade\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"; private static Thread thread; @@ -355,7 +355,7 @@ public void testHandshakeRejectionTestCase13() throws Exception { @Test(timeout = 5000) public void testHandshakeRejectionTestCase14() throws Exception { - ArrayList protocols = new ArrayList(); + ArrayList protocols = new ArrayList<>(); protocols.add(new Protocol("chat")); protocols.add(new Protocol("chat2")); testProtocolRejection(14, new Draft_6455(Collections.emptyList(), protocols)); @@ -363,7 +363,7 @@ public void testHandshakeRejectionTestCase14() throws Exception { @Test(timeout = 5000) public void testHandshakeRejectionTestCase15() throws Exception { - ArrayList protocols = new ArrayList(); + ArrayList protocols = new ArrayList<>(); protocols.add(new Protocol("chat")); protocols.add(new Protocol("chat2")); testProtocolRejection(15, new Draft_6455(Collections.emptyList(), protocols)); @@ -371,7 +371,7 @@ public void testHandshakeRejectionTestCase15() throws Exception { @Test(timeout = 5000) public void testHandshakeRejectionTestCase16() throws Exception { - ArrayList protocols = new ArrayList(); + ArrayList protocols = new ArrayList<>(); protocols.add(new Protocol("chat")); protocols.add(new Protocol("chat2")); testProtocolRejection(16, new Draft_6455(Collections.emptyList(), protocols)); @@ -379,7 +379,7 @@ public void testHandshakeRejectionTestCase16() throws Exception { @Test(timeout = 5000) public void testHandshakeRejectionTestCase17() throws Exception { - ArrayList protocols = new ArrayList(); + ArrayList protocols = new ArrayList<>(); protocols.add(new Protocol("chat")); protocols.add(new Protocol("")); testProtocolRejection(17, new Draft_6455(Collections.emptyList(), protocols)); @@ -402,7 +402,7 @@ public void testHandshakeRejectionTestCase20() throws Exception { @Test(timeout = 5000) public void testHandshakeRejectionTestCase21() throws Exception { - ArrayList protocols = new ArrayList(); + ArrayList protocols = new ArrayList<>(); protocols.add(new Protocol("chat1")); protocols.add(new Protocol("chat2")); protocols.add(new Protocol("chat3")); @@ -411,7 +411,7 @@ public void testHandshakeRejectionTestCase21() throws Exception { @Test(timeout = 5000) public void testHandshakeRejectionTestCase22() throws Exception { - ArrayList protocols = new ArrayList(); + ArrayList protocols = new ArrayList<>(); protocols.add(new Protocol("chat2")); protocols.add(new Protocol("chat3")); protocols.add(new Protocol("chat1")); @@ -420,7 +420,7 @@ public void testHandshakeRejectionTestCase22() throws Exception { @Test(timeout = 5000) public void testHandshakeRejectionTestCase23() throws Exception { - ArrayList protocols = new ArrayList(); + ArrayList protocols = new ArrayList<>(); protocols.add(new Protocol("chat3")); protocols.add(new Protocol("chat2")); protocols.add(new Protocol("chat1")); @@ -463,7 +463,7 @@ public void testHandshakeRejectionTestCase29() throws Exception { private void testProtocolRejection(int i, Draft_6455 draft) throws Exception { final int finalI = i; final boolean[] threadReturned = {false}; - WebSocketClient webSocketClient = new WebSocketClient( + final WebSocketClient webSocketClient = new WebSocketClient( new URI("ws://localhost:" + port + "/" + finalI), draft) { @Override public void onOpen(ServerHandshake handshakedata) { @@ -509,6 +509,7 @@ public void onClose(int code, String reason, boolean remote) { case 2: case 3: case 4: + case 17: case 20: case 24: case 25: @@ -533,10 +534,9 @@ public void onClose(int code, String reason, boolean remote) { case 6: case 7: case 8: - case 17: + case 14: assertEquals("chat", getProtocol().getProvidedProtocol()); break; - case 14: case 22: assertEquals("chat2", getProtocol().getProvidedProtocol()); break; @@ -588,9 +588,24 @@ public void onError(Exception ex) { fail("There should not be an exception"); } }; - Thread finalThread = new Thread(webSocketClient); + final AssertionError[] exc = new AssertionError[1]; + exc[0] = null; + Thread finalThread = new Thread(new Runnable() { + @Override + public void run() { + try { + webSocketClient.run(); + }catch(AssertionError e){ + exc[0] = e; + } + } + + }); finalThread.start(); finalThread.join(); + if (exc[0] != null) { + throw exc[0]; + } if (!threadReturned[0]) { fail("Error"); diff --git a/src/test/java/org/java_websocket/server/AllServerTests.java b/src/test/java/org/java_websocket/server/AllServerTests.java index 9f7683552..f1f84fc90 100644 --- a/src/test/java/org/java_websocket/server/AllServerTests.java +++ b/src/test/java/org/java_websocket/server/AllServerTests.java @@ -25,6 +25,7 @@ package org.java_websocket.server; +import org.java_websocket.protocols.ProtocolHandshakeRejectionTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; @@ -32,7 +33,7 @@ @RunWith(Suite.class) @Suite.SuiteClasses({ org.java_websocket.server.DefaultWebSocketServerFactoryTest.class, - org.java_websocket.protocols.ProtoclHandshakeRejectionTest.class + ProtocolHandshakeRejectionTest.class }) /** * Start all tests for the server diff --git a/src/test/java/org/java_websocket/server/WebSocketServerTest.java b/src/test/java/org/java_websocket/server/WebSocketServerTest.java index decac6c28..5bebf8028 100644 --- a/src/test/java/org/java_websocket/server/WebSocketServerTest.java +++ b/src/test/java/org/java_websocket/server/WebSocketServerTest.java @@ -142,6 +142,14 @@ public void testGetPort() throws IOException, InterruptedException { assertNotEquals(0, server.getPort()); } + @Test + public void testMaxPendingConnections() { + MyWebSocketServer server = new MyWebSocketServer(1337); + assertEquals(server.getMaxPendingConnections(), -1); + server.setMaxPendingConnections(10); + assertEquals(server.getMaxPendingConnections(), 10); + } + @Test public void testBroadcast() { MyWebSocketServer server = new MyWebSocketServer(1337); From 65c3f033a243ec23272a4969020e7a7e50845817 Mon Sep 17 00:00:00 2001 From: Marcel Prestel Date: Wed, 21 Oct 2020 13:47:20 +0000 Subject: [PATCH 089/165] Update sonar.yml --- .github/workflows/sonar.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index 66e4370a5..232b8a973 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -33,4 +33,4 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: mvn -B org.jacoco:jacoco-maven-plugin:prepare-agent install org.jacoco:jacoco-maven-plugin:report verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar \ No newline at end of file + run: mvn -B org.jacoco:jacoco-maven-plugin:prepare-agent install org.jacoco:jacoco-maven-plugin:report verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dmaven.test.failure.ignore=true From 766d7c1e968477f0be9b517bb1dd31daa99456b5 Mon Sep 17 00:00:00 2001 From: Prashant Tholia <65695939+prashanttholia@users.noreply.github.com> Date: Mon, 18 Jan 2021 20:21:39 +0530 Subject: [PATCH 090/165] Update documentation comments for member methods Update documentation comments for methods getRemoteSocketAddress and getLocalSocketAddress in WebSocket.java. --- src/main/java/org/java_websocket/WebSocket.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/java_websocket/WebSocket.java b/src/main/java/org/java_websocket/WebSocket.java index 6c7e9effc..d515f631b 100644 --- a/src/main/java/org/java_websocket/WebSocket.java +++ b/src/main/java/org/java_websocket/WebSocket.java @@ -137,17 +137,18 @@ public interface WebSocket { boolean hasBufferedData(); /** - * Returns the address of the endpoint this socket is connected to, or{@code null} if it is + * Returns the address of the endpoint this socket is connected to, or {@code null} if it is * unconnected. * - * @return never returns null + * @return the remote socket address or null, if this socket is unconnected */ InetSocketAddress getRemoteSocketAddress(); /** - * Returns the address of the endpoint this socket is bound to. + * Returns the address of the endpoint this socket is bound to, or {@code null} if it is not + * bound. * - * @return never returns null + * @return the local socket address or null, if this socket is not bound */ InetSocketAddress getLocalSocketAddress(); From b08342884ce37801b64cc6efeef984b5634da6f0 Mon Sep 17 00:00:00 2001 From: PhilipRoman Date: Wed, 3 Feb 2021 18:03:05 +0200 Subject: [PATCH 091/165] Set compatibility in build.gradle to 1.7 --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index e18733fae..fc7e007ea 100644 --- a/build.gradle +++ b/build.gradle @@ -10,8 +10,8 @@ repositories { group = 'org.java-websocket' version = '1.5.2-SNAPSHOT' -sourceCompatibility = 1.6 -targetCompatibility = 1.6 +sourceCompatibility = 1.7 +targetCompatibility = 1.7 configurations { deployerJars From 25af0976337829718d85b9711c2479e7c440bf59 Mon Sep 17 00:00:00 2001 From: PhilipRoman Date: Wed, 3 Feb 2021 18:37:17 +0200 Subject: [PATCH 092/165] Remove unused code and clean up build.gradle --- build.gradle | 30 +++++++++++------------------- 1 file changed, 11 insertions(+), 19 deletions(-) diff --git a/build.gradle b/build.gradle index fc7e007ea..098707ee5 100644 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,8 @@ -apply plugin: 'java' -apply plugin: 'idea' -apply plugin: 'maven' - +plugins { + id 'java' + id 'idea' + id 'maven' +} repositories { mavenLocal() @@ -17,10 +18,12 @@ configurations { deployerJars } -configure(install.repositories.mavenInstaller) { - pom.version = project.version - pom.groupId = "org.java-websocket" - pom.artifactId = 'Java-WebSocket' +install { + repositories.mavenInstaller { + pom.version = project.version + pom.groupId = project.group + pom.artifactId = 'Java-WebSocket' + } } dependencies { @@ -30,14 +33,3 @@ dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' testCompile group: 'org.json', name: 'json', version: '20180813' } - - -//deploy to maven repository -//uploadArchives { -// repositories.mavenDeployer { -// configuration = configurations.deployerJars -// repository(url: repositoryUrl) { -// authentication(userName: repositoryUsername, password: repositoryPassword) -// } -// } -//} From feec867c81d1a426815717b489147894a19826e5 Mon Sep 17 00:00:00 2001 From: marci4 Date: Mon, 22 Mar 2021 21:59:27 +0100 Subject: [PATCH 093/165] Use SecureRandom instead of Random Fixes #1132 --- src/main/java/org/java_websocket/drafts/Draft_6455.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index 06c964d88..68feb615e 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -29,6 +29,7 @@ import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; @@ -36,7 +37,6 @@ import java.util.LinkedList; import java.util.List; import java.util.Locale; -import java.util.Random; import java.util.TimeZone; import org.java_websocket.WebSocketImpl; import org.java_websocket.enums.CloseHandshakeType; @@ -150,7 +150,7 @@ public class Draft_6455 extends Draft { /** * Attribute for the reusable random instance */ - private final Random reuseableRandom = new Random(); + private final SecureRandom reuseableRandom = new SecureRandom(); /** * Attribute for the maximum allowed size of a frame From 234a86545d5fc109367a2a8e03943710f1fb51b5 Mon Sep 17 00:00:00 2001 From: PhilipRoman Date: Mon, 29 Mar 2021 09:51:24 +0300 Subject: [PATCH 094/165] Configure Gradle to use utf-8 --- build.gradle | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/build.gradle b/build.gradle index 098707ee5..37bdcd90e 100644 --- a/build.gradle +++ b/build.gradle @@ -18,6 +18,14 @@ configurations { deployerJars } +compileJava { + options.compilerArgs += ['-encoding', 'UTF-8'] +} + +javadoc { + options.encoding = 'UTF-8' +} + install { repositories.mavenInstaller { pom.version = project.version From 9e5b79527ea1199c97dd4cf49871aafea0bcc903 Mon Sep 17 00:00:00 2001 From: PhilipRoman Date: Mon, 29 Mar 2021 10:49:55 +0300 Subject: [PATCH 095/165] Replace deprecated Gradle 'maven' plugin with 'maven-publish' --- build.gradle | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/build.gradle b/build.gradle index 37bdcd90e..d1be25f8a 100644 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,7 @@ plugins { id 'java' id 'idea' - id 'maven' + id 'maven-publish' } repositories { @@ -14,10 +14,6 @@ version = '1.5.2-SNAPSHOT' sourceCompatibility = 1.7 targetCompatibility = 1.7 -configurations { - deployerJars -} - compileJava { options.compilerArgs += ['-encoding', 'UTF-8'] } @@ -26,16 +22,19 @@ javadoc { options.encoding = 'UTF-8' } -install { - repositories.mavenInstaller { - pom.version = project.version - pom.groupId = project.group - pom.artifactId = 'Java-WebSocket' +publishing { + publications { + maven(MavenPublication) { + groupId = project.group + artifactId = 'Java-WebSocket' + version = project.version + + from components.java + } } } dependencies { - deployerJars "org.apache.maven.wagon:wagon-webdav:1.0-beta-2" compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25' testCompile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25' testCompile group: 'junit', name: 'junit', version: '4.12' From a25bce4a522ae538433a528460b6c0280a327828 Mon Sep 17 00:00:00 2001 From: PhilipRoman Date: Mon, 29 Mar 2021 11:05:43 +0300 Subject: [PATCH 096/165] Switch from deprecated Gradle 'compile' configuration to 'implementation' --- build.gradle | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index d1be25f8a..a23daffc7 100644 --- a/build.gradle +++ b/build.gradle @@ -35,8 +35,8 @@ publishing { } dependencies { - compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25' - testCompile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25' - testCompile group: 'junit', name: 'junit', version: '4.12' - testCompile group: 'org.json', name: 'json', version: '20180813' + implementation group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25' + testImplementation group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25' + testImplementation group: 'junit', name: 'junit', version: '4.12' + testImplementation group: 'org.json', name: 'json', version: '20180813' } From 2b33f4208c4e4007f863dd9c371d4369ac72ca43 Mon Sep 17 00:00:00 2001 From: marci4 Date: Mon, 5 Apr 2021 17:41:28 +0200 Subject: [PATCH 097/165] Update Changelog.md Changelog for 1.5.2 --- CHANGELOG.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b62db7b9..f4852e428 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,30 @@ # Change log +## Version Release 1.5.2 (2021/04/05) + +#### Bugs Fixed + +* [Issue 1132](https://github.com/TooTallNate/Java-WebSocket/issues/1132) - Draft_6455 flagged by Veracode CWE-331 replace Random with SecureRandom ([PR 1133 ](https://github.com/TooTallNate/Java-WebSocket/pull/1133) by [@marci4](https://github.com/marci4)) +* [Issue 1053](https://github.com/TooTallNate/Java-WebSocket/issues/1053) - It's an invalid check null with SEC_WEB_SOCKET_KEY . ([PR 1054 ](https://github.com/TooTallNate/Java-WebSocket/pull/1054) by [@dota17](https://github.com/dota17)) +* [Issue 1026](https://github.com/TooTallNate/Java-WebSocket/issues/1026) - Force client to use the valid schema ([PR 1025 ](https://github.com/TooTallNate/Java-WebSocket/pull/1025) by [@yindex](https://github.com/yindex)) +* [PR 1070](https://github.com/TooTallNate/Java-WebSocket/pull/1070) - Prioritise using provided socket factory when creating socket with proxy, by [@marci4](https://github.com/marci4) +* [PR 1028](https://github.com/TooTallNate/Java-WebSocket/pull/1028) - Fixed typo in WebSocketClient.reset's error message, by [@alphaho](https://github.com/alphaho) +* [PR 1018](https://github.com/TooTallNate/Java-WebSocket/pull/1018) - Added missing return character, by [@pawankgupta-se](https://github.com/pawankgupta-se) + +#### New Features + +* [Issue 1008](https://github.com/TooTallNate/Java-WebSocket/issues/1008) - Improve Sec-WebSocket-Protocol usability ([PR 1034 ](https://github.com/TooTallNate/Java-WebSocket/pull/1034) by [@marci4](https://github.com/marci4)) + +#### Refactoring + +* [Issue 1050](https://github.com/TooTallNate/Java-WebSocket/issues/1050) - What about adding the CodeFormatterProfile.xml with the code format ? ([PR 1060 ](https://github.com/TooTallNate/Java-WebSocket/pull/1060) by [@dota17](https://github.com/dota17)) +* [PR 1072](https://github.com/TooTallNate/Java-WebSocket/pull/1072) - Improve code quality, by [@marci4](https://github.com/marci4) +* [PR 1060](https://github.com/TooTallNate/Java-WebSocket/pull/1060) - Using Google Java Code Style To Reformat Code, by [@dota17](https://github.com/dota17) + +In this release 5 issues and 9 pull requests were closed. + +############################################################################### + ## Version Release 1.5.1 (2020/05/10) #### Bugs Fixed @@ -8,6 +33,8 @@ In this release 1 issue and 1 pull request were closed. +############################################################################### + ## Version Release 1.5.0 (2020/05/06) #### Breaking Changes From b088e6d27efc4cf73837b21db4c75eddcf77f328 Mon Sep 17 00:00:00 2001 From: marci4 Date: Mon, 5 Apr 2021 17:55:09 +0200 Subject: [PATCH 098/165] Release 1.5.2 --- build.gradle | 2 +- pom.xml | 3 ++- src/main/java/org/java_websocket/SSLSocketChannel.java | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/build.gradle b/build.gradle index a23daffc7..e8be125e9 100644 --- a/build.gradle +++ b/build.gradle @@ -10,7 +10,7 @@ repositories { } group = 'org.java-websocket' -version = '1.5.2-SNAPSHOT' +version = '1.5.3-SNAPSHOT' sourceCompatibility = 1.7 targetCompatibility = 1.7 diff --git a/pom.xml b/pom.xml index af362d909..52f26cd29 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.java-websocket Java-WebSocket jar - 1.5.2-SNAPSHOT + 1.5.3-SNAPSHOT Java-WebSocket A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket @@ -226,6 +226,7 @@ ossrh true + https://oss.sonatype.org/ diff --git a/src/main/java/org/java_websocket/SSLSocketChannel.java b/src/main/java/org/java_websocket/SSLSocketChannel.java index 0c1f0c413..b4024505b 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel.java @@ -417,7 +417,7 @@ private ByteBuffer enlargeApplicationBuffer(ByteBuffer buffer) { } /** - * Compares sessionProposedCapacity with buffer's capacity. If buffer's capacity is + * Compares sessionProposedCapacity with buffer's capacity. If buffer's capacity is * smaller, returns a buffer with the proposed capacity. If it's equal or larger, returns a buffer * with capacity twice the size of the initial one. * From 9a290e85b9d13a2c395b7106b1e43aceb4ac2fc2 Mon Sep 17 00:00:00 2001 From: marci4 Date: Mon, 19 Apr 2021 19:56:00 +0200 Subject: [PATCH 099/165] Provide SSLSession in WebSocketClient Fixes #1142 --- .../client/WebSocketClient.java | 8 +- .../java_websocket/issues/Issue1142Test.java | 138 ++++++++++++++++++ 2 files changed, 144 insertions(+), 2 deletions(-) create mode 100644 src/test/java/org/java_websocket/issues/Issue1142Test.java diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 203c9b67d..ae45f676c 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -955,12 +955,16 @@ public String getResourceDescriptor() { @Override public boolean hasSSLSupport() { - return engine.hasSSLSupport(); + return socket instanceof SSLSocket; } @Override public SSLSession getSSLSession() { - return engine.getSSLSession(); + if (!hasSSLSupport()) { + throw new IllegalArgumentException( + "This websocket uses ws instead of wss. No SSLSession available."); + } + return ((SSLSocket)socket).getSession(); } @Override diff --git a/src/test/java/org/java_websocket/issues/Issue1142Test.java b/src/test/java/org/java_websocket/issues/Issue1142Test.java new file mode 100644 index 000000000..21de76bb6 --- /dev/null +++ b/src/test/java/org/java_websocket/issues/Issue1142Test.java @@ -0,0 +1,138 @@ +package org.java_websocket.issues; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.util.concurrent.CountDownLatch; +import javax.net.ssl.SSLContext; +import org.java_websocket.WebSocket; +import org.java_websocket.client.WebSocketClient; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.handshake.ServerHandshake; +import org.java_websocket.server.DefaultSSLWebSocketServerFactory; +import org.java_websocket.server.WebSocketServer; +import org.java_websocket.util.SSLContextUtil; +import org.java_websocket.util.SocketUtil; +import org.junit.Test; + +public class Issue1142Test { + + + + @Test(timeout = 4000) + public void testWithoutSSLSession() + throws IOException, URISyntaxException, InterruptedException { + int port = SocketUtil.getAvailablePort(); + final CountDownLatch countServerDownLatch = new CountDownLatch(1); + final WebSocketClient webSocket = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + countServerDownLatch.countDown(); + } + + @Override + public void onMessage(String message) { + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + } + }; + WebSocketServer server = new MyWebSocketServer(port, countServerDownLatch); + server.start(); + countServerDownLatch.await(); + webSocket.connectBlocking(); + assertFalse(webSocket.hasSSLSupport()); + try { + webSocket.getSSLSession(); + assertFalse(false); + } catch (IllegalArgumentException e) { + // Fine + } + server.stop(); + } + + @Test(timeout = 4000) + public void testWithSSLSession() + throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { + int port = SocketUtil.getAvailablePort(); + final CountDownLatch countServerDownLatch = new CountDownLatch(1); + final WebSocketClient webSocket = new WebSocketClient(new URI("wss://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + countServerDownLatch.countDown(); + } + + @Override + public void onMessage(String message) { + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + } + }; + WebSocketServer server = new MyWebSocketServer(port, countServerDownLatch); + SSLContext sslContext = SSLContextUtil.getContext(); + + server.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext)); + webSocket.setSocketFactory(sslContext.getSocketFactory()); + server.start(); + countServerDownLatch.await(); + webSocket.connectBlocking(); + assertTrue(webSocket.hasSSLSupport()); + assertNotNull(webSocket.getSSLSession()); + server.stop(); + } + + private static class MyWebSocketServer extends WebSocketServer { + + private final CountDownLatch countServerLatch; + + + public MyWebSocketServer(int port, CountDownLatch serverDownLatch) { + super(new InetSocketAddress(port)); + this.countServerLatch = serverDownLatch; + } + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + ex.printStackTrace(); + } + + @Override + public void onStart() { + countServerLatch.countDown(); + } + } +} From ce28e7023f8ddeb9bc1971bf80ab629e6dc27e28 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 25 Jul 2021 22:03:01 +0200 Subject: [PATCH 100/165] PermessageDeflate should handle uncompressed messages Fixes #1164 --- .../PerMessageDeflateExtension.java | 36 +++++++++++++--- .../example/AutobahnServerTest.java | 4 +- .../PerMessageDeflateExtensionTest.java | 41 ++++++++++++++++++- 3 files changed, 73 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index 6da4a0c98..824ceb68e 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -44,6 +44,8 @@ public class PerMessageDeflateExtension extends CompressionExtension { private static final byte[] TAIL_BYTES = {(byte) 0x00, (byte) 0x00, (byte) 0xFF, (byte) 0xFF}; private static final int BUFFER_SIZE = 1 << 10; + private int threshold = 1024; + private boolean serverNoContextTakeover = true; private boolean clientNoContextTakeover = false; @@ -70,6 +72,24 @@ public void setDeflater(Deflater deflater) { this.deflater = deflater; } + /** + * Get the size threshold for doing the compression + * @return Size (in bytes) below which messages will not be compressed + * @since 1.5.3 + */ + public int getThreshold() { + return threshold; + } + + /** + * Set the size when payloads smaller than this will not be compressed. + * @param threshold the size in bytes + * @since 1.5.3 + */ + public void setThreshold(int threshold) { + this.threshold = threshold; + } + /** * Access the "server_no_context_takeover" extension parameter * @@ -127,6 +147,10 @@ public void decodeFrame(Framedata inputFrame) throws InvalidDataException { throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "RSV1 bit can only be set for the first frame."); } + // If rsv1 is not set, we dont have a compressed message + if (!inputFrame.isRSV1()) { + return; + } // Decompressed output buffer. ByteArrayOutputStream output = new ByteArrayOutputStream(); @@ -190,12 +214,16 @@ public void encodeFrame(Framedata inputFrame) { return; } + byte[] payloadData = inputFrame.getPayloadData().array(); + if (payloadData.length < threshold) { + return; + } // Only the first frame's RSV1 must be set. if (!(inputFrame instanceof ContinuousFrame)) { ((DataFrame) inputFrame).setRSV1(true); } - deflater.setInput(inputFrame.getPayloadData().array()); + deflater.setInput(payloadData); // Compressed output buffer. ByteArrayOutputStream output = new ByteArrayOutputStream(); // Temporary buffer to hold compressed output. @@ -316,10 +344,6 @@ public IExtension copyInstance() { */ @Override public void isFrameValid(Framedata inputFrame) throws InvalidDataException { - if ((inputFrame instanceof TextFrame || inputFrame instanceof BinaryFrame) && !inputFrame - .isRSV1()) { - throw new InvalidFrameException("RSV1 bit must be set for DataFrames."); - } if ((inputFrame instanceof ContinuousFrame) && (inputFrame.isRSV1() || inputFrame.isRSV2() || inputFrame.isRSV3())) { throw new InvalidFrameException( @@ -333,4 +357,6 @@ public void isFrameValid(Framedata inputFrame) throws InvalidDataException { public String toString() { return "PerMessageDeflateExtension"; } + + } diff --git a/src/test/java/org/java_websocket/example/AutobahnServerTest.java b/src/test/java/org/java_websocket/example/AutobahnServerTest.java index 0f6bc84df..6bfaf5871 100644 --- a/src/test/java/org/java_websocket/example/AutobahnServerTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnServerTest.java @@ -101,8 +101,10 @@ public static void main(String[] args) throws UnknownHostException { System.out.println("No limit specified. Defaulting to MaxInteger"); limit = Integer.MAX_VALUE; } + PerMessageDeflateExtension perMessageDeflateExtension = new PerMessageDeflateExtension(); + perMessageDeflateExtension.setThreshold(0); AutobahnServerTest test = new AutobahnServerTest(port, limit, - new Draft_6455(new PerMessageDeflateExtension())); + new Draft_6455(perMessageDeflateExtension)); test.setConnectionLostTimeout(0); test.start(); } diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index 624748318..0a25383b6 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -11,6 +11,7 @@ import java.util.zip.Inflater; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.extensions.permessage_deflate.PerMessageDeflateExtension; +import org.java_websocket.framing.BinaryFrame; import org.java_websocket.framing.ContinuousFrame; import org.java_websocket.framing.TextFrame; import org.junit.Test; @@ -20,6 +21,7 @@ public class PerMessageDeflateExtensionTest { @Test public void testDecodeFrame() throws InvalidDataException { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setThreshold(0); String str = "This is a highly compressable text" + "This is a highly compressable text" + "This is a highly compressable text" @@ -29,13 +31,30 @@ public void testDecodeFrame() throws InvalidDataException { TextFrame frame = new TextFrame(); frame.setPayload(ByteBuffer.wrap(message)); deflateExtension.encodeFrame(frame); + assertTrue(frame.isRSV1()); deflateExtension.decodeFrame(frame); assertArrayEquals(message, frame.getPayloadData().array()); } + @Test + public void testDecodeFrameIfRSVIsNotSet() throws InvalidDataException { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + String str = "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text"; + byte[] message = str.getBytes(); + TextFrame frame = new TextFrame(); + frame.setPayload(ByteBuffer.wrap(message)); + deflateExtension.decodeFrame(frame); + assertArrayEquals(message, frame.getPayloadData().array()); + assertFalse(frame.isRSV1()); + } @Test public void testEncodeFrame() { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setThreshold(0); String str = "This is a highly compressable text" + "This is a highly compressable text" + "This is a highly compressable text" @@ -47,6 +66,25 @@ public void testEncodeFrame() { deflateExtension.encodeFrame(frame); assertTrue(message.length > frame.getPayloadData().array().length); } + @Test + public void testEncodeFrameBelowThreshold() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setThreshold(11); + String str = "Hello World"; + byte[] message = str.getBytes(); + TextFrame frame = new TextFrame(); + frame.setPayload(ByteBuffer.wrap(message)); + deflateExtension.encodeFrame(frame); + // Message length is equal to the threshold --> encode + assertTrue(frame.isRSV1()); + str = "Hello Worl"; + message = str.getBytes(); + frame = new TextFrame(); + frame.setPayload(ByteBuffer.wrap(message)); + deflateExtension.encodeFrame(frame); + // Message length is below to the threshold --> do NOT encode + assertFalse(frame.isRSV1()); + } @Test public void testAcceptProvidedExtensionAsServer() { @@ -72,9 +110,8 @@ public void testIsFrameValid() { TextFrame frame = new TextFrame(); try { deflateExtension.isFrameValid(frame); - fail("Frame not valid. RSV1 must be set."); } catch (Exception e) { - // + fail("RSV1 is optional and should therefore not fail"); } frame.setRSV1(true); try { From 392fb1c3864d142421a92835c5823a78b1dd42c7 Mon Sep 17 00:00:00 2001 From: GrpeApple Date: Tue, 27 Jul 2021 20:13:18 +0800 Subject: [PATCH 101/165] Remove trailing whitespace --- CHANGELOG.md | 4 ++-- README.markdown | 8 ++++---- sonar-project.properties | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f4852e428..9bbbe7b91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,7 +41,7 @@ In this release 1 issue and 1 pull request were closed. This release requires API Level 1.7. -#### Security +#### Security This release contains a security fix for [CVE-2020-11050](https://nvd.nist.gov/vuln/detail/CVE-2020-11050). @@ -345,4 +345,4 @@ In this release 11 issues and 15 pull requests were closed. * [Issue 271](https://github.com/TooTallNate/Java-WebSocket/issues/271) - There is no notification for websocket server success start * [PR 462](https://github.com/TooTallNate/Java-WebSocket/pull/462) - Make TCP_NODELAY accessible -In this release 6 issues and 1 pull request were closed. \ No newline at end of file +In this release 6 issues and 1 pull request were closed. diff --git a/README.markdown b/README.markdown index d527bb044..90a7dab36 100644 --- a/README.markdown +++ b/README.markdown @@ -15,8 +15,8 @@ Implemented WebSocket protocol versions are: * [RFC 6455](http://tools.ietf.org/html/rfc6455) * [RFC 7692](http://tools.ietf.org/html/rfc7692) -[Here](https://github.com/TooTallNate/Java-WebSocket/wiki/Drafts) some more details about protocol versions/drafts. -[PerMessageDeflateExample](https://github.com/TooTallNate/Java-WebSocket/wiki/PerMessageDeflateExample) enable the extension with reference to both a server and client example. +[Here](https://github.com/TooTallNate/Java-WebSocket/wiki/Drafts) some more details about protocol versions/drafts. +[PerMessageDeflateExample](https://github.com/TooTallNate/Java-WebSocket/wiki/PerMessageDeflateExample) enable the extension with reference to both a server and client example. ## Getting Started @@ -76,14 +76,14 @@ Writing your own WebSocket Client The `org.java_websocket.client.WebSocketClient` abstract class can connect to valid WebSocket servers. The constructor expects a valid `ws://` URI to connect to. Important events `onOpen`, `onClose`, `onMessage` and `onError` -get fired throughout the life of the WebSocketClient, and must be implemented +get fired throughout the life of the WebSocketClient, and must be implemented in **your** subclass. An example for a WebSocketClient can be found in both the [wiki](https://github.com/TooTallNate/Java-WebSocket/wiki#client-example) and the [example](https://github.com/TooTallNate/Java-WebSocket/tree/master/src/main/example) folder. Examples ------------------- - + You can find a lot of examples [here](https://github.com/TooTallNate/Java-WebSocket/tree/master/src/main/example). WSS Support diff --git a/sonar-project.properties b/sonar-project.properties index 32d17639a..63a992eba 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -2,5 +2,5 @@ sonar.organization=marci4-github sonar.projectKey=org.java-websocket:Java-WebSocket # relative paths to source directories. More details and properties are described -# in https://sonarcloud.io/documentation/project-administration/narrowing-the-focus/ +# in https://sonarcloud.io/documentation/project-administration/narrowing-the-focus/ sonar.sources=src/main/java/org/java_websocket From a64ee7c6a823fb714a5d21052a05221de8049f89 Mon Sep 17 00:00:00 2001 From: marci4 Date: Tue, 27 Jul 2021 22:25:56 +0200 Subject: [PATCH 102/165] Deactivate sonar for pull requests --- .github/workflows/sonar.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index 232b8a973..82fdeb1b0 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -3,8 +3,6 @@ on: push: branches: - master - pull_request: - types: [opened, synchronize, reopened] jobs: build: name: SonarQube From f61aa43ff07ae6677461cbe7b9333a1e9eb800f2 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sat, 7 Aug 2021 14:31:18 +0200 Subject: [PATCH 103/165] Update README.markdown --- README.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.markdown b/README.markdown index d527bb044..86ab8d48d 100644 --- a/README.markdown +++ b/README.markdown @@ -94,7 +94,7 @@ To see how to use wss please take a look at the examples.
      If you do not have a valid **certificate** in place then you will have to create a self signed one. Browsers will simply refuse the connection in case of a bad certificate and will not ask the user to accept it. So the first step will be to make a browser to accept your self signed certificate. ( https://bugzilla.mozilla.org/show_bug.cgi?id=594502 ).
      -If the websocket server url is `wss://localhost:8000` visit the url `https://localhost:8000` with your browser. The browser will recognize the handshake and allow you to accept the certificate. This technique is also demonstrated in this [video](http://www.youtube.com/watch?v=F8lBdfAZPkU). +If the websocket server url is `wss://localhost:8000` visit the url `https://localhost:8000` with your browser. The browser will recognize the handshake and allow you to accept the certificate. The vm option `-Djavax.net.debug=all` can help to find out if there is a problem with the certificate. From d71467cc56885930def936cf552e6c52952035ab Mon Sep 17 00:00:00 2001 From: Uladzimir Tsykun Date: Mon, 4 Oct 2021 02:42:47 +0300 Subject: [PATCH 104/165] Added support unresolved socket addresses --- src/main/java/org/java_websocket/client/WebSocketClient.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index ae45f676c..4277c2209 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -469,7 +469,7 @@ public void run() { socket.setReuseAddress(isReuseAddr()); if (!socket.isConnected()) { - InetSocketAddress addr = new InetSocketAddress(dnsResolver.resolve(uri), this.getPort()); + InetSocketAddress addr = dnsResolver == null ? InetSocketAddress.createUnresolved(uri.getHost(), getPort()) : new InetSocketAddress(dnsResolver.resolve(uri), this.getPort()); socket.connect(addr, connectTimeout); } From bbb9e0402adc699eee1603c0eef67a7782361ca5 Mon Sep 17 00:00:00 2001 From: artrayme Date: Wed, 20 Oct 2021 15:34:24 +0300 Subject: [PATCH 105/165] update the package version to 1.5.2 --- README.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.markdown b/README.markdown index 6b7ffc61b..851a3cf10 100644 --- a/README.markdown +++ b/README.markdown @@ -31,7 +31,7 @@ To use maven add this dependency to your pom.xml: org.java-websocket Java-WebSocket - 1.5.1 + 1.5.2 ``` @@ -42,7 +42,7 @@ mavenCentral() ``` Then you can just add the latest version to your build. ```xml -compile "org.java-websocket:Java-WebSocket:1.5.1" +compile "org.java-websocket:Java-WebSocket:1.5.2" ``` #### Logging From 9843afaef4b4c86b44860c06cd2bca7c73fe8833 Mon Sep 17 00:00:00 2001 From: artrayme Date: Wed, 20 Oct 2021 15:36:41 +0300 Subject: [PATCH 106/165] dependency for gradle version 7.0+ --- README.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.markdown b/README.markdown index 851a3cf10..0f32fc257 100644 --- a/README.markdown +++ b/README.markdown @@ -44,6 +44,10 @@ Then you can just add the latest version to your build. ```xml compile "org.java-websocket:Java-WebSocket:1.5.2" ``` +Or this option if you use gradle 7.0 and above. +```xml +implementation 'org.java-websocket:Java-WebSocket:1.5.2' +``` #### Logging From ebb70e31b548db08390105587692df4f03b9e009 Mon Sep 17 00:00:00 2001 From: denini08 Date: Thu, 4 Nov 2021 09:25:14 -0300 Subject: [PATCH 107/165] fixing flaky test --- src/test/java/org/java_websocket/issues/Issue677Test.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/test/java/org/java_websocket/issues/Issue677Test.java b/src/test/java/org/java_websocket/issues/Issue677Test.java index d35fed8a3..52dfc94b7 100644 --- a/src/test/java/org/java_websocket/issues/Issue677Test.java +++ b/src/test/java/org/java_websocket/issues/Issue677Test.java @@ -115,7 +115,6 @@ public void onStart() { webSocket0.connectBlocking(); assertTrue("webSocket.isOpen()", webSocket0.isOpen()); webSocket0.close(); - assertTrue("webSocket.isClosing()", webSocket0.isClosing()); countDownLatch0.await(); assertTrue("webSocket.isClosed()", webSocket0.isClosed()); webSocket1.connectBlocking(); From 118b933fce023d74895a4fa2123fab1b86e8a482 Mon Sep 17 00:00:00 2001 From: Antoni Spaanderman <49868160+antonilol@users.noreply.github.com> Date: Sat, 20 Nov 2021 18:07:11 +0100 Subject: [PATCH 108/165] mini comment error --- src/main/example/ExampleClient.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/example/ExampleClient.java b/src/main/example/ExampleClient.java index 089afe822..73b832bea 100644 --- a/src/main/example/ExampleClient.java +++ b/src/main/example/ExampleClient.java @@ -62,7 +62,7 @@ public void onMessage(String message) { @Override public void onClose(int code, String reason, boolean remote) { - // The codecodes are documented in class org.java_websocket.framing.CloseFrame + // The close codes are documented in class org.java_websocket.framing.CloseFrame System.out.println( "Connection closed by " + (remote ? "remote peer" : "us") + " Code: " + code + " Reason: " + reason); @@ -80,4 +80,4 @@ public static void main(String[] args) throws URISyntaxException { c.connect(); } -} \ No newline at end of file +} From 698f47b5a1dc81d4ba8e56ba2cb756ca57908674 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 12 Dec 2021 11:08:50 +0100 Subject: [PATCH 109/165] Reset lastPong in onOpen Fixes #1203 --- .../org/java_websocket/WebSocketImpl.java | 1 + .../java_websocket/issues/Issue1203Test.java | 95 +++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 src/test/java/org/java_websocket/issues/Issue1203Test.java diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index 8a6f96027..8d6464bee 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -752,6 +752,7 @@ private void write(List bufs) { private void open(Handshakedata d) { log.trace("open using draft: {}", draft); readyState = ReadyState.OPEN; + updateLastPong(); try { wsl.onWebsocketOpen(this, d); } catch (RuntimeException e) { diff --git a/src/test/java/org/java_websocket/issues/Issue1203Test.java b/src/test/java/org/java_websocket/issues/Issue1203Test.java new file mode 100644 index 000000000..32ef85235 --- /dev/null +++ b/src/test/java/org/java_websocket/issues/Issue1203Test.java @@ -0,0 +1,95 @@ +package org.java_websocket.issues; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.net.InetSocketAddress; +import java.net.URI; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.CountDownLatch; +import org.java_websocket.WebSocket; +import org.java_websocket.client.WebSocketClient; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.handshake.ServerHandshake; +import org.java_websocket.server.WebSocketServer; +import org.java_websocket.util.SocketUtil; +import org.junit.Assert; +import org.junit.Test; + +public class Issue1203Test { + private final CountDownLatch countServerDownLatch = new CountDownLatch(1); + private final CountDownLatch countClientDownLatch = new CountDownLatch(1); + boolean isClosedCalled = false; + @Test(timeout = 50000) + public void testIssue() throws Exception { + int port = SocketUtil.getAvailablePort(); + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } + + @Override + public void onMessage(WebSocket conn, String message) { + } + + @Override + public void onError(WebSocket conn, Exception ex) { + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + }; + final WebSocketClient client = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + countClientDownLatch.countDown(); + } + + @Override + public void onMessage(String message) { + + } + + @Override + public void onClose(int code, String reason, boolean remote) { + isClosedCalled = true; + } + + @Override + public void onError(Exception ex) { + + } + }; + + server.setConnectionLostTimeout(10); + server.start(); + countServerDownLatch.await(); + + client.setConnectionLostTimeout(10); + Timer timer = new Timer(); + TimerTask task = new TimerTask() { + @Override + public void run() { + try { + client.connectBlocking(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }; + timer.schedule(task, 15000); + countClientDownLatch.await(); + Thread.sleep(30000); + Assert.assertFalse(isClosedCalled); + client.closeBlocking(); + server.stop(); + } +} From 11e3d3cfd96e0b84fb1ef7138f96d7df052844d1 Mon Sep 17 00:00:00 2001 From: Vladimir Date: Sun, 2 Jan 2022 14:23:38 +0200 Subject: [PATCH 110/165] high cpu when channel close exception fix --- src/main/java/org/java_websocket/SSLSocketChannel2.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/java_websocket/SSLSocketChannel2.java b/src/main/java/org/java_websocket/SSLSocketChannel2.java index d9b9a4c31..c0ea28e3f 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel2.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel2.java @@ -385,10 +385,13 @@ public boolean isConnected() { public void close() throws IOException { sslEngine.closeOutbound(); sslEngine.getSession().invalidate(); - if (socketChannel.isOpen()) { - socketChannel.write(wrap(emptybuffer));// FIXME what if not all bytes can be written + try { + if (socketChannel.isOpen()) { + socketChannel.write(wrap(emptybuffer)); + } + } finally { // in case socketChannel.write produce exception - channel will never close + socketChannel.close(); } - socketChannel.close(); } private boolean isHandShakeComplete() { From d9537d69917bb368cbaf8927171eb7d25f534308 Mon Sep 17 00:00:00 2001 From: Oleg Aleksandrov Date: Wed, 23 Mar 2022 23:24:06 +0200 Subject: [PATCH 111/165] Issue-1160 Added java.lang.Error handling in WebSocketImpl and WebSocketServer --- .../org/java_websocket/WebSocketImpl.java | 10 ++ .../server/WebSocketServer.java | 16 +- .../java_websocket/issues/Issue1160Test.java | 159 ++++++++++++++++++ 3 files changed, 183 insertions(+), 2 deletions(-) create mode 100644 src/test/java/org/java_websocket/issues/Issue1160Test.java diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index 8d6464bee..a9fb4a9f9 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -26,6 +26,8 @@ package org.java_websocket; import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; @@ -410,6 +412,14 @@ private void decodeFrames(ByteBuffer socketBuffer) { log.error("Closing due to invalid data in frame", e); wsl.onWebsocketError(this, e); close(e); + } catch (VirtualMachineError | ThreadDeath | LinkageError e) { + log.error("Got fatal error during frame processing"); + throw e; + } catch (Error e) { + log.error("Closing web socket due to an error during frame processing"); + Exception exception = new Exception(e.getMessage()); + wsl.onWebsocketError(this, exception); + close(CloseFrame.UNEXPECTED_CONDITION, exception.getMessage()); } } diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 11073619c..e8e188e30 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -1079,8 +1079,20 @@ public void run() { } } catch (InterruptedException e) { Thread.currentThread().interrupt(); - } catch (RuntimeException e) { - handleFatal(ws, e); + } catch (VirtualMachineError | ThreadDeath | LinkageError e) { + if (ws != null) { + ws.close(); + } + log.error("Got fatal error in worker thread" + getName()); + Exception exception = new Exception(e.getMessage()); + handleFatal(ws, exception); + } catch (Throwable e) { + log.error("Uncaught exception in thread {}: {}", getName(), e); + if (ws != null) { + Exception exception = new Exception(e.getMessage()); + onWebsocketError(ws, exception); + ws.close(); + } } } diff --git a/src/test/java/org/java_websocket/issues/Issue1160Test.java b/src/test/java/org/java_websocket/issues/Issue1160Test.java new file mode 100644 index 000000000..e456132cc --- /dev/null +++ b/src/test/java/org/java_websocket/issues/Issue1160Test.java @@ -0,0 +1,159 @@ +package org.java_websocket.issues; + +import org.java_websocket.WebSocket; +import org.java_websocket.client.WebSocketClient; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.handshake.ServerHandshake; +import org.java_websocket.server.WebSocketServer; +import org.java_websocket.util.SocketUtil; +import org.junit.Assert; +import org.junit.Test; + +import java.net.InetSocketAddress; +import java.net.URI; +import java.nio.ByteBuffer; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; + +public class Issue1160Test { + private final CountDownLatch countServerStart = new CountDownLatch(1); + + static class TestClient extends WebSocketClient { + private final CountDownLatch onCloseLatch; + + public TestClient(URI uri, CountDownLatch latch) { + super(uri); + onCloseLatch = latch; + } + + @Override + public void onOpen(ServerHandshake handshakedata) { + } + + @Override + public void onMessage(String message) { + } + + @Override + public void onClose(int code, String reason, boolean remote) { + onCloseLatch.countDown(); + } + + @Override + public void onError(Exception ex) { + } + } + + + @Test(timeout = 5000) + public void nonFatalErrorShallBeHandledByServer() throws Exception { + final AtomicInteger isServerOnErrorCalledCounter = new AtomicInteger(0); + + int port = SocketUtil.getAvailablePort(); + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } + + @Override + public void onMessage(WebSocket conn, ByteBuffer message) { + throw new Error("Some error"); + } + + @Override + public void onMessage(WebSocket conn, String message) { + throw new Error("Some error"); + } + + @Override + public void onError(WebSocket conn, Exception ex) { + isServerOnErrorCalledCounter.incrementAndGet(); + } + + @Override + public void onStart() { + countServerStart.countDown(); + } + }; + + + server.setConnectionLostTimeout(10); + server.start(); + countServerStart.await(); + + URI uri = new URI("ws://localhost:" + port); + + int CONNECTION_COUNT = 3; + for (int i = 0; i < CONNECTION_COUNT; i++) { + CountDownLatch countClientDownLatch = new CountDownLatch(1); + WebSocketClient client = new TestClient(uri, countClientDownLatch); + client.setConnectionLostTimeout(10); + + client.connectBlocking(); + client.send(new byte[100]); + countClientDownLatch.await(); + client.closeBlocking(); + } + + Assert.assertEquals(CONNECTION_COUNT, isServerOnErrorCalledCounter.get()); + + server.stop(); + } + + @Test(timeout = 5000) + public void fatalErrorShallNotBeHandledByServer() throws Exception { + int port = SocketUtil.getAvailablePort(); + + final CountDownLatch countServerDownLatch = new CountDownLatch(1); + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + countServerDownLatch.countDown(); + } + + @Override + public void onMessage(WebSocket conn, ByteBuffer message) { + throw new OutOfMemoryError("Some error"); + } + + @Override + public void onMessage(WebSocket conn, String message) { + throw new OutOfMemoryError("Some error"); + } + + @Override + public void onError(WebSocket conn, Exception ex) { + } + + @Override + public void onStart() { + countServerStart.countDown(); + } + }; + + + server.setConnectionLostTimeout(10); + server.start(); + countServerStart.await(); + + URI uri = new URI("ws://localhost:" + port); + + CountDownLatch countClientDownLatch = new CountDownLatch(1); + WebSocketClient client = new TestClient(uri, countClientDownLatch); + client.setConnectionLostTimeout(10); + + client.connectBlocking(); + client.send(new byte[100]); + countClientDownLatch.await(); + countServerDownLatch.await(); + Assert.assertTrue(countClientDownLatch.getCount() == 0 && countServerDownLatch.getCount() == 0); + } +} From a2eeaaa9e15986901311af721953f66647855943 Mon Sep 17 00:00:00 2001 From: Oleg Aleksandrov Date: Thu, 24 Mar 2022 22:18:28 +0200 Subject: [PATCH 112/165] Issue-1160 Put whole Error into Exception during Error processing, not just stack trace --- src/main/java/org/java_websocket/server/WebSocketServer.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index e8e188e30..4ee66e252 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -1084,12 +1084,12 @@ public void run() { ws.close(); } log.error("Got fatal error in worker thread" + getName()); - Exception exception = new Exception(e.getMessage()); + Exception exception = new Exception(e); handleFatal(ws, exception); } catch (Throwable e) { log.error("Uncaught exception in thread {}: {}", getName(), e); if (ws != null) { - Exception exception = new Exception(e.getMessage()); + Exception exception = new Exception(e); onWebsocketError(ws, exception); ws.close(); } From a97965dd651f355a89dae9a72c2b5da53bcae716 Mon Sep 17 00:00:00 2001 From: Oleg Aleksandrov Date: Thu, 24 Mar 2022 22:29:21 +0200 Subject: [PATCH 113/165] Issue-1160 Add whole exception not just exception message when converting Erro to Exception --- src/main/java/org/java_websocket/WebSocketImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index a9fb4a9f9..0d4176bfb 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -417,7 +417,7 @@ private void decodeFrames(ByteBuffer socketBuffer) { throw e; } catch (Error e) { log.error("Closing web socket due to an error during frame processing"); - Exception exception = new Exception(e.getMessage()); + Exception exception = new Exception(e); wsl.onWebsocketError(this, exception); close(CloseFrame.UNEXPECTED_CONDITION, exception.getMessage()); } From 7780dbe883b055aa38cad12b4fe389ab05a54ffc Mon Sep 17 00:00:00 2001 From: Oleg Aleksandrov Date: Fri, 25 Mar 2022 12:27:16 +0200 Subject: [PATCH 114/165] Issue-1160 Code clean up, send to client only error type without whole error message --- src/main/java/org/java_websocket/WebSocketImpl.java | 5 ++--- src/main/java/org/java_websocket/server/WebSocketServer.java | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index 0d4176bfb..4869b65a1 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -26,8 +26,6 @@ package org.java_websocket; import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; @@ -419,7 +417,8 @@ private void decodeFrames(ByteBuffer socketBuffer) { log.error("Closing web socket due to an error during frame processing"); Exception exception = new Exception(e); wsl.onWebsocketError(this, exception); - close(CloseFrame.UNEXPECTED_CONDITION, exception.getMessage()); + String errorMessage = "Got error " + e.getClass().getName() + " on the server side"; + close(CloseFrame.UNEXPECTED_CONDITION, errorMessage); } } diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 4ee66e252..6348ca4d3 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -1083,7 +1083,7 @@ public void run() { if (ws != null) { ws.close(); } - log.error("Got fatal error in worker thread" + getName()); + log.error("Got fatal error in worker thread {}", getName()); Exception exception = new Exception(e); handleFatal(ws, exception); } catch (Throwable e) { From b5a97a5d3b10fba734cee53f550f22334dd52576 Mon Sep 17 00:00:00 2001 From: Oleg Aleksandrov Date: Fri, 25 Mar 2022 13:34:54 +0200 Subject: [PATCH 115/165] Issue-1160 Clean up error message in WebSocketImpl if error had been caught --- .idea/.gitignore | 3 +++ src/main/java/org/java_websocket/WebSocketImpl.java | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 .idea/.gitignore diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 000000000..26d33521a --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index 4869b65a1..aad172127 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -417,7 +417,7 @@ private void decodeFrames(ByteBuffer socketBuffer) { log.error("Closing web socket due to an error during frame processing"); Exception exception = new Exception(e); wsl.onWebsocketError(this, exception); - String errorMessage = "Got error " + e.getClass().getName() + " on the server side"; + String errorMessage = "Got error " + e.getClass().getName(); close(CloseFrame.UNEXPECTED_CONDITION, errorMessage); } } From 4920cb106b7ef1306e2e282717a4aacd30f3c89b Mon Sep 17 00:00:00 2001 From: Oleg Aleksandrov Date: Fri, 25 Mar 2022 15:07:07 +0200 Subject: [PATCH 116/165] Issue-1160 Removed unnecessary file, added by accident --- .idea/.gitignore | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 .idea/.gitignore diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 26d33521a..000000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml From ebed7cf857563e8e060e9226fa93dc3948cc6cbf Mon Sep 17 00:00:00 2001 From: Oleg Aleksandrov Date: Fri, 25 Mar 2022 18:07:01 +0200 Subject: [PATCH 117/165] Correct closing web socket connections in case of fatal server stopping --- .../server/WebSocketServer.java | 29 ++++++++++++------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 11073619c..2d3659523 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -248,6 +248,10 @@ public void start() { new Thread(this).start(); } + public void stop(int timeout) throws InterruptedException { + stop(timeout, ""); + } + /** * Closes all connected clients sockets, then closes the underlying ServerSocketChannel, * effectively killing the server socket selectorthread, freeing the port the server was bound to @@ -257,10 +261,11 @@ public void start() { * * @param timeout Specifies how many milliseconds the overall close handshaking may take * altogether before the connections are closed without proper close - * handshaking.
      + * handshaking. + * @param closeMessage Specifies message for remote client
      * @throws InterruptedException Interrupt */ - public void stop(int timeout) throws InterruptedException { + public void stop(int timeout, String closeMessage) throws InterruptedException { if (!isclosed.compareAndSet(false, true)) { // this also makes sure that no further connections will be added to this.connections return; @@ -274,7 +279,7 @@ public void stop(int timeout) throws InterruptedException { } for (WebSocket ws : socketsToClose) { - ws.close(CloseFrame.GOING_AWAY); + ws.close(CloseFrame.GOING_AWAY, closeMessage); } wsf.close(); @@ -680,6 +685,17 @@ private void handleIOException(SelectionKey key, WebSocket conn, IOException ex) private void handleFatal(WebSocket conn, Exception e) { log.error("Shutdown due to fatal error", e); onError(conn, e); + + String causeMessage = e.getCause() != null ? " caused by " + e.getCause().getClass().getName() : ""; + String errorMessage = "Got error on server side: " + e.getClass().getName() + causeMessage; + try { + stop(0, errorMessage); + } catch (InterruptedException e1) { + Thread.currentThread().interrupt(); + log.error("Interrupt during stop", e); + onError(null, e1); + } + //Shutting down WebSocketWorkers, see #222 if (decoders != null) { for (WebSocketWorker w : decoders) { @@ -689,13 +705,6 @@ private void handleFatal(WebSocket conn, Exception e) { if (selectorthread != null) { selectorthread.interrupt(); } - try { - stop(); - } catch (InterruptedException e1) { - Thread.currentThread().interrupt(); - log.error("Interrupt during stop", e); - onError(null, e1); - } } @Override From d00a606d7c48915502c527c4d6ae9747b87caf69 Mon Sep 17 00:00:00 2001 From: Oleg Aleksandrov Date: Fri, 25 Mar 2022 18:40:06 +0200 Subject: [PATCH 118/165] Correct web socket closing: removing unnecessary web socket closing in case of error handling --- src/main/java/org/java_websocket/server/WebSocketServer.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 3641c4ce9..bb8178c25 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -1089,9 +1089,6 @@ public void run() { } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (VirtualMachineError | ThreadDeath | LinkageError e) { - if (ws != null) { - ws.close(); - } log.error("Got fatal error in worker thread {}", getName()); Exception exception = new Exception(e); handleFatal(ws, exception); From a4d23c3fad81523197509b781b132a7a266892b8 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 3 Apr 2022 12:28:32 +0200 Subject: [PATCH 119/165] Fixes #1230 Adjust the handling of RSV1/RSV2/RSV3 in the translateSingleFrame --- .../org/java_websocket/drafts/Draft_6455.java | 51 ++++++++++++++----- .../PerMessageDeflateExtension.java | 13 ++--- 2 files changed, 41 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index 68feb615e..fb2f36ab1 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -115,13 +115,23 @@ public class Draft_6455 extends Draft { /** * Attribute for the used extension in this draft */ - private IExtension extension = new DefaultExtension(); + private IExtension negotiatedExtension = new DefaultExtension(); + + /** + * Attribute for the default extension + */ + private IExtension defaultExtension = new DefaultExtension(); /** * Attribute for all available extension in this draft */ private List knownExtensions; + /** + * Current active extension used to decode messages + */ + private IExtension currentDecodingExtension; + /** * Attribute for the used protocol in this draft */ @@ -241,10 +251,11 @@ public Draft_6455(List inputExtensions, List inputProtoco knownExtensions.addAll(inputExtensions); //We always add the DefaultExtension to implement the normal RFC 6455 specification if (!hasDefault) { - knownExtensions.add(this.knownExtensions.size(), extension); + knownExtensions.add(this.knownExtensions.size(), negotiatedExtension); } knownProtocols.addAll(inputProtocols); maxFrameSize = inputMaxFrameSize; + currentDecodingExtension = null; } @Override @@ -259,9 +270,9 @@ public HandshakeState acceptHandshakeAsServer(ClientHandshake handshakedata) String requestedExtension = handshakedata.getFieldValue(SEC_WEB_SOCKET_EXTENSIONS); for (IExtension knownExtension : knownExtensions) { if (knownExtension.acceptProvidedExtensionAsServer(requestedExtension)) { - extension = knownExtension; + negotiatedExtension = knownExtension; extensionState = HandshakeState.MATCHED; - log.trace("acceptHandshakeAsServer - Matching extension found: {}", extension); + log.trace("acceptHandshakeAsServer - Matching extension found: {}", negotiatedExtension); break; } } @@ -316,9 +327,9 @@ public HandshakeState acceptHandshakeAsClient(ClientHandshake request, ServerHan String requestedExtension = response.getFieldValue(SEC_WEB_SOCKET_EXTENSIONS); for (IExtension knownExtension : knownExtensions) { if (knownExtension.acceptProvidedExtensionAsClient(requestedExtension)) { - extension = knownExtension; + negotiatedExtension = knownExtension; extensionState = HandshakeState.MATCHED; - log.trace("acceptHandshakeAsClient - Matching extension found: {}", extension); + log.trace("acceptHandshakeAsClient - Matching extension found: {}", negotiatedExtension); break; } } @@ -337,7 +348,7 @@ public HandshakeState acceptHandshakeAsClient(ClientHandshake request, ServerHan * @return the extension which is used or null, if handshake is not yet done */ public IExtension getExtension() { - return extension; + return negotiatedExtension; } /** @@ -562,8 +573,20 @@ private Framedata translateSingleFrame(ByteBuffer buffer) frame.setRSV3(rsv3); payload.flip(); frame.setPayload(payload); - getExtension().isFrameValid(frame); - getExtension().decodeFrame(frame); + if (frame.getOpcode() != Opcode.CONTINUOUS) { + // Prioritize the negotiated extension + if (frame.isRSV1() ||frame.isRSV2() || frame.isRSV3()) { + currentDecodingExtension = getExtension(); + } else { + // No encoded message, so we can use the default one + currentDecodingExtension = defaultExtension; + } + } + if (currentDecodingExtension == null) { + currentDecodingExtension = defaultExtension; + } + currentDecodingExtension.isFrameValid(frame); + currentDecodingExtension.decodeFrame(frame); if (log.isTraceEnabled()) { log.trace("afterDecoding({}): {}", frame.getPayloadData().remaining(), (frame.getPayloadData().remaining() > 1000 ? "too big to display" @@ -780,10 +803,10 @@ public List createFrames(String text, boolean mask) { @Override public void reset() { incompleteframe = null; - if (extension != null) { - extension.reset(); + if (negotiatedExtension != null) { + negotiatedExtension.reset(); } - extension = new DefaultExtension(); + negotiatedExtension = new DefaultExtension(); protocol = null; } @@ -1116,7 +1139,7 @@ public boolean equals(Object o) { if (maxFrameSize != that.getMaxFrameSize()) { return false; } - if (extension != null ? !extension.equals(that.getExtension()) : that.getExtension() != null) { + if (negotiatedExtension != null ? !negotiatedExtension.equals(that.getExtension()) : that.getExtension() != null) { return false; } return protocol != null ? protocol.equals(that.getProtocol()) : that.getProtocol() == null; @@ -1124,7 +1147,7 @@ public boolean equals(Object o) { @Override public int hashCode() { - int result = extension != null ? extension.hashCode() : 0; + int result = negotiatedExtension != null ? negotiatedExtension.hashCode() : 0; result = 31 * result + (protocol != null ? protocol.hashCode() : 0); result = 31 * result + (maxFrameSize ^ (maxFrameSize >>> 32)); return result; diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index 824ceb68e..f24f9b6c9 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -142,15 +142,15 @@ public void decodeFrame(Framedata inputFrame) throws InvalidDataException { return; } + if (!inputFrame.isRSV1() && inputFrame.getOpcode() != Opcode.CONTINUOUS) { + return; + } + // RSV1 bit must be set only for the first frame. if (inputFrame.getOpcode() == Opcode.CONTINUOUS && inputFrame.isRSV1()) { throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "RSV1 bit can only be set for the first frame."); } - // If rsv1 is not set, we dont have a compressed message - if (!inputFrame.isRSV1()) { - return; - } // Decompressed output buffer. ByteArrayOutputStream output = new ByteArrayOutputStream(); @@ -181,11 +181,6 @@ We can check the getRemaining() method to see whether the data we supplied has b throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, e.getMessage()); } - // RSV1 bit must be cleared after decoding, so that other extensions don't throw an exception. - if (inputFrame.isRSV1()) { - ((DataFrame) inputFrame).setRSV1(false); - } - // Set frames payload to the new decompressed data. ((FramedataImpl1) inputFrame) .setPayload(ByteBuffer.wrap(output.toByteArray(), 0, output.size())); From 8f1f8e4462b8939f4f1706681d934658c6794bc4 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 3 Apr 2022 12:30:50 +0200 Subject: [PATCH 120/165] Fix formatting --- src/main/java/org/java_websocket/drafts/Draft_6455.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index fb2f36ab1..eb4879976 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -575,7 +575,7 @@ private Framedata translateSingleFrame(ByteBuffer buffer) frame.setPayload(payload); if (frame.getOpcode() != Opcode.CONTINUOUS) { // Prioritize the negotiated extension - if (frame.isRSV1() ||frame.isRSV2() || frame.isRSV3()) { + if (frame.isRSV1() || frame.isRSV2() || frame.isRSV3()) { currentDecodingExtension = getExtension(); } else { // No encoded message, so we can use the default one From 5ff6ede8897397c9e8d12c6335002993974c6ac0 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sat, 9 Apr 2022 20:03:30 +0200 Subject: [PATCH 121/165] Update changelog and readme --- CHANGELOG.md | 21 +++++++++++++++++++++ README.markdown | 6 +++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9bbbe7b91..11dc0358e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,26 @@ # Change log +## Version Release 1.5.3 (2022/04/09) + +#### Bugs Fixed + +* [Issue 1230](https://github.com/TooTallNate/Java-WebSocket/issues/1230) - CONTINUOUS should be decoded depending on the first frame ([PR 1232 ](https://github.com/TooTallNate/Java-WebSocket/pull/1232) by [@marci4](https://github.com/marci4)) +* [Issue 1203](https://github.com/TooTallNate/Java-WebSocket/issues/1203) - Lost connection detection not working on delayed connect-Call ([PR 1204 ](https://github.com/TooTallNate/Java-WebSocket/pull/1204) by [@marci4](https://github.com/marci4)) +* [Issue 1164](https://github.com/TooTallNate/Java-WebSocket/issues/1164) - [Android & Node.js Server] Problem using PerMessageDeflateExtension with custom ping/pong messages ? ([PR 1165 ](https://github.com/TooTallNate/Java-WebSocket/pull/1165) by [@marci4](https://github.com/marci4)) +* [Issue 1160](https://github.com/TooTallNate/Java-WebSocket/issues/1160) - `WebSocketWorker` does not handle `Throwable` ([PR 1223 ](https://github.com/TooTallNate/Java-WebSocket/pull/1223) by [@Serpion-ua](https://github.com/Serpion-ua)) +* [Issue 1142](https://github.com/TooTallNate/Java-WebSocket/issues/1142) - Verifying server certificate ([PR 1143 ](https://github.com/TooTallNate/Java-WebSocket/pull/1143) by [@marci4](https://github.com/marci4)) +* [PR 1227](https://github.com/TooTallNate/Java-WebSocket/pull/1227) - Correct web socket closing, by [@Serpion-ua](https://github.com/Serpion-ua) +* [PR 1223](https://github.com/TooTallNate/Java-WebSocket/pull/1223) - Issue-1160 Added java.lang.Error handling in WebSocketImpl and WebSocketServer, by [@Serpion-ua](https://github.com/Serpion-ua) +* [PR 1212](https://github.com/TooTallNate/Java-WebSocket/pull/1212) - high cpu when channel close exception fix, by [@Adeptius](https://github.com/Adeptius) + +#### New Features + +* [PR 1185](https://github.com/TooTallNate/Java-WebSocket/pull/1185) - Added support unresolved socket addresses, by [@vtsykun](https://github.com/vtsykun) + +In this release 5 issues and 8 pull requests were closed. + +############################################################################### + ## Version Release 1.5.2 (2021/04/05) #### Bugs Fixed diff --git a/README.markdown b/README.markdown index 0f32fc257..9ef01722c 100644 --- a/README.markdown +++ b/README.markdown @@ -31,7 +31,7 @@ To use maven add this dependency to your pom.xml: org.java-websocket Java-WebSocket - 1.5.2 + 1.5.3 ``` @@ -42,11 +42,11 @@ mavenCentral() ``` Then you can just add the latest version to your build. ```xml -compile "org.java-websocket:Java-WebSocket:1.5.2" +compile "org.java-websocket:Java-WebSocket:1.5.3" ``` Or this option if you use gradle 7.0 and above. ```xml -implementation 'org.java-websocket:Java-WebSocket:1.5.2' +implementation 'org.java-websocket:Java-WebSocket:1.5.3' ``` #### Logging From a81d0b55d13eb82ff69c6294b336c5fb7aca8e29 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sat, 9 Apr 2022 20:05:41 +0200 Subject: [PATCH 122/165] Update to next version 1.5.4 --- build.gradle | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index e8be125e9..149f1e3e5 100644 --- a/build.gradle +++ b/build.gradle @@ -10,7 +10,7 @@ repositories { } group = 'org.java-websocket' -version = '1.5.3-SNAPSHOT' +version = '1.5.4-SNAPSHOT' sourceCompatibility = 1.7 targetCompatibility = 1.7 diff --git a/pom.xml b/pom.xml index 52f26cd29..c72c92c65 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.java-websocket Java-WebSocket jar - 1.5.3-SNAPSHOT + 1.5.4-SNAPSHOT Java-WebSocket A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket From 5d4d52792687918a1c052a26dba16d0699c65609 Mon Sep 17 00:00:00 2001 From: PhilipRoman Date: Mon, 4 Jul 2022 18:56:29 +0300 Subject: [PATCH 123/165] Replace usages of deprecated constructor Integer(String) with Integer.parseInt --- src/main/java/org/java_websocket/drafts/Draft.java | 2 +- .../java/org/java_websocket/example/AutobahnClientTest.java | 4 ++-- .../org/java_websocket/example/AutobahnSSLServerTest.java | 2 +- .../java/org/java_websocket/example/AutobahnServerTest.java | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/java_websocket/drafts/Draft.java b/src/main/java/org/java_websocket/drafts/Draft.java index 7ba1ee4b3..2cda1e5ca 100644 --- a/src/main/java/org/java_websocket/drafts/Draft.java +++ b/src/main/java/org/java_websocket/drafts/Draft.java @@ -331,7 +331,7 @@ int readVersion(Handshakedata handshakedata) { if (vers.length() > 0) { int v; try { - v = new Integer(vers.trim()); + v = Integer.parseInt(vers.trim()); return v; } catch (NumberFormatException e) { return -1; diff --git a/src/test/java/org/java_websocket/example/AutobahnClientTest.java b/src/test/java/org/java_websocket/example/AutobahnClientTest.java index 9a3ce5235..5f726ddfe 100644 --- a/src/test/java/org/java_websocket/example/AutobahnClientTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnClientTest.java @@ -91,8 +91,8 @@ public static void main(String[] args) { String[] spl = line.split(" "); if (line.startsWith("r")) { if (spl.length == 3) { - start = new Integer(spl[1]); - end = new Integer(spl[2]); + start = Integer.parseInt(spl[1]); + end = Integer.parseInt(spl[2]); } if (start != null && end != null) { if (start > end) { diff --git a/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java b/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java index 7d3fa79b7..cc6f5ef7b 100644 --- a/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java @@ -90,7 +90,7 @@ public void onMessage(WebSocket conn, ByteBuffer blob) { public static void main(String[] args) throws UnknownHostException { int port; try { - port = new Integer(args[0]); + port = Integer.parseInt(args[0]); } catch (Exception e) { System.out.println("No port specified. Defaulting to 9003"); port = 9003; diff --git a/src/test/java/org/java_websocket/example/AutobahnServerTest.java b/src/test/java/org/java_websocket/example/AutobahnServerTest.java index 6bfaf5871..b0b9bc847 100644 --- a/src/test/java/org/java_websocket/example/AutobahnServerTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnServerTest.java @@ -90,13 +90,13 @@ public void onMessage(WebSocket conn, ByteBuffer blob) { public static void main(String[] args) throws UnknownHostException { int port, limit; try { - port = new Integer(args[0]); + port = Integer.parseInt(args[0]); } catch (Exception e) { System.out.println("No port specified. Defaulting to 9003"); port = 9003; } try { - limit = new Integer(args[1]); + limit = Integer.parseInt(args[1]); } catch (Exception e) { System.out.println("No limit specified. Defaulting to MaxInteger"); limit = Integer.MAX_VALUE; From 5eeb03daee83aa6e99da746e4e96899940c6bb86 Mon Sep 17 00:00:00 2001 From: Bowen Cai Date: Fri, 10 Feb 2023 18:59:37 -0600 Subject: [PATCH 124/165] websocketimpl: avoid string copy unless logging trace message --- src/main/java/org/java_websocket/WebSocketImpl.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index aad172127..c2cd223b9 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -224,10 +224,11 @@ public WebSocketImpl(WebSocketListener listener, Draft draft) { */ public void decode(ByteBuffer socketBuffer) { assert (socketBuffer.hasRemaining()); - log.trace("process({}): ({})", socketBuffer.remaining(), - (socketBuffer.remaining() > 1000 ? "too big to display" - : new String(socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining()))); - + if (log.isTraceEnabled()) { + log.trace("process({}): ({})", socketBuffer.remaining(), + (socketBuffer.remaining() > 1000 ? "too big to display" + : new String(socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining()))); + } if (readyState != ReadyState.NOT_YET_CONNECTED) { if (readyState == ReadyState.OPEN) { decodeFrames(socketBuffer); From e90af48d8974cc946e6994f58bd05a49339bb1d7 Mon Sep 17 00:00:00 2001 From: Anthony Vanelverdinghe Date: Thu, 23 Feb 2023 17:53:04 +0100 Subject: [PATCH 125/165] Make Base64Test independent of JDK --- .../java/org/java_websocket/util/Base64Test.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/test/java/org/java_websocket/util/Base64Test.java b/src/test/java/org/java_websocket/util/Base64Test.java index 41122d779..4382aab60 100644 --- a/src/test/java/org/java_websocket/util/Base64Test.java +++ b/src/test/java/org/java_websocket/util/Base64Test.java @@ -41,16 +41,22 @@ public void testEncodeBytes() throws IOException { Assert.assertEquals("", Base64.encodeBytes(new byte[0])); Assert.assertEquals("QHE=", Base64.encodeBytes(new byte[]{49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 2, 2, 0)); - Assert.assertEquals("H4sIAAAAAAAAADMEALfv3IMBAAAA", + assertGzipEncodedBytes("H4sIAAAAAAAA", "MEALfv3IMBAAAA", Base64.encodeBytes(new byte[]{49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 0, 1, 6)); - Assert.assertEquals("H4sIAAAAAAAAAHMoBABQHKKWAgAAAA==", + assertGzipEncodedBytes("H4sIAAAAAAAA", "MoBABQHKKWAgAAAA==", Base64.encodeBytes(new byte[]{49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 2, 2, 18)); Assert.assertEquals("F63=", Base64.encodeBytes(new byte[]{49, 121, 64, 113, 63, 43, -24, 62, 4, 48}, 2, 2, 32)); - Assert.assertEquals("6sg7---------6Bc0-0F699L-V----==", + assertGzipEncodedBytes("6sg7--------", "Bc0-0F699L-V----==", Base64.encodeBytes(new byte[]{49, 121, 64, 113, 63, 43, -24, 62, 4, 48}, 2, 2, 34)); } + // see https://bugs.openjdk.org/browse/JDK-8253142 + private void assertGzipEncodedBytes(String expectedPrefix, String expectedSuffix, String actual) { + Assert.assertTrue(actual.startsWith(expectedPrefix)); + Assert.assertTrue(actual.endsWith(expectedSuffix)); + } + @Test public void testEncodeBytes2() throws IOException { thrown.expect(IllegalArgumentException.class); From b79a1a46f050d1023daa3cee8476fbcd23e6cc70 Mon Sep 17 00:00:00 2001 From: Anthony Vanelverdinghe Date: Thu, 23 Feb 2023 18:01:03 +0100 Subject: [PATCH 126/165] Modularize --- pom.xml | 48 +++++++++++++++++++++++++-------- src/main/java9/module-info.java | 19 +++++++++++++ 2 files changed, 56 insertions(+), 11 deletions(-) create mode 100644 src/main/java9/module-info.java diff --git a/pom.xml b/pom.xml index c72c92c65..3edf46620 100644 --- a/pom.xml +++ b/pom.xml @@ -11,21 +11,21 @@ https://github.com/TooTallNate/Java-WebSocket UTF-8 - 1.7.25 + 2.0.6 4.12 20180813 - 4.3.1 + 6.4.0 3.1.1 - 3.7.0 + 3.10.1 1.6 - 3.0.2 - 2.10.3 - 3.1.0 - 3.0.0 + 3.3.0 + 3.5.0 + 3.4.1 + 3.2.1 1.6.8 org.java-websocket:Java-WebSocket marci4-github @@ -86,10 +86,12 @@ @@ -99,10 +101,33 @@ org.apache.maven.plugins maven-compiler-plugin ${maven.compiler.plugin.version} - - 1.7 - 1.7 - + + + default-compile + + compile + + + 1.7 + 1.7 + + + + + module-compile + compile + + compile + + + 9 + + ${project.basedir}/src/main/java9 + + true + + +
      org.apache.maven.plugins @@ -183,6 +208,7 @@ ${maven.checkstyle.plugin.version} google_checks.xml + **/module-info.java warning checkstyle-suppressions.xml checkstyle.suppressions.file diff --git a/src/main/java9/module-info.java b/src/main/java9/module-info.java new file mode 100644 index 000000000..35ad67c89 --- /dev/null +++ b/src/main/java9/module-info.java @@ -0,0 +1,19 @@ +/** + * This module implements a barebones WebSocket server and client. + */ +module org.java_websocket { + requires transitive org.slf4j; + + exports org.java_websocket; + exports org.java_websocket.client; + exports org.java_websocket.drafts; + exports org.java_websocket.enums; + exports org.java_websocket.exceptions; + exports org.java_websocket.extensions; + exports org.java_websocket.extensions.permessage_deflate; + exports org.java_websocket.framing; + exports org.java_websocket.handshake; + exports org.java_websocket.interfaces; + exports org.java_websocket.protocols; + exports org.java_websocket.server; +} From 11c52125a77536f3cf1030e2a7720c12a21ece39 Mon Sep 17 00:00:00 2001 From: Anthony Vanelverdinghe Date: Tue, 7 Mar 2023 18:02:06 +0100 Subject: [PATCH 127/165] Use release parameter --- pom.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 3edf46620..c1233c88b 100644 --- a/pom.xml +++ b/pom.xml @@ -108,8 +108,7 @@ compile - 1.7 - 1.7 + 7 From 8fbd5b85967d364275309bc5e0e3d74ae1ca264c Mon Sep 17 00:00:00 2001 From: Anthony Vanelverdinghe Date: Tue, 7 Mar 2023 18:02:28 +0100 Subject: [PATCH 128/165] Update GitHub workflows to JDK 17 --- .github/workflows/checkstyle.yml | 10 +++++----- .github/workflows/ci.yml | 16 ++++++++-------- .github/workflows/sonar.yml | 8 ++++---- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/.github/workflows/checkstyle.yml b/.github/workflows/checkstyle.yml index 8b74e7db5..1cae4f3c8 100644 --- a/.github/workflows/checkstyle.yml +++ b/.github/workflows/checkstyle.yml @@ -1,5 +1,5 @@ # This workflow will build a Java project with Maven -# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven name: Java Code Style Check with Maven @@ -11,10 +11,10 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 + - uses: actions/checkout@v3 + - name: Set up JDK 17 + uses: actions/setup-java@v3 with: - java-version: 1.8 + java-version: '17' - name: Code Style Check run: mvn -B checkstyle:check --file pom.xml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7c81f7ff0..eccc203e8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,21 +6,21 @@ jobs: Build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 + - uses: actions/checkout@v3 + - name: Set up JDK 17 + uses: actions/setup-java@v3 with: - java-version: 1.8 + java-version: '17' - name: Build run: mvn -DskipTests package --file pom.xml Test: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 + - uses: actions/checkout@v3 + - name: Set up JDK 17 + uses: actions/setup-java@v3 with: - java-version: 1.8 + java-version: '17' - name: Test run: mvn test --file pom.xml diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index 82fdeb1b0..8872ddaf9 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -8,13 +8,13 @@ jobs: name: SonarQube runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 with: fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - - name: Set up JDK 11 - uses: actions/setup-java@v1 + - name: Set up JDK 17 + uses: actions/setup-java@v3 with: - java-version: 11 + java-version: '17' - name: Cache SonarCloud packages uses: actions/cache@v1 with: From 3e8d3c51daf8d5f49b7d04025d822c9bd503f032 Mon Sep 17 00:00:00 2001 From: Anthony Vanelverdinghe Date: Tue, 7 Mar 2023 20:43:42 +0100 Subject: [PATCH 129/165] Add distribution attribute to GitHub workflows --- .github/workflows/checkstyle.yml | 1 + .github/workflows/ci.yml | 2 ++ .github/workflows/sonar.yml | 1 + 3 files changed, 4 insertions(+) diff --git a/.github/workflows/checkstyle.yml b/.github/workflows/checkstyle.yml index 1cae4f3c8..197b3f3aa 100644 --- a/.github/workflows/checkstyle.yml +++ b/.github/workflows/checkstyle.yml @@ -16,5 +16,6 @@ jobs: uses: actions/setup-java@v3 with: java-version: '17' + distribution: 'temurin' - name: Code Style Check run: mvn -B checkstyle:check --file pom.xml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eccc203e8..fb9ad601e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,6 +11,7 @@ jobs: uses: actions/setup-java@v3 with: java-version: '17' + distribution: 'temurin' - name: Build run: mvn -DskipTests package --file pom.xml @@ -22,5 +23,6 @@ jobs: uses: actions/setup-java@v3 with: java-version: '17' + distribution: 'temurin' - name: Test run: mvn test --file pom.xml diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index 8872ddaf9..538a5665b 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -15,6 +15,7 @@ jobs: uses: actions/setup-java@v3 with: java-version: '17' + distribution: 'temurin' - name: Cache SonarCloud packages uses: actions/cache@v1 with: From 12a7bb598c0ce6274a6c023a12f022b9c068efd0 Mon Sep 17 00:00:00 2001 From: Marcel Prestel Date: Fri, 14 Jul 2023 16:08:30 +0000 Subject: [PATCH 130/165] Remove snapshot badge --- README.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/README.markdown b/README.markdown index 9ef01722c..3adb36f39 100644 --- a/README.markdown +++ b/README.markdown @@ -3,7 +3,6 @@ Java WebSockets [![Build Status](https://travis-ci.org/marci4/Java-WebSocket-Dev.svg?branch=master)](https://travis-ci.org/marci4/Java-WebSocket-Dev) [![Javadocs](https://www.javadoc.io/badge/org.java-websocket/Java-WebSocket.svg)](https://www.javadoc.io/doc/org.java-websocket/Java-WebSocket) [![Maven Central](https://img.shields.io/maven-central/v/org.java-websocket/Java-WebSocket.svg)](https://mvnrepository.com/artifact/org.java-websocket/Java-WebSocket) -[![Sonatype Nexus (Snapshots)](https://img.shields.io/nexus/s/https/oss.sonatype.org/org.java-websocket/Java-WebSocket.svg)](https://oss.sonatype.org/content/repositories/snapshots/org/java-websocket/Java-WebSocket/) This repository contains a barebones WebSocket server and client implementation written in 100% Java. The underlying classes are implemented `java.nio`, which allows for a From 55588f124310e3c659a256d5031b7834f9757f1d Mon Sep 17 00:00:00 2001 From: marci4 Date: Thu, 20 Jul 2023 22:23:25 +0200 Subject: [PATCH 131/165] Update changelog --- CHANGELOG.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 11dc0358e..6a2ace063 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Change log +############################################################################### + +## Version Release 1.5.4 (2023/07/20) + +#### New Features + +* [Issue 1308](https://github.com/TooTallNate/Java-WebSocket/issues/1308) - Add support for Java modules ([PR 1309](https://github.com/TooTallNate/Java-WebSocket/pull/1309)) +* [PR 1309](https://github.com/TooTallNate/Java-WebSocket/pull/1309) - Add support for Java modules + +#### Refactoring + +* [PR 1259](https://github.com/TooTallNate/Java-WebSocket/pull/1259) - Replace usages of deprecated constructor Integer(String) with Integer.parseInt + +In this release 1 issue and 2 pull requests were closed. + +############################################################################### + ## Version Release 1.5.3 (2022/04/09) #### Bugs Fixed From d33bedd79a018e0405038b767687ab36284495a9 Mon Sep 17 00:00:00 2001 From: marci4 Date: Thu, 20 Jul 2023 22:24:56 +0200 Subject: [PATCH 132/165] Increase version to 1.5.5 --- pom.xml | 80 ++++++++------------------------------------------------- 1 file changed, 11 insertions(+), 69 deletions(-) diff --git a/pom.xml b/pom.xml index c1233c88b..f5dd46c16 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.java-websocket Java-WebSocket jar - 1.5.4-SNAPSHOT + 1.5.5-SNAPSHOT Java-WebSocket A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket @@ -26,7 +26,7 @@ 3.5.0 3.4.1 3.2.1 - 1.6.8 + 1.6.13 org.java-websocket:Java-WebSocket marci4-github https://sonarcloud.io @@ -156,6 +156,10 @@ org.apache.maven.plugins maven-javadoc-plugin ${maven.javadoc.plugin.version} + + src/main/java + -Xdoclint:none + attach-javadocs @@ -182,6 +186,7 @@ + org.sonatype.plugins @@ -250,7 +255,7 @@ true ossrh - true + false https://oss.sonatype.org/ @@ -261,72 +266,9 @@ org.apache.maven.plugins maven-javadoc-plugin - - - - - - full - - false - - - - org.slf4j - slf4j-simple - - - - - - biz.aQute.bnd - bnd-maven-plugin - - - org.apache.maven.plugins - maven-shade-plugin - - - package - - shade - - - true - with-dependencies - - - simplelogger.properties - src\main\example\simplelogger.properties - - - - - - - - org.apache.maven.plugins - maven-source-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - test-jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - org.apache.maven.plugins - maven-gpg-plugin + + -Xdoclint:none + From 5176255f5d846c9bdfefbe280d67d4a30c8438d4 Mon Sep 17 00:00:00 2001 From: Skyler Date: Tue, 25 Jul 2023 10:55:49 +0000 Subject: [PATCH 133/165] Bump version in install instructions --- README.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.markdown b/README.markdown index 3adb36f39..152facd1f 100644 --- a/README.markdown +++ b/README.markdown @@ -30,7 +30,7 @@ To use maven add this dependency to your pom.xml: org.java-websocket Java-WebSocket - 1.5.3 + 1.5.4 ``` @@ -41,11 +41,11 @@ mavenCentral() ``` Then you can just add the latest version to your build. ```xml -compile "org.java-websocket:Java-WebSocket:1.5.3" +compile "org.java-websocket:Java-WebSocket:1.5.4" ``` Or this option if you use gradle 7.0 and above. ```xml -implementation 'org.java-websocket:Java-WebSocket:1.5.3' +implementation 'org.java-websocket:Java-WebSocket:1.5.4' ``` #### Logging From 85b4999980f8cfbbf464dfe6663f48d182c11e87 Mon Sep 17 00:00:00 2001 From: PhilipRoman Date: Wed, 1 Nov 2023 16:55:44 +0200 Subject: [PATCH 134/165] Fix multiple issues related to reconnect --- .../org/java_websocket/client/WebSocketClient.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 4277c2209..893c8afbf 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -343,10 +343,12 @@ private void reset() { closeBlocking(); if (writeThread != null) { this.writeThread.interrupt(); + this.writeThread.join(); this.writeThread = null; } if (connectReadThread != null) { this.connectReadThread.interrupt(); + this.connectReadThread.join(); this.connectReadThread = null; } this.draft.reset(); @@ -505,6 +507,14 @@ public void run() { throw e; } + if (writeThread != null) { + writeThread.interrupt(); + try { + writeThread.join(); + } catch (InterruptedException e) { + /* ignore */ + } + } writeThread = new Thread(new WebsocketWriteThread(this)); writeThread.start(); @@ -523,7 +533,6 @@ public void run() { onError(e); engine.closeConnection(CloseFrame.ABNORMAL_CLOSE, e.getMessage()); } - connectReadThread = null; } private void upgradeSocketToSSL() @@ -801,7 +810,6 @@ public void run() { handleIOException(e); } finally { closeSocket(); - writeThread = null; } } From 9055e826abff585fbb289964f3d6bf3caab9e4cd Mon Sep 17 00:00:00 2001 From: HappyHacker123 Date: Fri, 10 Nov 2023 16:50:32 +0800 Subject: [PATCH 135/165] Fix the inconsistent version between dependency in pom.xml and build.gradle. --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 149f1e3e5..c0eb210aa 100644 --- a/build.gradle +++ b/build.gradle @@ -35,8 +35,8 @@ publishing { } dependencies { - implementation group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25' - testImplementation group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25' + implementation group: 'org.slf4j', name: 'slf4j-api', version: '2.0.6' + testImplementation group: 'org.slf4j', name: 'slf4j-simple', version: '2.0.6' testImplementation group: 'junit', name: 'junit', version: '4.12' testImplementation group: 'org.json', name: 'json', version: '20180813' } From 43c9693c7bbaa62512583ad29a53814cd2ec358c Mon Sep 17 00:00:00 2001 From: marci4 Date: Mon, 18 Dec 2023 23:16:20 +0100 Subject: [PATCH 136/165] Update changelog for 1.5.5 --- CHANGELOG.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a2ace063..fb44daa45 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Change log +############################################################################### +## Version Release 1.5.5 (2023/12/18) + +#### Bugs Fixed + +* [Issue 1365](https://github.com/TooTallNate/Java-WebSocket/issues/1365) - Hang on reconnectBlocking +* [Issue 1364](https://github.com/TooTallNate/Java-WebSocket/issues/1364) - NPE during reconnect ([PR 1367](https://github.com/TooTallNate/Java-WebSocket/pull/1367)) +* [PR 1367](https://github.com/TooTallNate/Java-WebSocket/pull/1367) - Fix multiple issues related to reconnect + +In this release 2 issues and 1 pull request were closed. + ############################################################################### ## Version Release 1.5.4 (2023/07/20) From 4a6e1c4a15f347cd51054b2dfaaef4de10ad2abf Mon Sep 17 00:00:00 2001 From: marci4 Date: Mon, 18 Dec 2023 23:21:59 +0100 Subject: [PATCH 137/165] Increase version to 1.5.6 --- build.gradle | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index c0eb210aa..5138b1a74 100644 --- a/build.gradle +++ b/build.gradle @@ -10,7 +10,7 @@ repositories { } group = 'org.java-websocket' -version = '1.5.4-SNAPSHOT' +version = '1.5.6-SNAPSHOT' sourceCompatibility = 1.7 targetCompatibility = 1.7 diff --git a/pom.xml b/pom.xml index f5dd46c16..74f29a166 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.java-websocket Java-WebSocket jar - 1.5.5-SNAPSHOT + 1.5.6-SNAPSHOT Java-WebSocket A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket From 1ecae0e3a692eb076b8c6dd8de6f3120650c8597 Mon Sep 17 00:00:00 2001 From: PhilipRoman Date: Sat, 13 Jan 2024 09:48:14 +0200 Subject: [PATCH 138/165] Replace with in javadocs --- .../org/java_websocket/WebSocketAdapter.java | 2 +- .../org/java_websocket/WebSocketListener.java | 32 +++++++++---------- .../server/WebSocketServer.java | 12 +++---- .../java/org/java_websocket/util/Base64.java | 12 +++---- 4 files changed, 29 insertions(+), 29 deletions(-) diff --git a/src/main/java/org/java_websocket/WebSocketAdapter.java b/src/main/java/org/java_websocket/WebSocketAdapter.java index e60215f8c..d06ca6f91 100644 --- a/src/main/java/org/java_websocket/WebSocketAdapter.java +++ b/src/main/java/org/java_websocket/WebSocketAdapter.java @@ -99,7 +99,7 @@ public void onWebsocketPong(WebSocket conn, Framedata f) { * Default implementation for onPreparePing, returns a (cached) PingFrame that has no application * data. * - * @param conn The WebSocket connection from which the ping frame will be sent. + * @param conn The WebSocket connection from which the ping frame will be sent. * @return PingFrame to be sent. * @see org.java_websocket.WebSocketListener#onPreparePing(WebSocket) */ diff --git a/src/main/java/org/java_websocket/WebSocketListener.java b/src/main/java/org/java_websocket/WebSocketListener.java index 6d2bfdd92..f0b21d526 100644 --- a/src/main/java/org/java_websocket/WebSocketListener.java +++ b/src/main/java/org/java_websocket/WebSocketListener.java @@ -38,8 +38,8 @@ import org.java_websocket.handshake.ServerHandshakeBuilder; /** - * Implemented by WebSocketClient and WebSocketServer. The methods within are - * called by WebSocket. Almost every method takes a first parameter conn which represents + * Implemented by WebSocketClient and WebSocketServer. The methods within are + * called by WebSocket. Almost every method takes a first parameter conn which represents * the source of the respective event. */ public interface WebSocketListener { @@ -86,7 +86,7 @@ void onWebsocketHandshakeSentAsClient(WebSocket conn, ClientHandshake request) /** * Called when an entire text frame has been received. Do whatever you want here... * - * @param conn The WebSocket instance this event is occurring on. + * @param conn The WebSocket instance this event is occurring on. * @param message The UTF-8 decoded message that was received. */ void onWebsocketMessage(WebSocket conn, String message); @@ -94,7 +94,7 @@ void onWebsocketHandshakeSentAsClient(WebSocket conn, ClientHandshake request) /** * Called when an entire binary frame has been received. Do whatever you want here... * - * @param conn The WebSocket instance this event is occurring on. + * @param conn The WebSocket instance this event is occurring on. * @param blob The binary message that was received. */ void onWebsocketMessage(WebSocket conn, ByteBuffer blob); @@ -103,16 +103,16 @@ void onWebsocketHandshakeSentAsClient(WebSocket conn, ClientHandshake request) * Called after onHandshakeReceived returns true. Indicates that a complete * WebSocket connection has been established, and we are ready to send/receive data. * - * @param conn The WebSocket instance this event is occurring on. + * @param conn The WebSocket instance this event is occurring on. * @param d The handshake of the websocket instance */ void onWebsocketOpen(WebSocket conn, Handshakedata d); /** - * Called after WebSocket#close is explicity called, or when the other end of the + * Called after WebSocket#close is explicity called, or when the other end of the * WebSocket connection is closed. * - * @param ws The WebSocket instance this event is occurring on. + * @param ws The WebSocket instance this event is occurring on. * @param code The codes can be looked up here: {@link CloseFrame} * @param reason Additional information string * @param remote Returns whether or not the closing of the connection was initiated by the remote @@ -123,7 +123,7 @@ void onWebsocketHandshakeSentAsClient(WebSocket conn, ClientHandshake request) /** * Called as soon as no further frames are accepted * - * @param ws The WebSocket instance this event is occurring on. + * @param ws The WebSocket instance this event is occurring on. * @param code The codes can be looked up here: {@link CloseFrame} * @param reason Additional information string * @param remote Returns whether or not the closing of the connection was initiated by the remote @@ -134,7 +134,7 @@ void onWebsocketHandshakeSentAsClient(WebSocket conn, ClientHandshake request) /** * send when this peer sends a close handshake * - * @param ws The WebSocket instance this event is occurring on. + * @param ws The WebSocket instance this event is occurring on. * @param code The codes can be looked up here: {@link CloseFrame} * @param reason Additional information string */ @@ -144,7 +144,7 @@ void onWebsocketHandshakeSentAsClient(WebSocket conn, ClientHandshake request) * Called if an exception worth noting occurred. If an error causes the connection to fail onClose * will be called additionally afterwards. * - * @param conn The WebSocket instance this event is occurring on. + * @param conn The WebSocket instance this event is occurring on. * @param ex The exception that occurred.
      Might be null if the exception is not related to * any specific connection. For example if the server port could not be bound. */ @@ -153,7 +153,7 @@ void onWebsocketHandshakeSentAsClient(WebSocket conn, ClientHandshake request) /** * Called a ping frame has been received. This method must send a corresponding pong by itself. * - * @param conn The WebSocket instance this event is occurring on. + * @param conn The WebSocket instance this event is occurring on. * @param f The ping frame. Control frames may contain payload. */ void onWebsocketPing(WebSocket conn, Framedata f); @@ -162,7 +162,7 @@ void onWebsocketHandshakeSentAsClient(WebSocket conn, ClientHandshake request) * Called just before a ping frame is sent, in order to allow users to customize their ping frame * data. * - * @param conn The WebSocket connection from which the ping frame will be sent. + * @param conn The WebSocket connection from which the ping frame will be sent. * @return PingFrame to be sent. */ PingFrame onPreparePing(WebSocket conn); @@ -170,7 +170,7 @@ void onWebsocketHandshakeSentAsClient(WebSocket conn, ClientHandshake request) /** * Called when a pong frame is received. * - * @param conn The WebSocket instance this event is occurring on. + * @param conn The WebSocket instance this event is occurring on. * @param f The pong frame. Control frames may contain payload. **/ void onWebsocketPong(WebSocket conn, Framedata f); @@ -179,19 +179,19 @@ void onWebsocketHandshakeSentAsClient(WebSocket conn, ClientHandshake request) * This method is used to inform the selector thread that there is data queued to be written to * the socket. * - * @param conn The WebSocket instance this event is occurring on. + * @param conn The WebSocket instance this event is occurring on. */ void onWriteDemand(WebSocket conn); /** - * @param conn The WebSocket instance this event is occurring on. + * @param conn The WebSocket instance this event is occurring on. * @return Returns the address of the endpoint this socket is bound to. * @see WebSocket#getLocalSocketAddress() */ InetSocketAddress getLocalSocketAddress(WebSocket conn); /** - * @param conn The WebSocket instance this event is occurring on. + * @param conn The WebSocket instance this event is occurring on. * @return Returns the address of the endpoint this socket is connected to, or{@code null} if it * is unconnected. * @see WebSocket#getRemoteSocketAddress() diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index bb8178c25..9dbf004da 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -71,7 +71,7 @@ import org.slf4j.LoggerFactory; /** - * WebSocketServer is an abstract class that only takes care of the + * WebSocketServer is an abstract class that only takes care of the * HTTP handshake portion of WebSockets. It's up to a subclass to add functionality/purpose to the * server. */ @@ -183,7 +183,7 @@ public WebSocketServer(InetSocketAddress address, int decodercount, List /** * Creates a WebSocketServer that will attempt to bind/listen on the given address, and - * comply with Draft version draft. + * comply with Draft version draft. * * @param address The address (host:port) this server should listen on. * @param decodercount The number of {@link WebSocketWorker}s that will be used to process @@ -872,7 +872,7 @@ public InetSocketAddress getRemoteSocketAddress(WebSocket conn) { * Called after an opening handshake has been performed and the given websocket is ready to be * written on. * - * @param conn The WebSocket instance this event is occurring on. + * @param conn The WebSocket instance this event is occurring on. * @param handshake The handshake of the websocket instance */ public abstract void onOpen(WebSocket conn, ClientHandshake handshake); @@ -880,7 +880,7 @@ public InetSocketAddress getRemoteSocketAddress(WebSocket conn) { /** * Called after the websocket connection has been closed. * - * @param conn The WebSocket instance this event is occurring on. + * @param conn The WebSocket instance this event is occurring on. * @param code The codes can be looked up here: {@link CloseFrame} * @param reason Additional information string * @param remote Returns whether or not the closing of the connection was initiated by the remote @@ -891,7 +891,7 @@ public InetSocketAddress getRemoteSocketAddress(WebSocket conn) { /** * Callback for string messages received from the remote host * - * @param conn The WebSocket instance this event is occurring on. + * @param conn The WebSocket instance this event is occurring on. * @param message The UTF-8 decoded message that was received. * @see #onMessage(WebSocket, ByteBuffer) **/ @@ -919,7 +919,7 @@ public InetSocketAddress getRemoteSocketAddress(WebSocket conn) { /** * Callback for binary messages received from the remote host * - * @param conn The WebSocket instance this event is occurring on. + * @param conn The WebSocket instance this event is occurring on. * @param message The binary message that was received. * @see #onMessage(WebSocket, ByteBuffer) **/ diff --git a/src/main/java/org/java_websocket/util/Base64.java b/src/main/java/org/java_websocket/util/Base64.java index e9ff7b87a..067a027e1 100644 --- a/src/main/java/org/java_websocket/util/Base64.java +++ b/src/main/java/org/java_websocket/util/Base64.java @@ -35,7 +35,7 @@ *
      * byte[] myByteArray = Base64.decode( encoded ); * - *

      The options parameter, which appears in a few places, is used to pass + *

      The options parameter, which appears in a few places, is used to pass * several pieces of information to the encoder. In the "higher level" methods such as encodeBytes( * bytes, options ) the options parameter can be used to indicate such things as first gzipping the * bytes before encoding them, not inserting linefeeds, and encoding using the URL-safe and Ordered @@ -140,9 +140,9 @@ * when data that's being decoded is gzip-compressed and will decompress it * automatically. Generally things are cleaner. You'll probably have to * change some method calls that you were making to support the new - * options format (ints that you "OR" together). + * options format (ints that you "OR" together). *

    • v1.5.1 - Fixed bug when decompressing and decoding to a - * byte[] using decode( String s, boolean gzipCompressed ). + * byte[] using decode( String s, boolean gzipCompressed ). * Added the ability to "suspend" encoding in the Output Stream so * you can turn on and off the encoding if you need to embed base64 * data in an otherwise "normal" stream (like an XML file).
    • @@ -873,7 +873,7 @@ else if (source[srcOffset + 3] == EQUALS_SIGN) { /** * A {@link Base64.OutputStream} will write data to another - * java.io.OutputStream, given in the constructor, + * java.io.OutputStream, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 @@ -895,7 +895,7 @@ public static class OutputStream extends java.io.FilterOutputStream { /** * Constructs a {@link Base64.OutputStream} in ENCODE mode. * - * @param out the java.io.OutputStream to which data will be written. + * @param out the java.io.OutputStream to which data will be written. * @since 1.3 */ public OutputStream(java.io.OutputStream out) { @@ -914,7 +914,7 @@ public OutputStream(java.io.OutputStream out) { *

      * Example: new Base64.OutputStream( out, Base64.ENCODE ) * - * @param out the java.io.OutputStream to which data will be written. + * @param out the java.io.OutputStream to which data will be written. * @param options Specified options. * @see Base64#ENCODE * @see Base64#DO_BREAK_LINES From d4365d4396bcfaf04c43f7d9239c8a2b64069518 Mon Sep 17 00:00:00 2001 From: Pavel Treutner Date: Tue, 16 Jan 2024 11:12:52 +0100 Subject: [PATCH 139/165] Retrieve default SSL socket factory to reconcile the configuration with jdk.tls.client.protocols --- src/main/java/org/java_websocket/client/WebSocketClient.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 893c8afbf..955cd3d6c 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -45,7 +45,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.net.SocketFactory; -import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSession; @@ -543,9 +542,7 @@ private void upgradeSocketToSSL() if (socketFactory instanceof SSLSocketFactory) { factory = (SSLSocketFactory) socketFactory; } else { - SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); - sslContext.init(null, null, null); - factory = sslContext.getSocketFactory(); + factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); } socket = factory.createSocket(socket, uri.getHost(), getPort(), true); } From c717bc74e60f7bc9ed83426f66198eb8bc6394c5 Mon Sep 17 00:00:00 2001 From: newk5 Date: Sat, 27 Nov 2021 07:31:01 +0000 Subject: [PATCH 140/165] Provide way to start the client/server as daemons --- .../org/java_websocket/AbstractWebSocket.java | 30 +++++++- .../client/WebSocketClient.java | 2 + .../server/WebSocketServer.java | 18 ++++- .../util/NamedThreadFactory.java | 8 ++ .../server/DaemonThreadTest.java | 75 +++++++++++++++++++ 5 files changed, 131 insertions(+), 2 deletions(-) create mode 100644 src/test/java/org/java_websocket/server/DaemonThreadTest.java diff --git a/src/main/java/org/java_websocket/AbstractWebSocket.java b/src/main/java/org/java_websocket/AbstractWebSocket.java index c3e77a089..ee3cc13d5 100644 --- a/src/main/java/org/java_websocket/AbstractWebSocket.java +++ b/src/main/java/org/java_websocket/AbstractWebSocket.java @@ -90,6 +90,13 @@ public abstract class AbstractWebSocket extends WebSocketAdapter { */ private boolean websocketRunning = false; + /** + * Attribute to start internal threads as daemon + * + * @since 1.5.6 + */ + private boolean daemon = false; + /** * Attribute to sync on */ @@ -182,7 +189,7 @@ protected void startConnectionLostTimer() { private void restartConnectionLostTimer() { cancelConnectionLostTimer(); connectionLostCheckerService = Executors - .newSingleThreadScheduledExecutor(new NamedThreadFactory("connectionLostChecker")); + .newSingleThreadScheduledExecutor(new NamedThreadFactory("connectionLostChecker", daemon)); Runnable connectionLostChecker = new Runnable() { /** @@ -308,4 +315,25 @@ public void setReuseAddr(boolean reuseAddr) { this.reuseAddr = reuseAddr; } + + /** + * Getter for daemon + * + * @return whether internal threads are spawned in daemon mode + * @since 1.5.6 + */ + public boolean isDaemon() { + return daemon; + } + + /** + * Setter for daemon + *

      + * Controls whether or not internal threads are spawned in daemon mode + * + * @since 1.5.6 + */ + public void setDaemon(boolean daemon) { + this.daemon = daemon; + } } diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 955cd3d6c..756534cd9 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -373,6 +373,7 @@ public void connect() { throw new IllegalStateException("WebSocketClient objects are not reuseable"); } connectReadThread = new Thread(this); + connectReadThread.setDaemon(isDaemon()); connectReadThread.setName("WebSocketConnectReadThread-" + connectReadThread.getId()); connectReadThread.start(); } @@ -515,6 +516,7 @@ public void run() { } } writeThread = new Thread(new WebsocketWriteThread(this)); + writeThread.setDaemon(isDaemon()); writeThread.start(); byte[] rawbuffer = new byte[WebSocketImpl.RCVBUF]; diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 9dbf004da..8e00c5b22 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -245,7 +245,9 @@ public void start() { if (selectorthread != null) { throw new IllegalStateException(getClass().getName() + " can only be started once."); } - new Thread(this).start(); + Thread t = new Thread(this); + t.setDaemon(isDaemon()); + t.start(); } public void stop(int timeout) throws InterruptedException { @@ -326,6 +328,20 @@ public int getPort() { return port; } + @Override + public void setDaemon(boolean daemon) { + // pass it to the AbstractWebSocket too, to use it on the connectionLostChecker thread factory + super.setDaemon(daemon); + // we need to apply this to the decoders as well since they were created during the constructor + for (WebSocketWorker w : decoders) { + if (w.isAlive()) { + throw new IllegalStateException("Cannot call setDaemon after server is already started!"); + } else { + w.setDaemon(daemon); + } + } + } + /** * Get the list of active drafts * diff --git a/src/main/java/org/java_websocket/util/NamedThreadFactory.java b/src/main/java/org/java_websocket/util/NamedThreadFactory.java index 2a424fe1a..19091c01c 100644 --- a/src/main/java/org/java_websocket/util/NamedThreadFactory.java +++ b/src/main/java/org/java_websocket/util/NamedThreadFactory.java @@ -34,14 +34,22 @@ public class NamedThreadFactory implements ThreadFactory { private final ThreadFactory defaultThreadFactory = Executors.defaultThreadFactory(); private final AtomicInteger threadNumber = new AtomicInteger(1); private final String threadPrefix; + private final boolean daemon; public NamedThreadFactory(String threadPrefix) { this.threadPrefix = threadPrefix; + this.daemon = false; + } + + public NamedThreadFactory(String threadPrefix, boolean daemon) { + this.threadPrefix = threadPrefix; + this.daemon = daemon; } @Override public Thread newThread(Runnable runnable) { Thread thread = defaultThreadFactory.newThread(runnable); + thread.setDaemon(daemon); thread.setName(threadPrefix + "-" + threadNumber); return thread; } diff --git a/src/test/java/org/java_websocket/server/DaemonThreadTest.java b/src/test/java/org/java_websocket/server/DaemonThreadTest.java new file mode 100644 index 000000000..f1b25c6f0 --- /dev/null +++ b/src/test/java/org/java_websocket/server/DaemonThreadTest.java @@ -0,0 +1,75 @@ +package org.java_websocket.server; + +import java.io.IOException; +import java.net.*; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import org.java_websocket.WebSocket; +import org.java_websocket.handshake.*; +import org.java_websocket.client.*; +import org.java_websocket.server.WebSocketServer; +import org.java_websocket.util.SocketUtil; +import org.junit.Test; +import static org.junit.Assert.assertTrue; + +public class DaemonThreadTest { + + @Test(timeout = 1000) + public void test_AllCreatedThreadsAreDaemon() throws Throwable { + + Set threadSet1 = Thread.getAllStackTraces().keySet(); + final CountDownLatch ready = new CountDownLatch(1); + + WebSocketServer server = new WebSocketServer(new InetSocketAddress(SocketUtil.getAvailablePort())) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) {} + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) {} + @Override + public void onMessage(WebSocket conn, String message) {} + @Override + public void onError(WebSocket conn, Exception ex) {} + @Override + public void onStart() {} + }; + server.setDaemon(true); + server.setDaemon(false); + server.setDaemon(true); + server.start(); + + WebSocketClient client = new WebSocketClient(URI.create("ws://localhost:" + server.getPort())) { + @Override + public void onOpen(ServerHandshake handshake) { + ready.countDown(); + } + @Override + public void onClose(int code, String reason, boolean remote) {} + @Override + public void onMessage(String message) {} + @Override + public void onError(Exception ex) {} + }; + client.setDaemon(false); + client.setDaemon(true); + client.connect(); + + ready.await(); + Set threadSet2 = Thread.getAllStackTraces().keySet(); + threadSet2.removeAll(threadSet1); + + assertTrue("new threads created (no new threads indicates issue in test)", !threadSet2.isEmpty()); + + for (Thread t : threadSet2) + assertTrue(t.getName(), t.isDaemon()); + + boolean exception = false; + try { + server.setDaemon(false); + } catch(IllegalStateException e) { + exception = true; + } + assertTrue("exception was thrown when calling setDaemon on a running server", exception); + + server.stop(); + } +} From 4bdfe1f30ac8152246dcab3bc52cc51cc860c277 Mon Sep 17 00:00:00 2001 From: marci4 Date: Tue, 6 Feb 2024 22:33:41 +0100 Subject: [PATCH 141/165] Release 1.5.6 --- CHANGELOG.md | 16 ++++++++++++++++ README.markdown | 6 +++--- build.gradle | 2 +- pom.xml | 2 +- 4 files changed, 21 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fb44daa45..b3e954704 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,22 @@ # Change log ############################################################################### +## Version Release 1.5.6 (2024/02/06) + +#### Bugs Fixed + +* [Issue 1382](https://github.com/TooTallNate/Java-WebSocket/issues/1382) - WebSocketClient.upgradeSocketToSSL is enforcing TLS 1.2 ([PR 1387](https://github.com/TooTallNate/Java-WebSocket/pull/1387)) +* [PR 1387](https://github.com/TooTallNate/Java-WebSocket/pull/1387) - Retrieve default SSL socket factory + +#### New Features + +* [Issue 1390](https://github.com/TooTallNate/Java-WebSocket/issues/1390) - Thread created by NamedThreadFactory should be a daemon ([PR 1391](https://github.com/TooTallNate/Java-WebSocket/pull/1391)) +* [PR 1391](https://github.com/TooTallNate/Java-WebSocket/pull/1391) - Provide way to start the client/server as daemons + +In this release 2 issues and 2 pull requests were closed. + +############################################################################### + ## Version Release 1.5.5 (2023/12/18) #### Bugs Fixed diff --git a/README.markdown b/README.markdown index 152facd1f..01449f38c 100644 --- a/README.markdown +++ b/README.markdown @@ -30,7 +30,7 @@ To use maven add this dependency to your pom.xml: org.java-websocket Java-WebSocket - 1.5.4 + 1.5.6 ``` @@ -41,11 +41,11 @@ mavenCentral() ``` Then you can just add the latest version to your build. ```xml -compile "org.java-websocket:Java-WebSocket:1.5.4" +compile "org.java-websocket:Java-WebSocket:1.5.6" ``` Or this option if you use gradle 7.0 and above. ```xml -implementation 'org.java-websocket:Java-WebSocket:1.5.4' +implementation 'org.java-websocket:Java-WebSocket:1.5.6' ``` #### Logging diff --git a/build.gradle b/build.gradle index 5138b1a74..0359cddfb 100644 --- a/build.gradle +++ b/build.gradle @@ -10,7 +10,7 @@ repositories { } group = 'org.java-websocket' -version = '1.5.6-SNAPSHOT' +version = '1.5.6' sourceCompatibility = 1.7 targetCompatibility = 1.7 diff --git a/pom.xml b/pom.xml index 74f29a166..148eefd20 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.java-websocket Java-WebSocket jar - 1.5.6-SNAPSHOT + 1.5.6 Java-WebSocket A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket From 765932aa96837100167ebca9f1c4b60d2256698c Mon Sep 17 00:00:00 2001 From: marci4 Date: Tue, 6 Feb 2024 22:39:51 +0100 Subject: [PATCH 142/165] Increase version to 1.5.7 --- build.gradle | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 0359cddfb..3a381ce43 100644 --- a/build.gradle +++ b/build.gradle @@ -10,7 +10,7 @@ repositories { } group = 'org.java-websocket' -version = '1.5.6' +version = '1.5.7-SNAPSHOT' sourceCompatibility = 1.7 targetCompatibility = 1.7 diff --git a/pom.xml b/pom.xml index 148eefd20..48b1ca9e2 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.java-websocket Java-WebSocket jar - 1.5.6 + 1.5.7-SNAPSHOT Java-WebSocket A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket From f7d51a84cfaeb829d0edaa40c0aa0df1ad0bdf67 Mon Sep 17 00:00:00 2001 From: Cameron Auser Date: Fri, 16 Feb 2024 15:15:37 -0600 Subject: [PATCH 143/165] Explicitly close the socket when resetting the client if the connection is not yet opened. This prevents the write thread from hanging while attempting to write to the output stream. Reset the connection if we fail to connect during connectBlocking. --- .../org/java_websocket/client/WebSocketClient.java | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 756534cd9..d8db47254 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -339,7 +339,11 @@ private void reset() { "You cannot initialize a reconnect out of the websocket thread. Use reconnect in another thread to ensure a successful cleanup."); } try { + if (engine.getReadyState() == ReadyState.NOT_YET_CONNECTED) { + socket.close(); + } closeBlocking(); + if (writeThread != null) { this.writeThread.interrupt(); this.writeThread.join(); @@ -401,7 +405,13 @@ public boolean connectBlocking() throws InterruptedException { */ public boolean connectBlocking(long timeout, TimeUnit timeUnit) throws InterruptedException { connect(); - return connectLatch.await(timeout, timeUnit) && engine.isOpen(); + + boolean connected = connectLatch.await(timeout, timeUnit); + if (!connected) { + reset(); + } + + return connected && engine.isOpen(); } /** From d8eb0f8b98293c6a9dc18558b5c8cf41a58badda Mon Sep 17 00:00:00 2001 From: Cameron Auser Date: Wed, 21 Feb 2024 09:17:50 -0600 Subject: [PATCH 144/165] Ensure the socket is not null when attempting to close it. --- src/main/java/org/java_websocket/client/WebSocketClient.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index d8db47254..18cea8a29 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -339,7 +339,9 @@ private void reset() { "You cannot initialize a reconnect out of the websocket thread. Use reconnect in another thread to ensure a successful cleanup."); } try { - if (engine.getReadyState() == ReadyState.NOT_YET_CONNECTED) { + // This socket null check ensures we can reconnect a socket that failed to connect. It's an uncommon edge case, but we want to make sure we support it + if (engine.getReadyState() == ReadyState.NOT_YET_CONNECTED && socket != null) { + // Closing the socket when we have not connected prevents the writeThread from hanging on a write indefinitely during connection teardown socket.close(); } closeBlocking(); From acd03d098c1685d91dba7ae16b9588944c1cf432 Mon Sep 17 00:00:00 2001 From: PhilipRoman Date: Sat, 24 Feb 2024 14:11:56 +0200 Subject: [PATCH 145/165] Add test for connectBlocking cleanup (#1399) --- .../client/ConnectBlockingTest.java | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 src/test/java/org/java_websocket/client/ConnectBlockingTest.java diff --git a/src/test/java/org/java_websocket/client/ConnectBlockingTest.java b/src/test/java/org/java_websocket/client/ConnectBlockingTest.java new file mode 100644 index 000000000..fa7797cd8 --- /dev/null +++ b/src/test/java/org/java_websocket/client/ConnectBlockingTest.java @@ -0,0 +1,68 @@ +package org.java_websocket.client; + +import java.io.IOException; +import java.net.*; +import java.util.Set; +import java.util.concurrent.*; +import org.java_websocket.WebSocket; +import org.java_websocket.handshake.*; +import org.java_websocket.client.*; +import org.java_websocket.server.WebSocketServer; +import org.java_websocket.util.SocketUtil; +import org.java_websocket.enums.ReadyState; +import org.junit.Test; +import static org.junit.Assert.*; + +public class ConnectBlockingTest { + + @Test(timeout = 1000) + public void test_ConnectBlockingCleanup() throws Throwable { + + Set threadSet1 = Thread.getAllStackTraces().keySet(); + final CountDownLatch ready = new CountDownLatch(1); + final CountDownLatch accepted = new CountDownLatch(1); + + final int port = SocketUtil.getAvailablePort(); + + /* TCP server which listens to a port, but does not answer handshake */ + Thread server = new Thread(new Runnable() { + @Override + public void run() { + try { + ServerSocket serverSocket = new ServerSocket(port); + ready.countDown(); + Socket clientSocket = serverSocket.accept(); + accepted.countDown(); + } catch (Throwable t) { + assertTrue(t instanceof InterruptedException); + } + } + }); + server.start(); + ready.await(); + + WebSocketClient client = new WebSocketClient(URI.create("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshake) { + } + @Override + public void onClose(int code, String reason, boolean remote) {} + @Override + public void onMessage(String message) {} + @Override + public void onError(Exception ex) { + ex.printStackTrace(); + } + }; + boolean connected = client.connectBlocking(100, TimeUnit.MILLISECONDS); + assertEquals("TCP socket should have been accepted", 0, accepted.getCount()); + assertFalse("WebSocket should not be connected (as server didn't send handshake)", connected); + + server.interrupt(); + server.join(); + + Set threadSet2 = Thread.getAllStackTraces().keySet(); + assertEquals("no threads left over", threadSet1, threadSet2); + assertTrue("WebSocket is in closed state", client.getReadyState() == ReadyState.CLOSED || client.getReadyState() == ReadyState.NOT_YET_CONNECTED); + } +} From 1f842a6e1e3a49489b6fcae885c0f9fc9605206b Mon Sep 17 00:00:00 2001 From: Philip Roman <33231208+PhilipRoman@users.noreply.github.com> Date: Mon, 15 Apr 2024 09:18:57 +0300 Subject: [PATCH 146/165] Add timeout to CI test --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fb9ad601e..57ed219ec 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,6 +17,7 @@ jobs: Test: runs-on: ubuntu-latest + timeout-minutes: 15 steps: - uses: actions/checkout@v3 - name: Set up JDK 17 From f625a1a5e0db59f9f7f0d2d9d5671a439f012b9d Mon Sep 17 00:00:00 2001 From: PhilipRoman Date: Mon, 15 Apr 2024 00:04:10 +0300 Subject: [PATCH 147/165] Allow setting custom TCP receive buffer size Also increase default to 64K for performance improvement. --- .../org/java_websocket/AbstractWebSocket.java | 37 +++++++++++++++++++ .../org/java_websocket/WebSocketImpl.java | 5 --- .../client/WebSocketClient.java | 7 +++- .../server/WebSocketServer.java | 8 +++- 4 files changed, 49 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/java_websocket/AbstractWebSocket.java b/src/main/java/org/java_websocket/AbstractWebSocket.java index ee3cc13d5..bbb1dc8f0 100644 --- a/src/main/java/org/java_websocket/AbstractWebSocket.java +++ b/src/main/java/org/java_websocket/AbstractWebSocket.java @@ -102,6 +102,18 @@ public abstract class AbstractWebSocket extends WebSocketAdapter { */ private final Object syncConnectionLost = new Object(); + /** + * TCP receive buffer size that will be used for sockets (zero means use system default) + * + * @since 1.5.7 + */ + private int receiveBufferSize = 0; + + /** + * Used for internal buffer allocations when the socket buffer size is not specified. + */ + protected static int DEFAULT_READ_BUFFER_SIZE = 65536; + /** * Get the interval checking for lost connections Default is 60 seconds * @@ -336,4 +348,29 @@ public boolean isDaemon() { public void setDaemon(boolean daemon) { this.daemon = daemon; } + + /** + * Returns the TCP receive buffer size that will be used for sockets (or zero, if not explicitly set). + * @see java.net.Socket#setReceiveBufferSize(int) + * + * @since 1.5.7 + */ + public int getReceiveBufferSize() { + return receiveBufferSize; + } + + /** + * Sets the TCP receive buffer size that will be used for sockets. + * If this is not explicitly set (or set to zero), the system default is used. + * @see java.net.Socket#setReceiveBufferSize(int) + * + * @since 1.5.7 + */ + public void setReceiveBufferSize(int receiveBufferSize) { + if (receiveBufferSize < 0) { + throw new IllegalArgumentException("buffer size < 0"); + } + this.receiveBufferSize = receiveBufferSize; + } + } diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index c2cd223b9..3289aefcf 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -85,11 +85,6 @@ public class WebSocketImpl implements WebSocket { */ public static final int DEFAULT_WSS_PORT = 443; - /** - * Initial buffer size - */ - public static final int RCVBUF = 16384; - /** * Logger instance * diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 18cea8a29..1ac2df071 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -481,6 +481,10 @@ public void run() { socket.setTcpNoDelay(isTcpNoDelay()); socket.setReuseAddress(isReuseAddr()); + int receiveBufferSize = getReceiveBufferSize(); + if (receiveBufferSize > 0) { + socket.setReceiveBufferSize(receiveBufferSize); + } if (!socket.isConnected()) { InetSocketAddress addr = dnsResolver == null ? InetSocketAddress.createUnresolved(uri.getHost(), getPort()) : new InetSocketAddress(dnsResolver.resolve(uri), this.getPort()); @@ -531,7 +535,8 @@ public void run() { writeThread.setDaemon(isDaemon()); writeThread.start(); - byte[] rawbuffer = new byte[WebSocketImpl.RCVBUF]; + int receiveBufferSize = getReceiveBufferSize(); + byte[] rawbuffer = new byte[receiveBufferSize > 0 ? receiveBufferSize : DEFAULT_READ_BUFFER_SIZE]; int readBytes; try { diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 8e00c5b22..e4f8790ee 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -578,7 +578,10 @@ private boolean doSetupSelectorAndServerThread() { server = ServerSocketChannel.open(); server.configureBlocking(false); ServerSocket socket = server.socket(); - socket.setReceiveBufferSize(WebSocketImpl.RCVBUF); + int receiveBufferSize = getReceiveBufferSize(); + if (receiveBufferSize > 0) { + socket.setReceiveBufferSize(receiveBufferSize); + } socket.setReuseAddress(isReuseAddr()); socket.bind(address, getMaxPendingConnections()); selector = Selector.open(); @@ -655,7 +658,8 @@ protected void releaseBuffers(WebSocket c) throws InterruptedException { } public ByteBuffer createBuffer() { - return ByteBuffer.allocate(WebSocketImpl.RCVBUF); + int receiveBufferSize = getReceiveBufferSize(); + return ByteBuffer.allocate(receiveBufferSize > 0 ? receiveBufferSize : DEFAULT_READ_BUFFER_SIZE); } protected void queue(WebSocketImpl ws) throws InterruptedException { From ad3d043f6a09f6f3bd36e64e2eb41ec5f7606730 Mon Sep 17 00:00:00 2001 From: Robert Schlabbach Date: Sat, 8 Jun 2024 08:23:07 +0200 Subject: [PATCH 148/165] Fix WebSocketServer sometimes missing GET request On Ubuntu 22.04 with Linux 6.5, it was observed that when the server gets the SSL records containing the client handshake finished message and the first HTTP GET request in ONE read operation, the latter SSL record is never processed. Commit 89eaf410dd8fe3845fa6fb0de3469b55da0205cb should have fixed this, but it turned out that when SSLSocketChannel2#processHandshake() is called from SSLSocketChannel2#write(), the second SSL record containing the HTTP GET request is stashed away, but never retrieved, since the calling code in WebSocketServer#doWrite() has no provisions for this, only WebSocketServer#doRead() does. Change SSLSocketChannel2#processHandshake() to only read from the socket when called from SSLSocketChannel#read(), to ensure that when two SSL records are read, the second one is processed as well. This fixes issue #1418. --- .../java/org/java_websocket/SSLSocketChannel2.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/java_websocket/SSLSocketChannel2.java b/src/main/java/org/java_websocket/SSLSocketChannel2.java index c0ea28e3f..23c4f8af1 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel2.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel2.java @@ -126,7 +126,7 @@ public SSLSocketChannel2(SocketChannel channel, SSLEngine sslEngine, ExecutorSer createBuffers(sslEngine.getSession()); // kick off handshake socketChannel.write(wrap(emptybuffer));// initializes res - processHandshake(); + processHandshake(false); } private void consumeFutureUninterruptible(Future f) { @@ -148,7 +148,7 @@ private void consumeFutureUninterruptible(Future f) { * This method will do whatever necessary to process the sslEngine handshake. Thats why it's * called both from the {@link #read(ByteBuffer)} and {@link #write(ByteBuffer)} **/ - private synchronized void processHandshake() throws IOException { + private synchronized void processHandshake(boolean isReading) throws IOException { if (sslEngine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING) { return; // since this may be called either from a reading or a writing thread and because this method is synchronized it is necessary to double check if we are still handshaking. } @@ -167,7 +167,7 @@ private synchronized void processHandshake() throws IOException { } } - if (sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) { + if (isReading && sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) { if (!isBlocking() || readEngineResult.getStatus() == Status.BUFFER_UNDERFLOW) { inCrypt.compact(); int read = socketChannel.read(inCrypt); @@ -273,7 +273,7 @@ protected void createBuffers(SSLSession session) { public int write(ByteBuffer src) throws IOException { if (!isHandShakeComplete()) { - processHandshake(); + processHandshake(false); return 0; } // assert(bufferallocations > 1); // see #190 @@ -303,10 +303,10 @@ public int read(ByteBuffer dst) throws IOException { if (!isHandShakeComplete()) { if (isBlocking()) { while (!isHandShakeComplete()) { - processHandshake(); + processHandshake(true); } } else { - processHandshake(); + processHandshake(true); if (!isHandShakeComplete()) { return 0; } From dd0764872dd468c673dd257693b733429657b00c Mon Sep 17 00:00:00 2001 From: marci4 Date: Mon, 8 Jul 2024 22:40:53 +0200 Subject: [PATCH 149/165] Release 1.5.7 --- CHANGELOG.md | 18 ++++++++++++++++++ README.markdown | 6 +++--- build.gradle | 2 +- pom.xml | 2 +- 4 files changed, 23 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b3e954704..c0befabb8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Change log +############################################################################### +## Version Release 1.5.7 (2024/07/08) + +#### Breaking Changes + +* [PR 1399](https://github.com/TooTallNate/Java-WebSocket/pull/1399) - Have connectBlocking clean up after a timeout + +#### Bugs Fixed + +* [PR 1419](https://github.com/TooTallNate/Java-WebSocket/pull/1419) - Fix issue #1418: WebSocketServer sometimes misses GET request after SSL handshake + +#### New Features + +* [PR 1407](https://github.com/TooTallNate/Java-WebSocket/pull/1407) - Allow setting custom TCP receive buffer size +* [PR 1399](https://github.com/TooTallNate/Java-WebSocket/pull/1399) - Have connectBlocking clean up after a timeout + +In this release 0 issues and 4 pull requests were closed. + ############################################################################### ## Version Release 1.5.6 (2024/02/06) diff --git a/README.markdown b/README.markdown index 01449f38c..aa13289f4 100644 --- a/README.markdown +++ b/README.markdown @@ -30,7 +30,7 @@ To use maven add this dependency to your pom.xml: org.java-websocket Java-WebSocket - 1.5.6 + 1.5.7 ``` @@ -41,11 +41,11 @@ mavenCentral() ``` Then you can just add the latest version to your build. ```xml -compile "org.java-websocket:Java-WebSocket:1.5.6" +compile "org.java-websocket:Java-WebSocket:1.5.7" ``` Or this option if you use gradle 7.0 and above. ```xml -implementation 'org.java-websocket:Java-WebSocket:1.5.6' +implementation 'org.java-websocket:Java-WebSocket:1.5.7' ``` #### Logging diff --git a/build.gradle b/build.gradle index 3a381ce43..f88c4aa63 100644 --- a/build.gradle +++ b/build.gradle @@ -10,7 +10,7 @@ repositories { } group = 'org.java-websocket' -version = '1.5.7-SNAPSHOT' +version = '1.5.7' sourceCompatibility = 1.7 targetCompatibility = 1.7 diff --git a/pom.xml b/pom.xml index 48b1ca9e2..910378d0d 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.java-websocket Java-WebSocket jar - 1.5.7-SNAPSHOT + 1.5.7 Java-WebSocket A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket From 202d7a486baa4a78b742d78e902492e698961b8e Mon Sep 17 00:00:00 2001 From: marci4 Date: Mon, 8 Jul 2024 23:33:21 +0200 Subject: [PATCH 150/165] Increase version to 1.5.8 --- build.gradle | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index f88c4aa63..51ca67bc3 100644 --- a/build.gradle +++ b/build.gradle @@ -10,7 +10,7 @@ repositories { } group = 'org.java-websocket' -version = '1.5.7' +version = '1.5.8-SNAPSHOT' sourceCompatibility = 1.7 targetCompatibility = 1.7 diff --git a/pom.xml b/pom.xml index 910378d0d..1140c813c 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.java-websocket Java-WebSocket jar - 1.5.7 + 1.5.8-SNAPSHOT Java-WebSocket A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket From 01e1a403a602a3b18306b53400a8e014e3ec9464 Mon Sep 17 00:00:00 2001 From: marci4 Date: Fri, 12 Jul 2024 16:55:54 +0200 Subject: [PATCH 151/165] Drop support for Java 1.7 Update dependencies Remove json dependency --- README.markdown | 2 +- build.gradle | 13 +- pom.xml | 18 +- .../autobahn/AutobahnServerResultsTest.java | 2772 ----------------- 4 files changed, 10 insertions(+), 2795 deletions(-) delete mode 100644 src/test/java/org/java_websocket/autobahn/AutobahnServerResultsTest.java diff --git a/README.markdown b/README.markdown index aa13289f4..3376ebc4c 100644 --- a/README.markdown +++ b/README.markdown @@ -114,7 +114,7 @@ Minimum Required JDK `Java-WebSocket` is known to work with: - * Java 1.7 and higher + * Java 8 and higher Other JRE implementations may work as well, but haven't been tested. diff --git a/build.gradle b/build.gradle index 51ca67bc3..29dcc51b0 100644 --- a/build.gradle +++ b/build.gradle @@ -10,9 +10,9 @@ repositories { } group = 'org.java-websocket' -version = '1.5.8-SNAPSHOT' -sourceCompatibility = 1.7 -targetCompatibility = 1.7 +version = '1.6.0-SNAPSHOT' +sourceCompatibility = 1.8 +targetCompatibility = 1.8 compileJava { options.compilerArgs += ['-encoding', 'UTF-8'] @@ -35,8 +35,7 @@ publishing { } dependencies { - implementation group: 'org.slf4j', name: 'slf4j-api', version: '2.0.6' - testImplementation group: 'org.slf4j', name: 'slf4j-simple', version: '2.0.6' - testImplementation group: 'junit', name: 'junit', version: '4.12' - testImplementation group: 'org.json', name: 'json', version: '20180813' + implementation group: 'org.slf4j', name: 'slf4j-api', version: '2.0.13' + testImplementation group: 'org.slf4j', name: 'slf4j-simple', version: '2.0.13' + testImplementation group: 'junit', name: 'junit', version: '4.13.1' } diff --git a/pom.xml b/pom.xml index 1140c813c..73c093ae9 100644 --- a/pom.xml +++ b/pom.xml @@ -5,17 +5,16 @@ org.java-websocket Java-WebSocket jar - 1.5.8-SNAPSHOT + 1.6.0-SNAPSHOT Java-WebSocket A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket UTF-8 - 2.0.6 + 2.0.13 - 4.12 - 20180813 + 4.13.1 6.4.0 @@ -63,12 +62,6 @@ ${junit.version} test - - org.json - json - ${org.json.version} - test - @@ -299,11 +292,6 @@ junit test - - org.json - json - test - diff --git a/src/test/java/org/java_websocket/autobahn/AutobahnServerResultsTest.java b/src/test/java/org/java_websocket/autobahn/AutobahnServerResultsTest.java deleted file mode 100644 index 807714049..000000000 --- a/src/test/java/org/java_websocket/autobahn/AutobahnServerResultsTest.java +++ /dev/null @@ -1,2772 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.autobahn; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.Scanner; -import org.json.JSONObject; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Test; - -public class AutobahnServerResultsTest { - - static JSONObject jsonObject = null; - - @BeforeClass - public static void getJSONObject() throws FileNotFoundException { - File file = new File("reports/servers/index.json"); - //File file = new File( "C:\\Python27\\Scripts\\reports\\servers\\index.json" ); - if (file.exists()) { - String content = new Scanner(file).useDelimiter("\\Z").next(); - jsonObject = new JSONObject(content); - jsonObject = jsonObject.getJSONObject("TooTallNate Java-WebSocket"); - } - Assume.assumeTrue(jsonObject != null); - } - - @Test - public void test1_1_1() { - JSONObject testResult = jsonObject.getJSONObject("1.1.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test1_1_2() { - JSONObject testResult = jsonObject.getJSONObject("1.1.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test1_1_3() { - JSONObject testResult = jsonObject.getJSONObject("1.1.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test1_1_4() { - JSONObject testResult = jsonObject.getJSONObject("1.1.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test1_1_5() { - JSONObject testResult = jsonObject.getJSONObject("1.1.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test1_1_6() { - JSONObject testResult = jsonObject.getJSONObject("1.1.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 30); - } - - @Test - public void test1_1_7() { - JSONObject testResult = jsonObject.getJSONObject("1.1.7"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 20); - } - - @Test - public void test1_1_8() { - JSONObject testResult = jsonObject.getJSONObject("1.1.8"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 30); - } - - @Test - public void test1_2_1() { - JSONObject testResult = jsonObject.getJSONObject("1.2.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test1_2_2() { - JSONObject testResult = jsonObject.getJSONObject("1.2.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test1_2_3() { - JSONObject testResult = jsonObject.getJSONObject("1.2.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test1_2_4() { - JSONObject testResult = jsonObject.getJSONObject("1.2.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 20); - } - - @Test - public void test1_2_5() { - JSONObject testResult = jsonObject.getJSONObject("1.2.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test1_2_6() { - JSONObject testResult = jsonObject.getJSONObject("1.2.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 70); - } - - @Test - public void test1_2_7() { - JSONObject testResult = jsonObject.getJSONObject("1.2.7"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 70); - } - - @Test - public void test1_2_8() { - JSONObject testResult = jsonObject.getJSONObject("1.2.8"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 60); - } - - @Test - public void test2_1() { - JSONObject testResult = jsonObject.getJSONObject("2.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test2_2() { - JSONObject testResult = jsonObject.getJSONObject("2.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test2_3() { - JSONObject testResult = jsonObject.getJSONObject("2.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test2_4() { - JSONObject testResult = jsonObject.getJSONObject("2.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test2_5() { - JSONObject testResult = jsonObject.getJSONObject("2.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test2_6() { - JSONObject testResult = jsonObject.getJSONObject("2.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 30); - } - - @Test - public void test2_7() { - JSONObject testResult = jsonObject.getJSONObject("2.7"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test2_8() { - JSONObject testResult = jsonObject.getJSONObject("2.8"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test2_9() { - JSONObject testResult = jsonObject.getJSONObject("2.9"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test2_10() { - JSONObject testResult = jsonObject.getJSONObject("2.10"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 60); - } - - @Test - public void test2_11() { - JSONObject testResult = jsonObject.getJSONObject("2.11"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 50); - } - - @Test - public void test3_1() { - JSONObject testResult = jsonObject.getJSONObject("3.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test3_2() { - JSONObject testResult = jsonObject.getJSONObject("3.2"); - assertEquals("NON-STRICT", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test3_3() { - JSONObject testResult = jsonObject.getJSONObject("3.3"); - assertEquals("NON-STRICT", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test3_4() { - JSONObject testResult = jsonObject.getJSONObject("3.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 20); - } - - @Test - public void test3_5() { - JSONObject testResult = jsonObject.getJSONObject("3.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test3_6() { - JSONObject testResult = jsonObject.getJSONObject("3.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test3_7() { - JSONObject testResult = jsonObject.getJSONObject("3.7"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test4_1_1() { - JSONObject testResult = jsonObject.getJSONObject("4.1.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test4_1_2() { - JSONObject testResult = jsonObject.getJSONObject("4.1.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test4_1_3() { - JSONObject testResult = jsonObject.getJSONObject("4.1.3"); - assertEquals("NON-STRICT", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test4_1_4() { - JSONObject testResult = jsonObject.getJSONObject("4.1.4"); - assertEquals("NON-STRICT", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test4_1_5() { - JSONObject testResult = jsonObject.getJSONObject("4.1.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test4_2_1() { - JSONObject testResult = jsonObject.getJSONObject("4.2.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test4_2_2() { - JSONObject testResult = jsonObject.getJSONObject("4.2.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test4_2_3() { - JSONObject testResult = jsonObject.getJSONObject("4.2.3"); - assertEquals("NON-STRICT", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test4_2_4() { - JSONObject testResult = jsonObject.getJSONObject("4.2.4"); - assertEquals("NON-STRICT", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test4_2_5() { - JSONObject testResult = jsonObject.getJSONObject("4.2.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 15); - } - - @Test - public void test5_1() { - JSONObject testResult = jsonObject.getJSONObject("5.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test5_2() { - JSONObject testResult = jsonObject.getJSONObject("5.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test5_3() { - JSONObject testResult = jsonObject.getJSONObject("5.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test5_4() { - JSONObject testResult = jsonObject.getJSONObject("5.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test5_5() { - JSONObject testResult = jsonObject.getJSONObject("5.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 20); - } - - @Test - public void test5_6() { - JSONObject testResult = jsonObject.getJSONObject("5.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 60); - } - - @Test - public void test5_7() { - JSONObject testResult = jsonObject.getJSONObject("5.7"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 60); - } - - @Test - public void test5_8() { - JSONObject testResult = jsonObject.getJSONObject("5.8"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 20); - } - - @Test - public void test5_9() { - JSONObject testResult = jsonObject.getJSONObject("5.9"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test5_10() { - JSONObject testResult = jsonObject.getJSONObject("5.10"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test5_11() { - JSONObject testResult = jsonObject.getJSONObject("5.11"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 20); - } - - @Test - public void test5_12() { - JSONObject testResult = jsonObject.getJSONObject("5.12"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test5_13() { - JSONObject testResult = jsonObject.getJSONObject("5.13"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test5_14() { - JSONObject testResult = jsonObject.getJSONObject("5.14"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test5_15() { - JSONObject testResult = jsonObject.getJSONObject("5.15"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test5_16() { - JSONObject testResult = jsonObject.getJSONObject("5.16"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test5_17() { - JSONObject testResult = jsonObject.getJSONObject("5.17"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test5_18() { - JSONObject testResult = jsonObject.getJSONObject("5.18"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test5_19() { - JSONObject testResult = jsonObject.getJSONObject("5.19"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 1100); - } - - @Test - public void test5_20() { - JSONObject testResult = jsonObject.getJSONObject("5.20"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 1100); - } - - @Test - public void test6_1_1() { - JSONObject testResult = jsonObject.getJSONObject("6.1.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_1_2() { - JSONObject testResult = jsonObject.getJSONObject("6.1.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_1_3() { - JSONObject testResult = jsonObject.getJSONObject("6.1.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_2_1() { - JSONObject testResult = jsonObject.getJSONObject("6.2.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_2_2() { - JSONObject testResult = jsonObject.getJSONObject("6.2.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_2_3() { - JSONObject testResult = jsonObject.getJSONObject("6.2.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_2_4() { - JSONObject testResult = jsonObject.getJSONObject("6.2.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_3_1() { - JSONObject testResult = jsonObject.getJSONObject("6.3.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_3_2() { - JSONObject testResult = jsonObject.getJSONObject("6.3.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_4_1() { - JSONObject testResult = jsonObject.getJSONObject("6.4.1"); - assertEquals("NON-STRICT", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 2100); - } - - @Test - public void test6_4_2() { - JSONObject testResult = jsonObject.getJSONObject("6.4.2"); - assertEquals("NON-STRICT", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 2100); - } - - @Test - public void test6_4_3() { - JSONObject testResult = jsonObject.getJSONObject("6.4.3"); - assertEquals("NON-STRICT", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 2100); - } - - @Test - public void test6_4_4() { - JSONObject testResult = jsonObject.getJSONObject("6.4.4"); - assertEquals("NON-STRICT", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 2100); - } - - @Test - public void test6_5_1() { - JSONObject testResult = jsonObject.getJSONObject("6.5.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_5_2() { - JSONObject testResult = jsonObject.getJSONObject("6.5.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_5_3() { - JSONObject testResult = jsonObject.getJSONObject("6.5.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_5_4() { - JSONObject testResult = jsonObject.getJSONObject("6.5.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_5_5() { - JSONObject testResult = jsonObject.getJSONObject("6.5.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_6_1() { - JSONObject testResult = jsonObject.getJSONObject("6.6.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_6_2() { - JSONObject testResult = jsonObject.getJSONObject("6.6.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_6_3() { - JSONObject testResult = jsonObject.getJSONObject("6.6.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_6_4() { - JSONObject testResult = jsonObject.getJSONObject("6.6.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_6_5() { - JSONObject testResult = jsonObject.getJSONObject("6.6.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_6_6() { - JSONObject testResult = jsonObject.getJSONObject("6.6.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_6_7() { - JSONObject testResult = jsonObject.getJSONObject("6.6.7"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_6_8() { - JSONObject testResult = jsonObject.getJSONObject("6.6.8"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_6_9() { - JSONObject testResult = jsonObject.getJSONObject("6.6.9"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_6_10() { - JSONObject testResult = jsonObject.getJSONObject("6.6.10"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_6_11() { - JSONObject testResult = jsonObject.getJSONObject("6.6.11"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_7_1() { - JSONObject testResult = jsonObject.getJSONObject("6.7.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_7_2() { - JSONObject testResult = jsonObject.getJSONObject("6.7.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_7_3() { - JSONObject testResult = jsonObject.getJSONObject("6.7.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_7_4() { - JSONObject testResult = jsonObject.getJSONObject("6.7.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_8_1() { - JSONObject testResult = jsonObject.getJSONObject("6.8.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_8_2() { - JSONObject testResult = jsonObject.getJSONObject("6.8.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_9_1() { - JSONObject testResult = jsonObject.getJSONObject("6.9.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_9_2() { - JSONObject testResult = jsonObject.getJSONObject("6.9.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_9_3() { - JSONObject testResult = jsonObject.getJSONObject("6.9.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_9_4() { - JSONObject testResult = jsonObject.getJSONObject("6.9.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_10_1() { - JSONObject testResult = jsonObject.getJSONObject("6.10.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_10_2() { - JSONObject testResult = jsonObject.getJSONObject("6.10.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_10_3() { - JSONObject testResult = jsonObject.getJSONObject("6.10.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_11_1() { - JSONObject testResult = jsonObject.getJSONObject("6.11.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_11_2() { - JSONObject testResult = jsonObject.getJSONObject("6.11.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_11_3() { - JSONObject testResult = jsonObject.getJSONObject("6.11.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_11_4() { - JSONObject testResult = jsonObject.getJSONObject("6.11.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_11_5() { - JSONObject testResult = jsonObject.getJSONObject("6.11.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_12_1() { - JSONObject testResult = jsonObject.getJSONObject("6.12.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_12_2() { - JSONObject testResult = jsonObject.getJSONObject("6.12.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_12_3() { - JSONObject testResult = jsonObject.getJSONObject("6.12.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_12_4() { - JSONObject testResult = jsonObject.getJSONObject("6.12.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_12_5() { - JSONObject testResult = jsonObject.getJSONObject("6.12.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_12_6() { - JSONObject testResult = jsonObject.getJSONObject("6.12.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_12_7() { - JSONObject testResult = jsonObject.getJSONObject("6.12.7"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_12_8() { - JSONObject testResult = jsonObject.getJSONObject("6.12.8"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_13_1() { - JSONObject testResult = jsonObject.getJSONObject("6.13.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_13_2() { - JSONObject testResult = jsonObject.getJSONObject("6.13.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_13_3() { - JSONObject testResult = jsonObject.getJSONObject("6.13.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_13_4() { - JSONObject testResult = jsonObject.getJSONObject("6.13.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_13_5() { - JSONObject testResult = jsonObject.getJSONObject("6.13.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_14_1() { - JSONObject testResult = jsonObject.getJSONObject("6.14.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_14_2() { - JSONObject testResult = jsonObject.getJSONObject("6.14.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_14_3() { - JSONObject testResult = jsonObject.getJSONObject("6.14.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_14_4() { - JSONObject testResult = jsonObject.getJSONObject("6.14.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_14_5() { - JSONObject testResult = jsonObject.getJSONObject("6.14.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_14_6() { - JSONObject testResult = jsonObject.getJSONObject("6.14.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_14_7() { - JSONObject testResult = jsonObject.getJSONObject("6.14.7"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_14_8() { - JSONObject testResult = jsonObject.getJSONObject("6.14.8"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_14_9() { - JSONObject testResult = jsonObject.getJSONObject("6.14.9"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_14_10() { - JSONObject testResult = jsonObject.getJSONObject("6.14.10"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_15_1() { - JSONObject testResult = jsonObject.getJSONObject("6.15.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_16_1() { - JSONObject testResult = jsonObject.getJSONObject("6.16.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_16_2() { - JSONObject testResult = jsonObject.getJSONObject("6.16.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_16_3() { - JSONObject testResult = jsonObject.getJSONObject("6.16.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_17_1() { - JSONObject testResult = jsonObject.getJSONObject("6.17.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_17_2() { - JSONObject testResult = jsonObject.getJSONObject("6.17.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_17_3() { - JSONObject testResult = jsonObject.getJSONObject("6.17.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_17_4() { - JSONObject testResult = jsonObject.getJSONObject("6.17.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_17_5() { - JSONObject testResult = jsonObject.getJSONObject("6.17.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_18_1() { - JSONObject testResult = jsonObject.getJSONObject("6.18.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_18_2() { - JSONObject testResult = jsonObject.getJSONObject("6.18.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_18_3() { - JSONObject testResult = jsonObject.getJSONObject("6.18.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_18_4() { - JSONObject testResult = jsonObject.getJSONObject("6.18.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_18_5() { - JSONObject testResult = jsonObject.getJSONObject("6.18.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_19_1() { - JSONObject testResult = jsonObject.getJSONObject("6.19.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_19_2() { - JSONObject testResult = jsonObject.getJSONObject("6.19.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_19_3() { - JSONObject testResult = jsonObject.getJSONObject("6.19.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_19_4() { - JSONObject testResult = jsonObject.getJSONObject("6.19.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_19_5() { - JSONObject testResult = jsonObject.getJSONObject("6.19.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_20_1() { - JSONObject testResult = jsonObject.getJSONObject("6.20.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_20_2() { - JSONObject testResult = jsonObject.getJSONObject("6.20.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_20_3() { - JSONObject testResult = jsonObject.getJSONObject("6.20.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_20_4() { - JSONObject testResult = jsonObject.getJSONObject("6.20.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_20_5() { - JSONObject testResult = jsonObject.getJSONObject("6.20.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_20_6() { - JSONObject testResult = jsonObject.getJSONObject("6.20.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_20_7() { - JSONObject testResult = jsonObject.getJSONObject("6.20.7"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_21_1() { - JSONObject testResult = jsonObject.getJSONObject("6.21.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_21_2() { - JSONObject testResult = jsonObject.getJSONObject("6.21.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_21_3() { - JSONObject testResult = jsonObject.getJSONObject("6.21.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_21_4() { - JSONObject testResult = jsonObject.getJSONObject("6.21.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_21_5() { - JSONObject testResult = jsonObject.getJSONObject("6.21.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_21_6() { - JSONObject testResult = jsonObject.getJSONObject("6.21.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_21_7() { - JSONObject testResult = jsonObject.getJSONObject("6.21.7"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_21_8() { - JSONObject testResult = jsonObject.getJSONObject("6.21.8"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_1() { - JSONObject testResult = jsonObject.getJSONObject("6.22.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_2() { - JSONObject testResult = jsonObject.getJSONObject("6.22.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_3() { - JSONObject testResult = jsonObject.getJSONObject("6.22.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_4() { - JSONObject testResult = jsonObject.getJSONObject("6.22.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_5() { - JSONObject testResult = jsonObject.getJSONObject("6.22.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_6() { - JSONObject testResult = jsonObject.getJSONObject("6.22.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_7() { - JSONObject testResult = jsonObject.getJSONObject("6.22.7"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_8() { - JSONObject testResult = jsonObject.getJSONObject("6.22.8"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_9() { - JSONObject testResult = jsonObject.getJSONObject("6.22.9"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_10() { - JSONObject testResult = jsonObject.getJSONObject("6.22.10"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_11() { - JSONObject testResult = jsonObject.getJSONObject("6.22.11"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_12() { - JSONObject testResult = jsonObject.getJSONObject("6.22.12"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_13() { - JSONObject testResult = jsonObject.getJSONObject("6.22.13"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_14() { - JSONObject testResult = jsonObject.getJSONObject("6.22.14"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_15() { - JSONObject testResult = jsonObject.getJSONObject("6.22.15"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_16() { - JSONObject testResult = jsonObject.getJSONObject("6.22.16"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_17() { - JSONObject testResult = jsonObject.getJSONObject("6.22.17"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_18() { - JSONObject testResult = jsonObject.getJSONObject("6.22.18"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_19() { - JSONObject testResult = jsonObject.getJSONObject("6.22.19"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_20() { - JSONObject testResult = jsonObject.getJSONObject("6.22.20"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_21() { - JSONObject testResult = jsonObject.getJSONObject("6.22.21"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_22() { - JSONObject testResult = jsonObject.getJSONObject("6.22.22"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_23() { - JSONObject testResult = jsonObject.getJSONObject("6.22.23"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_24() { - JSONObject testResult = jsonObject.getJSONObject("6.22.24"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_25() { - JSONObject testResult = jsonObject.getJSONObject("6.22.25"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_26() { - JSONObject testResult = jsonObject.getJSONObject("6.22.26"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_27() { - JSONObject testResult = jsonObject.getJSONObject("6.22.27"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_28() { - JSONObject testResult = jsonObject.getJSONObject("6.22.28"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_29() { - JSONObject testResult = jsonObject.getJSONObject("6.22.29"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_30() { - JSONObject testResult = jsonObject.getJSONObject("6.22.30"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_31() { - JSONObject testResult = jsonObject.getJSONObject("6.22.31"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_32() { - JSONObject testResult = jsonObject.getJSONObject("6.22.32"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_33() { - JSONObject testResult = jsonObject.getJSONObject("6.22.33"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_22_34() { - JSONObject testResult = jsonObject.getJSONObject("6.22.34"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_23_1() { - JSONObject testResult = jsonObject.getJSONObject("6.23.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_23_2() { - JSONObject testResult = jsonObject.getJSONObject("6.23.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_23_3() { - JSONObject testResult = jsonObject.getJSONObject("6.23.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_23_4() { - JSONObject testResult = jsonObject.getJSONObject("6.23.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_23_5() { - JSONObject testResult = jsonObject.getJSONObject("6.23.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_23_6() { - JSONObject testResult = jsonObject.getJSONObject("6.23.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test6_23_7() { - JSONObject testResult = jsonObject.getJSONObject("6.23.7"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_1_1() { - JSONObject testResult = jsonObject.getJSONObject("7.1.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_1_2() { - JSONObject testResult = jsonObject.getJSONObject("7.1.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_1_3() { - JSONObject testResult = jsonObject.getJSONObject("7.1.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_1_4() { - JSONObject testResult = jsonObject.getJSONObject("7.1.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_1_5() { - JSONObject testResult = jsonObject.getJSONObject("7.1.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_1_6() { - JSONObject testResult = jsonObject.getJSONObject("7.1.6"); - assertEquals("INFORMATIONAL", testResult.get("behavior")); - assertEquals("INFORMATIONAL", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 50); - } - - @Test - public void test7_3_1() { - JSONObject testResult = jsonObject.getJSONObject("7.3.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_3_2() { - JSONObject testResult = jsonObject.getJSONObject("7.3.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_3_3() { - JSONObject testResult = jsonObject.getJSONObject("7.3.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_3_4() { - JSONObject testResult = jsonObject.getJSONObject("7.3.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_3_5() { - JSONObject testResult = jsonObject.getJSONObject("7.3.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_3_6() { - JSONObject testResult = jsonObject.getJSONObject("7.3.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_5_1() { - JSONObject testResult = jsonObject.getJSONObject("7.5.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_7_1() { - JSONObject testResult = jsonObject.getJSONObject("7.7.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_7_2() { - JSONObject testResult = jsonObject.getJSONObject("7.7.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_7_3() { - JSONObject testResult = jsonObject.getJSONObject("7.7.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_7_4() { - JSONObject testResult = jsonObject.getJSONObject("7.7.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_7_5() { - JSONObject testResult = jsonObject.getJSONObject("7.7.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_7_6() { - JSONObject testResult = jsonObject.getJSONObject("7.7.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_7_7() { - JSONObject testResult = jsonObject.getJSONObject("7.7.7"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_7_8() { - JSONObject testResult = jsonObject.getJSONObject("7.7.8"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_7_9() { - JSONObject testResult = jsonObject.getJSONObject("7.7.9"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_7_10() { - JSONObject testResult = jsonObject.getJSONObject("7.7.10"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_7_11() { - JSONObject testResult = jsonObject.getJSONObject("7.7.11"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_7_12() { - JSONObject testResult = jsonObject.getJSONObject("7.7.12"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_7_13() { - JSONObject testResult = jsonObject.getJSONObject("7.7.13"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_9_1() { - JSONObject testResult = jsonObject.getJSONObject("7.9.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_9_2() { - JSONObject testResult = jsonObject.getJSONObject("7.9.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_9_3() { - JSONObject testResult = jsonObject.getJSONObject("7.9.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_9_4() { - JSONObject testResult = jsonObject.getJSONObject("7.9.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_9_5() { - JSONObject testResult = jsonObject.getJSONObject("7.9.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_9_7() { - JSONObject testResult = jsonObject.getJSONObject("7.9.7"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_9_8() { - JSONObject testResult = jsonObject.getJSONObject("7.9.8"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_9_9() { - JSONObject testResult = jsonObject.getJSONObject("7.9.9"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_9_10() { - JSONObject testResult = jsonObject.getJSONObject("7.9.10"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_9_11() { - JSONObject testResult = jsonObject.getJSONObject("7.9.11"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_13_1() { - JSONObject testResult = jsonObject.getJSONObject("7.13.1"); - assertEquals("INFORMATIONAL", testResult.get("behavior")); - assertEquals("INFORMATIONAL", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test7_13_2() { - JSONObject testResult = jsonObject.getJSONObject("7.13.2"); - assertEquals("INFORMATIONAL", testResult.get("behavior")); - assertEquals("INFORMATIONAL", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test9_1_1() { - JSONObject testResult = jsonObject.getJSONObject("9.1.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test9_1_2() { - JSONObject testResult = jsonObject.getJSONObject("9.1.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 20); - } - - @Test - public void test9_1_3() { - JSONObject testResult = jsonObject.getJSONObject("9.1.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 70); - } - - @Test - public void test9_1_4() { - JSONObject testResult = jsonObject.getJSONObject("9.1.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 375); - } - - @Test - public void test9_1_5() { - JSONObject testResult = jsonObject.getJSONObject("9.1.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 750); - } - - @Test - public void test9_1_6() { - JSONObject testResult = jsonObject.getJSONObject("9.1.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 1000); - } - - @Test - public void test9_2_1() { - JSONObject testResult = jsonObject.getJSONObject("9.2.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } - - @Test - public void test9_2_2() { - JSONObject testResult = jsonObject.getJSONObject("9.2.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 20); - } - - @Test - public void test9_2_3() { - JSONObject testResult = jsonObject.getJSONObject("9.2.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 70); - } - - @Test - public void test9_2_4() { - JSONObject testResult = jsonObject.getJSONObject("9.2.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 250); - } - - @Test - public void test9_2_5() { - JSONObject testResult = jsonObject.getJSONObject("9.2.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 350); - } - - @Test - public void test9_2_6() { - JSONObject testResult = jsonObject.getJSONObject("9.2.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 800); - } - - @Test - public void test9_3_1() { - JSONObject testResult = jsonObject.getJSONObject("9.3.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 2000); - } - - @Test - public void test9_3_2() { - JSONObject testResult = jsonObject.getJSONObject("9.3.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 600); - } - - @Test - public void test9_3_3() { - JSONObject testResult = jsonObject.getJSONObject("9.3.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 300); - } - - @Test - public void test9_3_4() { - JSONObject testResult = jsonObject.getJSONObject("9.3.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 250); - } - - @Test - public void test9_3_5() { - JSONObject testResult = jsonObject.getJSONObject("9.3.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 200); - } - - @Test - public void test9_3_6() { - JSONObject testResult = jsonObject.getJSONObject("9.3.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 175); - } - - @Test - public void test9_3_7() { - JSONObject testResult = jsonObject.getJSONObject("9.3.7"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 175); - } - - - @Test - public void test9_3_8() { - JSONObject testResult = jsonObject.getJSONObject("9.3.8"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 160); - } - - @Test - public void test9_3_9() { - JSONObject testResult = jsonObject.getJSONObject("9.3.9"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 160); - } - - @Test - public void test9_4_1() { - JSONObject testResult = jsonObject.getJSONObject("9.4.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 2300); - } - - @Test - public void test9_4_2() { - JSONObject testResult = jsonObject.getJSONObject("9.4.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 700); - } - - @Test - public void test9_4_3() { - JSONObject testResult = jsonObject.getJSONObject("9.4.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 350); - } - - @Test - public void test9_4_4() { - JSONObject testResult = jsonObject.getJSONObject("9.4.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 175); - } - - @Test - public void test9_4_5() { - JSONObject testResult = jsonObject.getJSONObject("9.4.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 150); - } - - @Test - public void test9_4_6() { - JSONObject testResult = jsonObject.getJSONObject("9.4.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 100); - } - - @Test - public void test9_4_7() { - JSONObject testResult = jsonObject.getJSONObject("9.4.7"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 125); - } - - @Test - public void test9_4_8() { - JSONObject testResult = jsonObject.getJSONObject("9.4.8"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 125); - } - - @Test - public void test9_4_9() { - JSONObject testResult = jsonObject.getJSONObject("9.4.9"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 125); - } - - @Test - public void test9_5_1() { - JSONObject testResult = jsonObject.getJSONObject("9.5.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 3200); - } - - @Test - public void test9_5_2() { - JSONObject testResult = jsonObject.getJSONObject("9.5.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 1300); - } - - @Test - public void test9_5_3() { - JSONObject testResult = jsonObject.getJSONObject("9.5.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 700); - } - - @Test - public void test9_5_4() { - JSONObject testResult = jsonObject.getJSONObject("9.5.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 450); - } - - @Test - public void test9_5_5() { - JSONObject testResult = jsonObject.getJSONObject("9.5.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 250); - } - - @Test - public void test9_5_6() { - JSONObject testResult = jsonObject.getJSONObject("9.5.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 150); - } - - @Test - public void test9_6_1() { - JSONObject testResult = jsonObject.getJSONObject("9.6.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 3000); - } - - @Test - public void test9_6_2() { - JSONObject testResult = jsonObject.getJSONObject("9.6.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 1500); - } - - @Test - public void test9_6_3() { - JSONObject testResult = jsonObject.getJSONObject("9.6.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 750); - } - - @Test - public void test9_6_4() { - JSONObject testResult = jsonObject.getJSONObject("9.6.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 450); - } - - @Test - public void test9_6_5() { - JSONObject testResult = jsonObject.getJSONObject("9.6.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 250); - } - - @Test - public void test9_6_6() { - JSONObject testResult = jsonObject.getJSONObject("9.6.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 200); - } - - @Test - public void test9_7_1() { - JSONObject testResult = jsonObject.getJSONObject("9.7.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 500); - } - - @Test - public void test9_7_2() { - JSONObject testResult = jsonObject.getJSONObject("9.7.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 400); - } - - @Test - public void test9_7_3() { - JSONObject testResult = jsonObject.getJSONObject("9.7.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 400); - } - - @Test - public void test9_7_4() { - JSONObject testResult = jsonObject.getJSONObject("9.7.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 400); - } - - @Test - public void test9_7_5() { - JSONObject testResult = jsonObject.getJSONObject("9.7.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 550); - } - - @Test - public void test9_7_6() { - JSONObject testResult = jsonObject.getJSONObject("9.7.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 850); - } - - @Test - public void test9_8_1() { - JSONObject testResult = jsonObject.getJSONObject("9.8.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 300); - } - - @Test - public void test9_8_2() { - JSONObject testResult = jsonObject.getJSONObject("9.8.2"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 320); - } - - @Test - public void test9_8_3() { - JSONObject testResult = jsonObject.getJSONObject("9.8.3"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 400); - } - - @Test - public void test9_8_4() { - JSONObject testResult = jsonObject.getJSONObject("9.8.4"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 400); - } - - @Test - public void test9_8_5() { - JSONObject testResult = jsonObject.getJSONObject("9.8.5"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 470); - } - - @Test - public void test9_8_6() { - JSONObject testResult = jsonObject.getJSONObject("9.8.6"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 770); - } - - @Test - public void test10_1_1() { - JSONObject testResult = jsonObject.getJSONObject("10.1.1"); - assertEquals("OK", testResult.get("behavior")); - assertEquals("OK", testResult.get("behaviorClose")); - Assume.assumeTrue("Duration: " + testResult.getInt("duration"), - testResult.getInt("duration") < 10); - } -} From a566891046b16f8c231dbcd83ed2578d8d93aea1 Mon Sep 17 00:00:00 2001 From: marci4 Date: Tue, 8 Oct 2024 22:32:30 +0200 Subject: [PATCH 152/165] Correctly clone values provided by the setter Fixes #1437 --- .../PerMessageDeflateExtension.java | 6 ++- .../PerMessageDeflateExtensionTest.java | 39 ++++++++++++++++++- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index f24f9b6c9..af7031869 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -330,7 +330,11 @@ public String getProvidedExtensionAsServer() { @Override public IExtension copyInstance() { - return new PerMessageDeflateExtension(); + PerMessageDeflateExtension clone = new PerMessageDeflateExtension(); + clone.setThreshold(this.getThreshold()); + clone.setClientNoContextTakeover(this.isClientNoContextTakeover()); + clone.setServerNoContextTakeover(this.isServerNoContextTakeover()); + return clone; } /** diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index 0a25383b6..57ba5c228 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -191,8 +191,36 @@ public void testSetClientNoContextTakeover() { @Test public void testCopyInstance() { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - IExtension newDeflateExtension = deflateExtension.copyInstance(); - assertEquals(deflateExtension.toString(), newDeflateExtension.toString()); + PerMessageDeflateExtension newDeflateExtension = (PerMessageDeflateExtension)deflateExtension.copyInstance(); + assertEquals("PerMessageDeflateExtension", newDeflateExtension.toString()); + // Also check the values + assertEquals(deflateExtension.getThreshold(), newDeflateExtension.getThreshold()); + assertEquals(deflateExtension.isClientNoContextTakeover(), newDeflateExtension.isClientNoContextTakeover()); + assertEquals(deflateExtension.isServerNoContextTakeover(), newDeflateExtension.isServerNoContextTakeover()); + // Adjust this to the factory + //assertEquals(deflateExtension.getDeflater(), newDeflateExtension.getDeflater()); + //assertEquals(deflateExtension.getInflater(), newDeflateExtension.getInflater()); + + deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setThreshold(512); + deflateExtension.setServerNoContextTakeover(false); + deflateExtension.setClientNoContextTakeover(true); + newDeflateExtension = (PerMessageDeflateExtension)deflateExtension.copyInstance(); + + assertEquals(deflateExtension.getThreshold(), newDeflateExtension.getThreshold()); + assertEquals(deflateExtension.isClientNoContextTakeover(), newDeflateExtension.isClientNoContextTakeover()); + assertEquals(deflateExtension.isServerNoContextTakeover(), newDeflateExtension.isServerNoContextTakeover()); + + + deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setThreshold(64); + deflateExtension.setServerNoContextTakeover(true); + deflateExtension.setClientNoContextTakeover(false); + newDeflateExtension = (PerMessageDeflateExtension)deflateExtension.copyInstance(); + + assertEquals(deflateExtension.getThreshold(), newDeflateExtension.getThreshold()); + assertEquals(deflateExtension.isClientNoContextTakeover(), newDeflateExtension.isClientNoContextTakeover()); + assertEquals(deflateExtension.isServerNoContextTakeover(), newDeflateExtension.isServerNoContextTakeover()); } @Test @@ -222,4 +250,11 @@ public void testSetDeflater() { assertEquals(deflateExtension.getDeflater().finished(), new Deflater(Deflater.DEFAULT_COMPRESSION, false).finished()); } + @Test + public void testDefaults() { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + assertFalse(deflateExtension.isClientNoContextTakeover()); + assertTrue(deflateExtension.isServerNoContextTakeover()); + assertEquals(1024, deflateExtension.getThreshold()); + } } From 1e9fbbf2c9b22605505d57785848880aa2ad8154 Mon Sep 17 00:00:00 2001 From: marci4 Date: Tue, 8 Oct 2024 23:14:08 +0200 Subject: [PATCH 153/165] Reuse inflater/deflater --- .../permessage_deflate/PerMessageDeflateExtension.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index af7031869..b38ad0928 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -166,7 +166,7 @@ We can check the getRemaining() method to see whether the data we supplied has b Note that this behavior doesn't occur if the message is "first compressed and then fragmented". */ if (inflater.getRemaining() > 0) { - inflater = new Inflater(true); + inflater.reset(); decompress(inputFrame.getPayloadData().array(), output); } @@ -174,7 +174,7 @@ We can check the getRemaining() method to see whether the data we supplied has b decompress(TAIL_BYTES, output); // If context takeover is disabled, inflater can be reset. if (clientNoContextTakeover) { - inflater = new Inflater(true); + inflater.reset(); } } } catch (DataFormatException e) { @@ -244,8 +244,7 @@ public void encodeFrame(Framedata inputFrame) { } if (serverNoContextTakeover) { - deflater.end(); - deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); + deflater.reset(); } } From fe7635bae9aa0f659da7e29194359b5d7454dc59 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 13 Oct 2024 11:36:42 +0200 Subject: [PATCH 154/165] Provide a setter/getter to set the deflater level --- .../PerMessageDeflateExtension.java | 32 +++++++++------- .../PerMessageDeflateExtensionTest.java | 37 ++++++------------- 2 files changed, 30 insertions(+), 39 deletions(-) diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index b38ad0928..b90ddce3b 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -53,23 +53,28 @@ public class PerMessageDeflateExtension extends CompressionExtension { // For WebSocketClients, this variable holds the extension parameters that client himself has requested. private Map requestedParameters = new LinkedHashMap<>(); - private Inflater inflater = new Inflater(true); - private Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); - - public Inflater getInflater() { - return inflater; - } + private int deflaterLevel = Deflater.DEFAULT_COMPRESSION; - public void setInflater(Inflater inflater) { - this.inflater = inflater; - } + private Inflater inflater = new Inflater(true); + private Deflater deflater = new Deflater(this.deflaterLevel, true); - public Deflater getDeflater() { - return deflater; + /** + * Get the compression level used for the compressor. + * @return the compression level (0-9) + */ + public int getDeflaterLevel() { + return this.deflaterLevel; } - public void setDeflater(Deflater deflater) { - this.deflater = deflater; + /** + * Set the compression level used for the compressor. + * @param level the compression level (0-9) + */ + public void setDeflaterLevel(int level) { + this.deflater.setLevel(level); + this.deflaterLevel = level; + //If the compression level is changed, the next invocation of deflate will compress the input available so far with the old level (and may be flushed); the new level will take effect only after that invocation. + this.deflater.deflate(new byte[0]); } /** @@ -333,6 +338,7 @@ public IExtension copyInstance() { clone.setThreshold(this.getThreshold()); clone.setClientNoContextTakeover(this.isClientNoContextTakeover()); clone.setServerNoContextTakeover(this.isServerNoContextTakeover()); + clone.setDeflaterLevel(this.getDeflaterLevel()); return clone; } diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index 57ba5c228..e434be9fb 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -197,64 +197,49 @@ public void testCopyInstance() { assertEquals(deflateExtension.getThreshold(), newDeflateExtension.getThreshold()); assertEquals(deflateExtension.isClientNoContextTakeover(), newDeflateExtension.isClientNoContextTakeover()); assertEquals(deflateExtension.isServerNoContextTakeover(), newDeflateExtension.isServerNoContextTakeover()); - // Adjust this to the factory - //assertEquals(deflateExtension.getDeflater(), newDeflateExtension.getDeflater()); - //assertEquals(deflateExtension.getInflater(), newDeflateExtension.getInflater()); + assertEquals(deflateExtension.getDeflaterLevel(), newDeflateExtension.getDeflaterLevel()); + deflateExtension = new PerMessageDeflateExtension(); deflateExtension.setThreshold(512); deflateExtension.setServerNoContextTakeover(false); deflateExtension.setClientNoContextTakeover(true); + deflateExtension.setDeflaterLevel(Deflater.BEST_COMPRESSION); newDeflateExtension = (PerMessageDeflateExtension)deflateExtension.copyInstance(); assertEquals(deflateExtension.getThreshold(), newDeflateExtension.getThreshold()); assertEquals(deflateExtension.isClientNoContextTakeover(), newDeflateExtension.isClientNoContextTakeover()); assertEquals(deflateExtension.isServerNoContextTakeover(), newDeflateExtension.isServerNoContextTakeover()); + assertEquals(deflateExtension.getDeflaterLevel(), newDeflateExtension.getDeflaterLevel()); deflateExtension = new PerMessageDeflateExtension(); deflateExtension.setThreshold(64); deflateExtension.setServerNoContextTakeover(true); deflateExtension.setClientNoContextTakeover(false); + deflateExtension.setDeflaterLevel(Deflater.NO_COMPRESSION); newDeflateExtension = (PerMessageDeflateExtension)deflateExtension.copyInstance(); assertEquals(deflateExtension.getThreshold(), newDeflateExtension.getThreshold()); assertEquals(deflateExtension.isClientNoContextTakeover(), newDeflateExtension.isClientNoContextTakeover()); assertEquals(deflateExtension.isServerNoContextTakeover(), newDeflateExtension.isServerNoContextTakeover()); + assertEquals(deflateExtension.getDeflaterLevel(), newDeflateExtension.getDeflaterLevel()); } @Test - public void testGetInflater() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertEquals(deflateExtension.getInflater().getRemaining(), new Inflater(true).getRemaining()); - } - - @Test - public void testSetInflater() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - deflateExtension.setInflater(new Inflater(false)); - assertEquals(deflateExtension.getInflater().getRemaining(), new Inflater(false).getRemaining()); - } - - @Test - public void testGetDeflater() { + public void testDeflaterLevel() { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertEquals(deflateExtension.getDeflater().finished(), - new Deflater(Deflater.DEFAULT_COMPRESSION, true).finished()); + assertEquals(Deflater.DEFAULT_COMPRESSION, deflateExtension.getDeflaterLevel()); + deflateExtension.setDeflaterLevel(Deflater.BEST_SPEED); + assertEquals(Deflater.BEST_SPEED, deflateExtension.getDeflaterLevel()); } - @Test - public void testSetDeflater() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - deflateExtension.setDeflater(new Deflater(Deflater.DEFAULT_COMPRESSION, false)); - assertEquals(deflateExtension.getDeflater().finished(), - new Deflater(Deflater.DEFAULT_COMPRESSION, false).finished()); - } @Test public void testDefaults() { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); assertFalse(deflateExtension.isClientNoContextTakeover()); assertTrue(deflateExtension.isServerNoContextTakeover()); assertEquals(1024, deflateExtension.getThreshold()); + assertEquals(Deflater.DEFAULT_COMPRESSION, deflateExtension.getDeflaterLevel()); } } From 4f4aed58c9025e1c5a06f8361651bc8a6d54d221 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 13 Oct 2024 15:53:21 +0200 Subject: [PATCH 155/165] Extends tests to better test the deflater level --- .../PerMessageDeflateExtensionTest.java | 107 ++++++++++++++++++ 1 file changed, 107 insertions(+) diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index e434be9fb..9093ea483 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -1,5 +1,6 @@ package org.java_websocket.extensions; +import static java.util.zip.GZIPInputStream.GZIP_MAGIC; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -7,6 +8,7 @@ import static org.junit.Assert.fail; import java.nio.ByteBuffer; +import java.util.Arrays; import java.util.zip.Deflater; import java.util.zip.Inflater; import org.java_websocket.exceptions.InvalidDataException; @@ -51,6 +53,111 @@ public void testDecodeFrameIfRSVIsNotSet() throws InvalidDataException { assertFalse(frame.isRSV1()); } + @Test + public void testDecodeFrameNoCompression() throws InvalidDataException { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setDeflaterLevel(Deflater.NO_COMPRESSION); + deflateExtension.setThreshold(0); + String str = "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text"; + byte[] message = str.getBytes(); + TextFrame frame = new TextFrame(); + frame.setPayload(ByteBuffer.wrap(message)); + deflateExtension.encodeFrame(frame); + byte[] payloadArray = frame.getPayloadData().array(); + assertArrayEquals(message, Arrays.copyOfRange(payloadArray, 5,payloadArray.length-5)); + assertTrue(frame.isRSV1()); + deflateExtension.decodeFrame(frame); + assertArrayEquals(message, frame.getPayloadData().array()); + } + + @Test + public void testDecodeFrameBestSpeedCompression() throws InvalidDataException { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setDeflaterLevel(Deflater.BEST_SPEED); + deflateExtension.setThreshold(0); + String str = "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text"; + byte[] message = str.getBytes(); + TextFrame frame = new TextFrame(); + frame.setPayload(ByteBuffer.wrap(message)); + + Deflater localDeflater = new Deflater(Deflater.BEST_SPEED,true); + localDeflater.setInput(ByteBuffer.wrap(message).array()); + byte[] buffer = new byte[1024]; + int bytesCompressed = localDeflater.deflate(buffer, 0, buffer.length, Deflater.SYNC_FLUSH); + + deflateExtension.encodeFrame(frame); + byte[] payloadArray = frame.getPayloadData().array(); + assertArrayEquals(Arrays.copyOfRange(buffer,0, bytesCompressed), Arrays.copyOfRange(payloadArray,0,payloadArray.length)); + assertTrue(frame.isRSV1()); + deflateExtension.decodeFrame(frame); + assertArrayEquals(message, frame.getPayloadData().array()); + } + + @Test + public void testDecodeFrameBestCompression() throws InvalidDataException { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setDeflaterLevel(Deflater.BEST_COMPRESSION); + deflateExtension.setThreshold(0); + String str = "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text"; + byte[] message = str.getBytes(); + TextFrame frame = new TextFrame(); + frame.setPayload(ByteBuffer.wrap(message)); + + Deflater localDeflater = new Deflater(Deflater.BEST_COMPRESSION,true); + localDeflater.setInput(ByteBuffer.wrap(message).array()); + byte[] buffer = new byte[1024]; + int bytesCompressed = localDeflater.deflate(buffer, 0, buffer.length, Deflater.SYNC_FLUSH); + + deflateExtension.encodeFrame(frame); + byte[] payloadArray = frame.getPayloadData().array(); + assertArrayEquals(Arrays.copyOfRange(buffer,0, bytesCompressed), Arrays.copyOfRange(payloadArray,0,payloadArray.length)); + assertTrue(frame.isRSV1()); + deflateExtension.decodeFrame(frame); + assertArrayEquals(message, frame.getPayloadData().array()); + } + + @Test + public void testDecodeFrameSwitchCompression() throws InvalidDataException { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); + deflateExtension.setDeflaterLevel(Deflater.NO_COMPRESSION); + deflateExtension.setThreshold(0); + String str = "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text" + + "This is a highly compressable text"; + byte[] message = str.getBytes(); + TextFrame frame = new TextFrame(); + frame.setPayload(ByteBuffer.wrap(message)); + + Deflater localDeflater = new Deflater(Deflater.BEST_COMPRESSION,true); + localDeflater.setInput(ByteBuffer.wrap(message).array()); + byte[] buffer = new byte[1024]; + int bytesCompressed = localDeflater.deflate(buffer, 0, buffer.length, Deflater.SYNC_FLUSH); + + // Change the deflater level after the creation and switch to a new deflater level + // Compression strategy should be applied instantly since we call .deflate manually + deflateExtension.setDeflaterLevel(Deflater.BEST_COMPRESSION); + deflateExtension.encodeFrame(frame); + byte[] payloadArray = frame.getPayloadData().array(); + assertArrayEquals(Arrays.copyOfRange(buffer,0, bytesCompressed), Arrays.copyOfRange(payloadArray,0,payloadArray.length)); + assertTrue(frame.isRSV1()); + deflateExtension.decodeFrame(frame); + assertArrayEquals(message, frame.getPayloadData().array()); + } + @Test public void testEncodeFrame() { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); From dfca00b6ea25e0628aecdd014125c4b8c04599e5 Mon Sep 17 00:00:00 2001 From: marci4 Date: Tue, 22 Oct 2024 23:09:18 +0200 Subject: [PATCH 156/165] Add Constructor with custom compression level --- .../PerMessageDeflateExtension.java | 42 ++++++------ .../PerMessageDeflateExtensionTest.java | 64 +++---------------- 2 files changed, 34 insertions(+), 72 deletions(-) diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java index b90ddce3b..9eb16ca15 100644 --- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java +++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java @@ -13,13 +13,11 @@ import org.java_websocket.extensions.CompressionExtension; import org.java_websocket.extensions.ExtensionRequestData; import org.java_websocket.extensions.IExtension; -import org.java_websocket.framing.BinaryFrame; import org.java_websocket.framing.CloseFrame; import org.java_websocket.framing.ContinuousFrame; import org.java_websocket.framing.DataFrame; import org.java_websocket.framing.Framedata; import org.java_websocket.framing.FramedataImpl1; -import org.java_websocket.framing.TextFrame; /** * PerMessage Deflate Extension (7. The @@ -53,28 +51,37 @@ public class PerMessageDeflateExtension extends CompressionExtension { // For WebSocketClients, this variable holds the extension parameters that client himself has requested. private Map requestedParameters = new LinkedHashMap<>(); - private int deflaterLevel = Deflater.DEFAULT_COMPRESSION; + private final int compressionLevel; - private Inflater inflater = new Inflater(true); - private Deflater deflater = new Deflater(this.deflaterLevel, true); + private final Inflater inflater; + private final Deflater deflater; /** - * Get the compression level used for the compressor. - * @return the compression level (0-9) + * Constructor for the PerMessage Deflate Extension (7. Thepermessage-deflate" Extension) + * + * Uses {@link java.util.zip.Deflater#DEFAULT_COMPRESSION} as the compression level for the {@link java.util.zip.Deflater#Deflater(int)} + */ + public PerMessageDeflateExtension() { + this(Deflater.DEFAULT_COMPRESSION); + } + + /** + * Constructor for the PerMessage Deflate Extension (7. Thepermessage-deflate" Extension) + * + * @param compressionLevel The compression level passed to the {@link java.util.zip.Deflater#Deflater(int)} */ - public int getDeflaterLevel() { - return this.deflaterLevel; + public PerMessageDeflateExtension(int compressionLevel) { + this.compressionLevel = compressionLevel; + this.deflater = new Deflater(this.compressionLevel, true); + this.inflater = new Inflater(true); } /** - * Set the compression level used for the compressor. - * @param level the compression level (0-9) + * Get the compression level used for the compressor. + * @return the compression level */ - public void setDeflaterLevel(int level) { - this.deflater.setLevel(level); - this.deflaterLevel = level; - //If the compression level is changed, the next invocation of deflate will compress the input available so far with the old level (and may be flushed); the new level will take effect only after that invocation. - this.deflater.deflate(new byte[0]); + public int getCompressionLevel() { + return this.compressionLevel; } /** @@ -334,11 +341,10 @@ public String getProvidedExtensionAsServer() { @Override public IExtension copyInstance() { - PerMessageDeflateExtension clone = new PerMessageDeflateExtension(); + PerMessageDeflateExtension clone = new PerMessageDeflateExtension(this.getCompressionLevel()); clone.setThreshold(this.getThreshold()); clone.setClientNoContextTakeover(this.isClientNoContextTakeover()); clone.setServerNoContextTakeover(this.isServerNoContextTakeover()); - clone.setDeflaterLevel(this.getDeflaterLevel()); return clone; } diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index 9093ea483..a4e2c3661 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -1,6 +1,5 @@ package org.java_websocket.extensions; -import static java.util.zip.GZIPInputStream.GZIP_MAGIC; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -10,10 +9,9 @@ import java.nio.ByteBuffer; import java.util.Arrays; import java.util.zip.Deflater; -import java.util.zip.Inflater; + import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.extensions.permessage_deflate.PerMessageDeflateExtension; -import org.java_websocket.framing.BinaryFrame; import org.java_websocket.framing.ContinuousFrame; import org.java_websocket.framing.TextFrame; import org.junit.Test; @@ -55,8 +53,7 @@ public void testDecodeFrameIfRSVIsNotSet() throws InvalidDataException { @Test public void testDecodeFrameNoCompression() throws InvalidDataException { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - deflateExtension.setDeflaterLevel(Deflater.NO_COMPRESSION); + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(Deflater.NO_COMPRESSION); deflateExtension.setThreshold(0); String str = "This is a highly compressable text" + "This is a highly compressable text" @@ -76,8 +73,7 @@ public void testDecodeFrameNoCompression() throws InvalidDataException { @Test public void testDecodeFrameBestSpeedCompression() throws InvalidDataException { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - deflateExtension.setDeflaterLevel(Deflater.BEST_SPEED); + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(Deflater.BEST_SPEED); deflateExtension.setThreshold(0); String str = "This is a highly compressable text" + "This is a highly compressable text" @@ -103,8 +99,7 @@ public void testDecodeFrameBestSpeedCompression() throws InvalidDataException { @Test public void testDecodeFrameBestCompression() throws InvalidDataException { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - deflateExtension.setDeflaterLevel(Deflater.BEST_COMPRESSION); + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(Deflater.BEST_COMPRESSION); deflateExtension.setThreshold(0); String str = "This is a highly compressable text" + "This is a highly compressable text" @@ -128,35 +123,6 @@ public void testDecodeFrameBestCompression() throws InvalidDataException { assertArrayEquals(message, frame.getPayloadData().array()); } - @Test - public void testDecodeFrameSwitchCompression() throws InvalidDataException { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - deflateExtension.setDeflaterLevel(Deflater.NO_COMPRESSION); - deflateExtension.setThreshold(0); - String str = "This is a highly compressable text" - + "This is a highly compressable text" - + "This is a highly compressable text" - + "This is a highly compressable text" - + "This is a highly compressable text"; - byte[] message = str.getBytes(); - TextFrame frame = new TextFrame(); - frame.setPayload(ByteBuffer.wrap(message)); - - Deflater localDeflater = new Deflater(Deflater.BEST_COMPRESSION,true); - localDeflater.setInput(ByteBuffer.wrap(message).array()); - byte[] buffer = new byte[1024]; - int bytesCompressed = localDeflater.deflate(buffer, 0, buffer.length, Deflater.SYNC_FLUSH); - - // Change the deflater level after the creation and switch to a new deflater level - // Compression strategy should be applied instantly since we call .deflate manually - deflateExtension.setDeflaterLevel(Deflater.BEST_COMPRESSION); - deflateExtension.encodeFrame(frame); - byte[] payloadArray = frame.getPayloadData().array(); - assertArrayEquals(Arrays.copyOfRange(buffer,0, bytesCompressed), Arrays.copyOfRange(payloadArray,0,payloadArray.length)); - assertTrue(frame.isRSV1()); - deflateExtension.decodeFrame(frame); - assertArrayEquals(message, frame.getPayloadData().array()); - } @Test public void testEncodeFrame() { @@ -304,41 +270,31 @@ public void testCopyInstance() { assertEquals(deflateExtension.getThreshold(), newDeflateExtension.getThreshold()); assertEquals(deflateExtension.isClientNoContextTakeover(), newDeflateExtension.isClientNoContextTakeover()); assertEquals(deflateExtension.isServerNoContextTakeover(), newDeflateExtension.isServerNoContextTakeover()); - assertEquals(deflateExtension.getDeflaterLevel(), newDeflateExtension.getDeflaterLevel()); + assertEquals(deflateExtension.getCompressionLevel(), newDeflateExtension.getCompressionLevel()); - deflateExtension = new PerMessageDeflateExtension(); + deflateExtension = new PerMessageDeflateExtension(Deflater.BEST_COMPRESSION); deflateExtension.setThreshold(512); deflateExtension.setServerNoContextTakeover(false); deflateExtension.setClientNoContextTakeover(true); - deflateExtension.setDeflaterLevel(Deflater.BEST_COMPRESSION); newDeflateExtension = (PerMessageDeflateExtension)deflateExtension.copyInstance(); assertEquals(deflateExtension.getThreshold(), newDeflateExtension.getThreshold()); assertEquals(deflateExtension.isClientNoContextTakeover(), newDeflateExtension.isClientNoContextTakeover()); assertEquals(deflateExtension.isServerNoContextTakeover(), newDeflateExtension.isServerNoContextTakeover()); - assertEquals(deflateExtension.getDeflaterLevel(), newDeflateExtension.getDeflaterLevel()); + assertEquals(deflateExtension.getCompressionLevel(), newDeflateExtension.getCompressionLevel()); - deflateExtension = new PerMessageDeflateExtension(); + deflateExtension = new PerMessageDeflateExtension(Deflater.NO_COMPRESSION); deflateExtension.setThreshold(64); deflateExtension.setServerNoContextTakeover(true); deflateExtension.setClientNoContextTakeover(false); - deflateExtension.setDeflaterLevel(Deflater.NO_COMPRESSION); newDeflateExtension = (PerMessageDeflateExtension)deflateExtension.copyInstance(); assertEquals(deflateExtension.getThreshold(), newDeflateExtension.getThreshold()); assertEquals(deflateExtension.isClientNoContextTakeover(), newDeflateExtension.isClientNoContextTakeover()); assertEquals(deflateExtension.isServerNoContextTakeover(), newDeflateExtension.isServerNoContextTakeover()); - assertEquals(deflateExtension.getDeflaterLevel(), newDeflateExtension.getDeflaterLevel()); - } - - @Test - public void testDeflaterLevel() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertEquals(Deflater.DEFAULT_COMPRESSION, deflateExtension.getDeflaterLevel()); - deflateExtension.setDeflaterLevel(Deflater.BEST_SPEED); - assertEquals(Deflater.BEST_SPEED, deflateExtension.getDeflaterLevel()); + assertEquals(deflateExtension.getCompressionLevel(), newDeflateExtension.getCompressionLevel()); } @Test @@ -347,6 +303,6 @@ public void testDefaults() { assertFalse(deflateExtension.isClientNoContextTakeover()); assertTrue(deflateExtension.isServerNoContextTakeover()); assertEquals(1024, deflateExtension.getThreshold()); - assertEquals(Deflater.DEFAULT_COMPRESSION, deflateExtension.getDeflaterLevel()); + assertEquals(Deflater.DEFAULT_COMPRESSION, deflateExtension.getCompressionLevel()); } } From 8eae4527f39bb98cdd64df1322e1e8f568033d30 Mon Sep 17 00:00:00 2001 From: PhilipRoman Date: Thu, 14 Nov 2024 15:44:52 +0200 Subject: [PATCH 157/165] Add support for creating server from existing Channel See #1440 The main motivation for this feature is the ability to integrate with on-demand socket activation. --- .../server/WebSocketServer.java | 35 +++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index e4f8790ee..8d11bcf48 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -181,6 +181,30 @@ public WebSocketServer(InetSocketAddress address, int decodercount, List this(address, decodercount, drafts, new HashSet()); } + // Small internal helper function to get around limitations of Java constructors. + private static InetSocketAddress checkAddressOfExistingChannel(ServerSocketChannel existingChannel) { + assert existingChannel.isOpen(); + SocketAddress addr; + try { + addr = existingChannel.getLocalAddress(); + } catch (IOException e) { + throw new IllegalArgumentException("Could not get address of channel passed to WebSocketServer, make sure it is bound", e); + } + if (addr == null) { + throw new IllegalArgumentException("Could not get address of channel passed to WebSocketServer, make sure it is bound"); + } + return (InetSocketAddress)addr; + } + + /** + * @param existingChannel An already open and bound server socket channel, which this server will use. + * For example, it can be System.inheritedChannel() to implement socket activation. + */ + public WebSocketServer(ServerSocketChannel existingChannel) { + this(checkAddressOfExistingChannel(existingChannel)); + this.server = existingChannel; + } + /** * Creates a WebSocketServer that will attempt to bind/listen on the given address, and * comply with Draft version draft. @@ -575,7 +599,10 @@ private void doWrite(SelectionKey key) throws WrappedIOException { private boolean doSetupSelectorAndServerThread() { selectorthread.setName("WebSocketSelector-" + selectorthread.getId()); try { - server = ServerSocketChannel.open(); + if (server == null) { + server = ServerSocketChannel.open(); + // If 'server' is not null, that means WebSocketServer was created from existing channel. + } server.configureBlocking(false); ServerSocket socket = server.socket(); int receiveBufferSize = getReceiveBufferSize(); @@ -583,7 +610,11 @@ private boolean doSetupSelectorAndServerThread() { socket.setReceiveBufferSize(receiveBufferSize); } socket.setReuseAddress(isReuseAddr()); - socket.bind(address, getMaxPendingConnections()); + // Socket may be already bound, if an existing channel was passed to constructor. + // In this case we cannot modify backlog size from pure Java code, so leave it as is. + if (!socket.isBound()) { + socket.bind(address, getMaxPendingConnections()); + } selector = Selector.open(); server.register(selector, server.validOps()); startConnectionLostTimer(); From e5253dc29af0c5640142cb9d0fb4c1c4cbd07c2d Mon Sep 17 00:00:00 2001 From: PhilipRoman Date: Thu, 14 Nov 2024 15:47:26 +0200 Subject: [PATCH 158/165] Add example of using WebSocketServer with systemd socket activation --- src/main/example/SocketActivation.java | 102 ++++++++++++++++++++++++ src/main/example/jws-activation.service | 17 ++++ src/main/example/jws-activation.socket | 9 +++ 3 files changed, 128 insertions(+) create mode 100644 src/main/example/SocketActivation.java create mode 100644 src/main/example/jws-activation.service create mode 100644 src/main/example/jws-activation.socket diff --git a/src/main/example/SocketActivation.java b/src/main/example/SocketActivation.java new file mode 100644 index 000000000..86b0da63a --- /dev/null +++ b/src/main/example/SocketActivation.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2010-2020 Nathan Rajlich + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.ServerSocketChannel; +import java.util.Collections; +import java.util.concurrent.atomic.AtomicInteger; +import org.java_websocket.WebSocket; +import org.java_websocket.drafts.Draft; +import org.java_websocket.drafts.Draft_6455; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.server.WebSocketServer; + +/** + * This is a "smart" chat server which will exit when no more clients are left, in order to demonstrate socket activation + */ +public class SocketActivation extends WebSocketServer { + + AtomicInteger clients = new AtomicInteger(0); + + public SocketActivation(ServerSocketChannel chan) { + super(chan); + } + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + conn.send("Welcome to the server!"); //This method sends a message to the new client + broadcast("new connection: " + handshake.getResourceDescriptor()); //This method sends a message to all clients connected + if(clients.get() == 0) { + broadcast("You are the first client to join"); + } + System.out.println(conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!"); + clients.incrementAndGet(); + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + broadcast(conn + " has left the room!"); + System.out.println(conn + " has left the room!"); + if(clients.decrementAndGet() <= 0) { + System.out.println("No more clients left, exiting"); + System.exit(0); + } + } + + @Override + public void onMessage(WebSocket conn, String message) { + broadcast(message); + System.out.println(conn + ": " + message); + } + + @Override + public void onMessage(WebSocket conn, ByteBuffer message) { + broadcast(message.array()); + System.out.println(conn + ": " + message); + } + + + public static void main(String[] args) throws InterruptedException, IOException { + if(System.inheritedChannel() == null) { + System.err.println("System.inheritedChannel() is null, make sure this program is started with file descriptor zero being a listening socket"); + System.exit(1); + } + SocketActivation s = new SocketActivation((ServerSocketChannel)System.inheritedChannel()); + s.start(); + System.out.println(">>>> SocketActivation started on port: " + s.getPort() + " <<<<"); + } + + @Override + public void onError(WebSocket conn, Exception ex) { + ex.printStackTrace(); + } + + @Override + public void onStart() { + System.out.println("Server started!"); + } + +} diff --git a/src/main/example/jws-activation.service b/src/main/example/jws-activation.service new file mode 100644 index 000000000..0ae3d091a --- /dev/null +++ b/src/main/example/jws-activation.service @@ -0,0 +1,17 @@ +[Unit] +Description=Java-WebSocket systemd activation demo service +After=network.target jws-activation.socket +Requires=jws-activation.socket + +[Service] +Type=simple +# Place the command for running SocketActivation.java in file "$HOME"/jws_activation_command: +ExecStart=/bin/sh %h/jws_activation_run +TimeoutStopSec=5 +StandardError=journal +StandardOutput=journal +# This is very important - systemd will pass the socket as file descriptor zero, which is what Java expects +StandardInput=socket + +[Install] +WantedBy=default.target diff --git a/src/main/example/jws-activation.socket b/src/main/example/jws-activation.socket new file mode 100644 index 000000000..db769c3e1 --- /dev/null +++ b/src/main/example/jws-activation.socket @@ -0,0 +1,9 @@ +[Unit] +Description=Java-WebSocket systemd activation demo socket +PartOf=jws-activation.service + +[Socket] +ListenStream=127.0.0.1:9999 + +[Install] +WantedBy=sockets.target From fcb759530db6b99190722097f9966ac93b2665b7 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 15 Dec 2024 15:55:21 +0100 Subject: [PATCH 159/165] Release 1.6.0 --- CHANGELOG.md | 21 +++++++++++++++++++++ README.markdown | 6 +++--- build.gradle | 2 +- pom.xml | 2 +- 4 files changed, 26 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c0befabb8..6dfbb71ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,26 @@ # Change log +############################################################################### +## Version Release 1.6.0 (2024/12/15) + +#### Breaking Changes + +* [Issue 1434](https://github.com/TooTallNate/Java-WebSocket/issues/1434) - Drop Java 1.7 support ([PR 1435](https://github.com/TooTallNate/Java-WebSocket/pull/1435)) +* [PR 1435](https://github.com/TooTallNate/Java-WebSocket/pull/1435) - Drop support for Java 1.7 + +#### Bugs Fixed + +* [Issue 1437](https://github.com/TooTallNate/Java-WebSocket/issues/1437) - Question: How can the compression threshold be set for the PerMessageDeflateExtension in a Deflate Client? ([PR 1439](https://github.com/TooTallNate/Java-WebSocket/pull/1439)) +* [Issue 1400](https://github.com/TooTallNate/Java-WebSocket/issues/1400) - PerMessageDeflateExtension#setDeflater()/#setInflater() is overwritten in case of no_context_takeover ([PR 1439](https://github.com/TooTallNate/Java-WebSocket/pull/1439)) +* [PR 1439](https://github.com/TooTallNate/Java-WebSocket/pull/1439) - Clone PerMessageDeflateExtension values correctly + +#### New Features + +* [Issue 1440](https://github.com/TooTallNate/Java-WebSocket/issues/1440) - Support for inherited sockets ([PR 1442](https://github.com/TooTallNate/Java-WebSocket/pull/1442)) +* [PR 1442](https://github.com/TooTallNate/Java-WebSocket/pull/1442) - Socket activation + +In this release 4 issues and 3 pull requests were closed. + ############################################################################### ## Version Release 1.5.7 (2024/07/08) diff --git a/README.markdown b/README.markdown index 3376ebc4c..313d11630 100644 --- a/README.markdown +++ b/README.markdown @@ -30,7 +30,7 @@ To use maven add this dependency to your pom.xml: org.java-websocket Java-WebSocket - 1.5.7 + 1.6.0 ``` @@ -41,11 +41,11 @@ mavenCentral() ``` Then you can just add the latest version to your build. ```xml -compile "org.java-websocket:Java-WebSocket:1.5.7" +compile "org.java-websocket:Java-WebSocket:1.6.0" ``` Or this option if you use gradle 7.0 and above. ```xml -implementation 'org.java-websocket:Java-WebSocket:1.5.7' +implementation 'org.java-websocket:Java-WebSocket:1.6.0' ``` #### Logging diff --git a/build.gradle b/build.gradle index 29dcc51b0..d87e04554 100644 --- a/build.gradle +++ b/build.gradle @@ -10,7 +10,7 @@ repositories { } group = 'org.java-websocket' -version = '1.6.0-SNAPSHOT' +version = '1.6.0' sourceCompatibility = 1.8 targetCompatibility = 1.8 diff --git a/pom.xml b/pom.xml index 73c093ae9..c3c2ac77c 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.java-websocket Java-WebSocket jar - 1.6.0-SNAPSHOT + 1.6.0 Java-WebSocket A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket From f66edcbd5e0b36282afac775cbd82ea4483424d9 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 15 Dec 2024 15:59:56 +0100 Subject: [PATCH 160/165] Increase Version to 1.6.1 --- build.gradle | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index d87e04554..bebbfe7a1 100644 --- a/build.gradle +++ b/build.gradle @@ -10,7 +10,7 @@ repositories { } group = 'org.java-websocket' -version = '1.6.0' +version = '1.6.1-SNAPSHOT' sourceCompatibility = 1.8 targetCompatibility = 1.8 diff --git a/pom.xml b/pom.xml index c3c2ac77c..764962750 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.java-websocket Java-WebSocket jar - 1.6.0 + 1.6.1-SNAPSHOT Java-WebSocket A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket From 7be8e7a97ae217a379a4a0e1395854d4bd6a4be2 Mon Sep 17 00:00:00 2001 From: marci4 Date: Sun, 15 Dec 2024 16:02:11 +0100 Subject: [PATCH 161/165] Remove outdated build info badge --- README.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/README.markdown b/README.markdown index 313d11630..75607d3a2 100644 --- a/README.markdown +++ b/README.markdown @@ -1,6 +1,5 @@ Java WebSockets =============== -[![Build Status](https://travis-ci.org/marci4/Java-WebSocket-Dev.svg?branch=master)](https://travis-ci.org/marci4/Java-WebSocket-Dev) [![Javadocs](https://www.javadoc.io/badge/org.java-websocket/Java-WebSocket.svg)](https://www.javadoc.io/doc/org.java-websocket/Java-WebSocket) [![Maven Central](https://img.shields.io/maven-central/v/org.java-websocket/Java-WebSocket.svg)](https://mvnrepository.com/artifact/org.java-websocket/Java-WebSocket) From 1ed042e60a0b455acbc1207c414eb7ce8736e45a Mon Sep 17 00:00:00 2001 From: Marcel Prestel Date: Sun, 26 Jan 2025 19:58:04 +0100 Subject: [PATCH 162/165] Update all dependencies and update to JUnit 5 (#1450) * Update all dependencies Update to JUnit 5 Adjust tests to JUnit 5 Improve Test stability * Set maven java version to 1.8 --- .github/workflows/ci.yml | 6 +- build.gradle | 6 +- pom.xml | 19 +- .../example/SSLServerLetsEncryptExample.java | 4 +- src/main/example/simplelogger.properties | 2 +- .../org/java_websocket/AbstractWebSocket.java | 2 +- .../java/org/java_websocket/AllTests.java | 49 - .../java_websocket/client/AllClientTests.java | 43 - .../java_websocket/client/AttachmentTest.java | 7 +- .../client/ConnectBlockingTest.java | 102 +- .../java_websocket/client/HeadersTest.java | 8 +- .../client/SchemaCheckTest.java | 143 +- .../java_websocket/drafts/AllDraftTests.java | 41 - .../java_websocket/drafts/Draft_6455Test.java | 149 +-- .../exceptions/AllExceptionsTests.java | 50 - .../exceptions/IncompleteExceptionTest.java | 6 +- .../IncompleteHandshakeExceptionTest.java | 9 +- .../exceptions/InvalidDataExceptionTest.java | 25 +- .../InvalidEncodingExceptionTest.java | 11 +- .../exceptions/InvalidFrameExceptionTest.java | 36 +- .../InvalidHandshakeExceptionTest.java | 37 +- .../LimitExceededExceptionTest.java | 23 +- .../exceptions/NotSendableExceptionTest.java | 16 +- .../WebsocketNotConnectedExceptionTest.java | 5 +- .../extensions/AllExtensionTests.java | 42 - .../extensions/CompressionExtensionTest.java | 5 +- .../extensions/DefaultExtensionTest.java | 226 ++-- .../PerMessageDeflateExtensionTest.java | 10 +- .../framing/AllFramingTests.java | 48 - .../framing/BinaryFrameTest.java | 22 +- .../framing/CloseFrameTest.java | 409 +++--- .../framing/ContinuousFrameTest.java | 23 +- .../framing/FramedataImpl1Test.java | 51 +- .../java_websocket/framing/PingFrameTest.java | 125 +- .../java_websocket/framing/PongFrameTest.java | 24 +- .../java_websocket/framing/TextFrameTest.java | 22 +- .../java_websocket/issues/AllIssueTests.java | 54 - .../java_websocket/issues/Issue1142Test.java | 15 +- .../java_websocket/issues/Issue1160Test.java | 20 +- .../java_websocket/issues/Issue1203Test.java | 15 +- .../java_websocket/issues/Issue256Test.java | 48 +- .../java_websocket/issues/Issue580Test.java | 23 +- .../java_websocket/issues/Issue598Test.java | 26 +- .../java_websocket/issues/Issue609Test.java | 15 +- .../java_websocket/issues/Issue621Test.java | 8 +- .../java_websocket/issues/Issue661Test.java | 21 +- .../java_websocket/issues/Issue666Test.java | 230 ++-- .../java_websocket/issues/Issue677Test.java | 20 +- .../java_websocket/issues/Issue713Test.java | 12 +- .../java_websocket/issues/Issue732Test.java | 23 +- .../java_websocket/issues/Issue764Test.java | 6 +- .../java_websocket/issues/Issue765Test.java | 10 +- .../java_websocket/issues/Issue811Test.java | 6 +- .../java_websocket/issues/Issue825Test.java | 6 +- .../java_websocket/issues/Issue834Test.java | 14 +- .../java_websocket/issues/Issue847Test.java | 35 +- .../java_websocket/issues/Issue855Test.java | 6 +- .../java_websocket/issues/Issue879Test.java | 27 +- .../java_websocket/issues/Issue890Test.java | 15 +- .../java_websocket/issues/Issue900Test.java | 6 +- .../java_websocket/issues/Issue941Test.java | 5 +- .../java_websocket/issues/Issue962Test.java | 21 +- .../java_websocket/issues/Issue997Test.java | 268 ++-- .../org/java_websocket/misc/AllMiscTests.java | 41 - .../misc/OpeningHandshakeRejectionTest.java | 428 +++--- .../protocols/AllProtocolTests.java | 42 - .../ProtocolHandshakeRejectionTest.java | 1184 +++++++++-------- .../protocols/ProtocolTest.java | 18 +- .../java_websocket/server/AllServerTests.java | 43 - .../CustomSSLWebSocketServerFactoryTest.java | 12 +- .../server/DaemonThreadTest.java | 24 +- .../DefaultSSLWebSocketServerFactoryTest.java | 12 +- .../DefaultWebSocketServerFactoryTest.java | 13 +- ...LParametersWebSocketServerFactoryTest.java | 12 +- .../server/WebSocketServerTest.java | 13 +- .../org/java_websocket/util/Base64Test.java | 64 +- .../util/ByteBufferUtilsTest.java | 48 +- .../util/CharsetfunctionsTest.java | 25 +- .../org/java_websocket/util/SocketUtil.java | 42 +- .../org/java_websocket/util/ThreadCheck.java | 25 +- 80 files changed, 2245 insertions(+), 2562 deletions(-) delete mode 100644 src/test/java/org/java_websocket/AllTests.java delete mode 100644 src/test/java/org/java_websocket/client/AllClientTests.java delete mode 100644 src/test/java/org/java_websocket/drafts/AllDraftTests.java delete mode 100644 src/test/java/org/java_websocket/exceptions/AllExceptionsTests.java delete mode 100644 src/test/java/org/java_websocket/extensions/AllExtensionTests.java delete mode 100644 src/test/java/org/java_websocket/framing/AllFramingTests.java delete mode 100644 src/test/java/org/java_websocket/issues/AllIssueTests.java delete mode 100644 src/test/java/org/java_websocket/misc/AllMiscTests.java delete mode 100644 src/test/java/org/java_websocket/protocols/AllProtocolTests.java delete mode 100644 src/test/java/org/java_websocket/server/AllServerTests.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 57ed219ec..145292c6c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,6 +1,6 @@ name: Continuous Integration -on: [push] +on: [push, pull_request] jobs: Build: @@ -12,6 +12,8 @@ jobs: with: java-version: '17' distribution: 'temurin' + - name: Maven Version + run: mvn --version - name: Build run: mvn -DskipTests package --file pom.xml @@ -25,5 +27,7 @@ jobs: with: java-version: '17' distribution: 'temurin' + - name: Maven Version + run: mvn --version - name: Test run: mvn test --file pom.xml diff --git a/build.gradle b/build.gradle index bebbfe7a1..3c4723581 100644 --- a/build.gradle +++ b/build.gradle @@ -35,7 +35,7 @@ publishing { } dependencies { - implementation group: 'org.slf4j', name: 'slf4j-api', version: '2.0.13' - testImplementation group: 'org.slf4j', name: 'slf4j-simple', version: '2.0.13' - testImplementation group: 'junit', name: 'junit', version: '4.13.1' + implementation group: 'org.slf4j', name: 'slf4j-api', version: '2.0.15' + testImplementation group: 'org.slf4j', name: 'slf4j-simple', version: '2.0.15' + testImplementation group: 'org.junit', name: 'junit-bom', version: '5.11.4', ext: 'pom' } diff --git a/pom.xml b/pom.xml index 764962750..fa2caa283 100644 --- a/pom.xml +++ b/pom.xml @@ -10,11 +10,13 @@ A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket + 1.8 + 1.8 UTF-8 - 2.0.13 + 2.0.16 - 4.13.1 + 5.11.4 6.4.0 @@ -57,10 +59,11 @@ test - junit - junit + org.junit + junit-bom ${junit.version} - test + pom + import @@ -101,7 +104,7 @@ compile - 7 + 8 @@ -288,8 +291,8 @@ test - junit - junit + org.junit.jupiter + junit-jupiter test diff --git a/src/main/example/SSLServerLetsEncryptExample.java b/src/main/example/SSLServerLetsEncryptExample.java index a048dd2eb..95308aa99 100644 --- a/src/main/example/SSLServerLetsEncryptExample.java +++ b/src/main/example/SSLServerLetsEncryptExample.java @@ -40,7 +40,6 @@ import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; -import javax.xml.bind.DatatypeConverter; import org.java_websocket.server.DefaultSSLWebSocketServerFactory; @@ -98,7 +97,8 @@ private static byte[] parseDERFromPEM(byte[] pem, String beginDelimiter, String String data = new String(pem); String[] tokens = data.split(beginDelimiter); tokens = tokens[1].split(endDelimiter); - return DatatypeConverter.parseBase64Binary(tokens[0]); + // return DatatypeConverter.parseBase64Binary(tokens[0]); + return null; } private static RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) diff --git a/src/main/example/simplelogger.properties b/src/main/example/simplelogger.properties index aa4322e92..794b8ad5a 100644 --- a/src/main/example/simplelogger.properties +++ b/src/main/example/simplelogger.properties @@ -1,5 +1,5 @@ org.slf4j.simpleLogger.logFile=System.out -org.slf4j.simpleLogger.defaultLogLevel=trace +org.slf4j.simpleLogger.defaultLogLevel=off org.slf4j.simpleLogger.showDateTime=true org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss.SSS org.slf4j.simpleLogger.showThreadName=false diff --git a/src/main/java/org/java_websocket/AbstractWebSocket.java b/src/main/java/org/java_websocket/AbstractWebSocket.java index bbb1dc8f0..ae9ce1824 100644 --- a/src/main/java/org/java_websocket/AbstractWebSocket.java +++ b/src/main/java/org/java_websocket/AbstractWebSocket.java @@ -201,7 +201,7 @@ protected void startConnectionLostTimer() { private void restartConnectionLostTimer() { cancelConnectionLostTimer(); connectionLostCheckerService = Executors - .newSingleThreadScheduledExecutor(new NamedThreadFactory("connectionLostChecker", daemon)); + .newSingleThreadScheduledExecutor(new NamedThreadFactory("WebSocketConnectionLostChecker", daemon)); Runnable connectionLostChecker = new Runnable() { /** diff --git a/src/test/java/org/java_websocket/AllTests.java b/src/test/java/org/java_websocket/AllTests.java deleted file mode 100644 index 7285be993..000000000 --- a/src/test/java/org/java_websocket/AllTests.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.util.ByteBufferUtilsTest.class, - org.java_websocket.util.Base64Test.class, - org.java_websocket.client.AllClientTests.class, - org.java_websocket.drafts.AllDraftTests.class, - org.java_websocket.issues.AllIssueTests.class, - org.java_websocket.exceptions.AllExceptionsTests.class, - org.java_websocket.misc.AllMiscTests.class, - org.java_websocket.protocols.AllProtocolTests.class, - org.java_websocket.framing.AllFramingTests.class -}) -/** - * Start all tests - */ -public class AllTests { - -} diff --git a/src/test/java/org/java_websocket/client/AllClientTests.java b/src/test/java/org/java_websocket/client/AllClientTests.java deleted file mode 100644 index 70006f0ac..000000000 --- a/src/test/java/org/java_websocket/client/AllClientTests.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.client; - - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.client.AttachmentTest.class, - org.java_websocket.client.SchemaCheckTest.class, - org.java_websocket.client.HeadersTest.class -}) -/** - * Start all tests for the client - */ -public class AllClientTests { - -} diff --git a/src/test/java/org/java_websocket/client/AttachmentTest.java b/src/test/java/org/java_websocket/client/AttachmentTest.java index 3a094816e..217bdf1b3 100644 --- a/src/test/java/org/java_websocket/client/AttachmentTest.java +++ b/src/test/java/org/java_websocket/client/AttachmentTest.java @@ -25,13 +25,14 @@ package org.java_websocket.client; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; import java.net.URI; import java.net.URISyntaxException; import org.java_websocket.handshake.ServerHandshake; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; public class AttachmentTest { diff --git a/src/test/java/org/java_websocket/client/ConnectBlockingTest.java b/src/test/java/org/java_websocket/client/ConnectBlockingTest.java index fa7797cd8..bb4741043 100644 --- a/src/test/java/org/java_websocket/client/ConnectBlockingTest.java +++ b/src/test/java/org/java_websocket/client/ConnectBlockingTest.java @@ -4,65 +4,75 @@ import java.net.*; import java.util.Set; import java.util.concurrent.*; + import org.java_websocket.WebSocket; import org.java_websocket.handshake.*; import org.java_websocket.client.*; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; import org.java_websocket.enums.ReadyState; -import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.*; public class ConnectBlockingTest { - @Test(timeout = 1000) - public void test_ConnectBlockingCleanup() throws Throwable { + @Test + @Timeout(1000) + public void test_ConnectBlockingCleanup() throws Throwable { + + Set threadSet1 = Thread.getAllStackTraces().keySet(); + final CountDownLatch ready = new CountDownLatch(1); + final CountDownLatch accepted = new CountDownLatch(1); + + final int port = SocketUtil.getAvailablePort(); + + /* TCP server which listens to a port, but does not answer handshake */ + Thread server = new Thread(new Runnable() { + @Override + public void run() { + try { + ServerSocket serverSocket = new ServerSocket(port); + serverSocket.setReuseAddress(true); + ready.countDown(); + Socket clientSocket = serverSocket.accept(); + accepted.countDown(); + } catch (Throwable t) { + assertInstanceOf(InterruptedException.class, t); + } + } + }); + server.start(); + ready.await(); - Set threadSet1 = Thread.getAllStackTraces().keySet(); - final CountDownLatch ready = new CountDownLatch(1); - final CountDownLatch accepted = new CountDownLatch(1); + WebSocketClient client = new WebSocketClient(URI.create("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshake) { + } - final int port = SocketUtil.getAvailablePort(); + @Override + public void onClose(int code, String reason, boolean remote) { + } - /* TCP server which listens to a port, but does not answer handshake */ - Thread server = new Thread(new Runnable() { - @Override - public void run() { - try { - ServerSocket serverSocket = new ServerSocket(port); - ready.countDown(); - Socket clientSocket = serverSocket.accept(); - accepted.countDown(); - } catch (Throwable t) { - assertTrue(t instanceof InterruptedException); - } - } - }); - server.start(); - ready.await(); + @Override + public void onMessage(String message) { + } - WebSocketClient client = new WebSocketClient(URI.create("ws://localhost:" + port)) { - @Override - public void onOpen(ServerHandshake handshake) { - } - @Override - public void onClose(int code, String reason, boolean remote) {} - @Override - public void onMessage(String message) {} - @Override - public void onError(Exception ex) { - ex.printStackTrace(); - } - }; - boolean connected = client.connectBlocking(100, TimeUnit.MILLISECONDS); - assertEquals("TCP socket should have been accepted", 0, accepted.getCount()); - assertFalse("WebSocket should not be connected (as server didn't send handshake)", connected); + @Override + public void onError(Exception ex) { + ex.printStackTrace(); + } + }; + boolean connected = client.connectBlocking(100, TimeUnit.MILLISECONDS); + assertEquals( 0, accepted.getCount(), "TCP socket should have been accepted"); + assertFalse(connected, "WebSocket should not be connected (as server didn't send handshake)"); - server.interrupt(); - server.join(); + server.interrupt(); + server.join(); - Set threadSet2 = Thread.getAllStackTraces().keySet(); - assertEquals("no threads left over", threadSet1, threadSet2); - assertTrue("WebSocket is in closed state", client.getReadyState() == ReadyState.CLOSED || client.getReadyState() == ReadyState.NOT_YET_CONNECTED); - } + Set threadSet2 = Thread.getAllStackTraces().keySet(); + assertEquals(threadSet1, threadSet2, "no threads left over"); + assertTrue(client.getReadyState() == ReadyState.CLOSED || client.getReadyState() == ReadyState.NOT_YET_CONNECTED, "WebSocket is in closed state"); + } } diff --git a/src/test/java/org/java_websocket/client/HeadersTest.java b/src/test/java/org/java_websocket/client/HeadersTest.java index 7d31422b5..8d60cf005 100644 --- a/src/test/java/org/java_websocket/client/HeadersTest.java +++ b/src/test/java/org/java_websocket/client/HeadersTest.java @@ -25,15 +25,15 @@ package org.java_websocket.client; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import org.java_websocket.handshake.ServerHandshake; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; public class HeadersTest { diff --git a/src/test/java/org/java_websocket/client/SchemaCheckTest.java b/src/test/java/org/java_websocket/client/SchemaCheckTest.java index 30f13e6f9..af36e5c66 100644 --- a/src/test/java/org/java_websocket/client/SchemaCheckTest.java +++ b/src/test/java/org/java_websocket/client/SchemaCheckTest.java @@ -1,85 +1,86 @@ package org.java_websocket.client; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import java.net.URI; import java.net.URISyntaxException; -import org.java_websocket.handshake.ServerHandshake; -import org.junit.Test; - -public class SchemaCheckTest { - - @Test - public void testSchemaCheck() throws URISyntaxException { - final String[] invalidCase = { - "http://localhost:80", - "http://localhost:81", - "http://localhost", - "https://localhost:443", - "https://localhost:444", - "https://localhost", - "any://localhost", - "any://localhost:82", - }; - final Exception[] exs = new Exception[invalidCase.length]; - for (int i = 0; i < invalidCase.length; i++) { - final int finalI = i; - new WebSocketClient(new URI(invalidCase[finalI])) { - @Override - public void onOpen(ServerHandshake handshakedata) { - - } - @Override - public void onMessage(String message) { - - } - - @Override - public void onClose(int code, String reason, boolean remote) { - - } - - @Override - public void onError(Exception ex) { - exs[finalI] = ex; - } - }.run(); - } - for (Exception exception : exs) { - assertTrue(exception instanceof IllegalArgumentException); - } - final String[] validCase = { - "ws://localhost", - "ws://localhost:80", - "ws://localhost:81", - "wss://localhost", - "wss://localhost:443", - "wss://localhost:444" - }; - for (String s : validCase) { - new WebSocketClient(new URI(s)) { - @Override - public void onOpen(ServerHandshake handshakedata) { +import org.java_websocket.handshake.ServerHandshake; +import org.junit.jupiter.api.Test; - } +import static org.junit.jupiter.api.Assertions.*; - @Override - public void onMessage(String message) { +public class SchemaCheckTest { + @Test + public void testSchemaCheck() throws URISyntaxException { + final String[] invalidCase = { + "http://localhost:80", + "http://localhost:81", + "http://localhost", + "https://localhost:443", + "https://localhost:444", + "https://localhost", + "any://localhost", + "any://localhost:82", + }; + final Exception[] exs = new Exception[invalidCase.length]; + for (int i = 0; i < invalidCase.length; i++) { + final int finalI = i; + new WebSocketClient(new URI(invalidCase[finalI])) { + @Override + public void onOpen(ServerHandshake handshakedata) { + + } + + @Override + public void onMessage(String message) { + + } + + @Override + public void onClose(int code, String reason, boolean remote) { + + } + + @Override + public void onError(Exception ex) { + exs[finalI] = ex; + } + }.run(); } - - @Override - public void onClose(int code, String reason, boolean remote) { - + for (Exception exception : exs) { + assertInstanceOf(IllegalArgumentException.class, exception); } - - @Override - public void onError(Exception ex) { - assertFalse(ex instanceof IllegalArgumentException); + final String[] validCase = { + "ws://localhost", + "ws://localhost:80", + "ws://localhost:81", + "wss://localhost", + "wss://localhost:443", + "wss://localhost:444" + }; + for (String s : validCase) { + new WebSocketClient(new URI(s)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + + } + + @Override + public void onMessage(String message) { + + } + + @Override + public void onClose(int code, String reason, boolean remote) { + + } + + @Override + public void onError(Exception ex) { + assertFalse(ex instanceof IllegalArgumentException); + } + }.run(); } - }.run(); } - } } diff --git a/src/test/java/org/java_websocket/drafts/AllDraftTests.java b/src/test/java/org/java_websocket/drafts/AllDraftTests.java deleted file mode 100644 index 39d2fa3fc..000000000 --- a/src/test/java/org/java_websocket/drafts/AllDraftTests.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.drafts; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.drafts.Draft_6455Test.class -}) -/** - * Start all tests for drafts - */ -public class AllDraftTests { - -} diff --git a/src/test/java/org/java_websocket/drafts/Draft_6455Test.java b/src/test/java/org/java_websocket/drafts/Draft_6455Test.java index d272de7fe..41850b32e 100644 --- a/src/test/java/org/java_websocket/drafts/Draft_6455Test.java +++ b/src/test/java/org/java_websocket/drafts/Draft_6455Test.java @@ -25,13 +25,6 @@ package org.java_websocket.drafts; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; @@ -49,7 +42,9 @@ import org.java_websocket.protocols.IProtocol; import org.java_websocket.protocols.Protocol; import org.java_websocket.util.Charsetfunctions; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class Draft_6455Test { @@ -90,33 +85,33 @@ public void testConstructor() throws Exception { //Fine } try { - Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), null); + Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), null); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { //Fine } try { - Draft_6455 draft_6455 = new Draft_6455(null, Collections.emptyList()); + Draft_6455 draft_6455 = new Draft_6455(null, Collections.emptyList()); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { //Fine } try { - Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.emptyList(), -1); + Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList(), -1); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { //Fine } try { - Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.emptyList(), 0); + Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList(), 0); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { //Fine } - Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.emptyList()); + Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList()); assertEquals(1, draft_6455.getKnownExtensions().size()); assertEquals(0, draft_6455.getKnownProtocols().size()); } @@ -140,13 +135,13 @@ public void testGetKnownExtensions() throws Exception { @Test public void testGetProtocol() throws Exception { - Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.emptyList()); + Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList()); assertNull(draft_6455.getProtocol()); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); assertNull(draft_6455.getProtocol()); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat"))); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); assertNull(draft_6455.getProtocol()); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); assertNotNull(draft_6455.getProtocol()); @@ -156,24 +151,24 @@ public void testGetProtocol() throws Exception { public void testGetKnownProtocols() throws Exception { Draft_6455 draft_6455 = new Draft_6455(); assertEquals(1, draft_6455.getKnownProtocols().size()); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.emptyList()); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList()); assertEquals(0, draft_6455.getKnownProtocols().size()); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat"))); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); assertEquals(1, draft_6455.getKnownProtocols().size()); ArrayList protocols = new ArrayList(); protocols.add(new Protocol("chat")); protocols.add(new Protocol("test")); - draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); assertEquals(2, draft_6455.getKnownProtocols().size()); } @Test public void testCopyInstance() throws Exception { Draft_6455 draft_6455 = new Draft_6455( - Collections.singletonList(new TestExtension()), - Collections.singletonList(new Protocol("chat"))); + Collections.singletonList(new TestExtension()), + Collections.singletonList(new Protocol("chat"))); Draft_6455 draftCopy = (Draft_6455) draft_6455.copyInstance(); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); assertNotEquals(draft_6455, draftCopy); @@ -186,7 +181,7 @@ public void testCopyInstance() throws Exception { @Test public void testReset() throws Exception { Draft_6455 draft_6455 = new Draft_6455( - Collections.singletonList(new TestExtension()), 100); + Collections.singletonList(new TestExtension()), 100); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); List extensionList = new ArrayList(draft_6455.getKnownExtensions()); List protocolList = new ArrayList(draft_6455.getKnownProtocols()); @@ -212,22 +207,22 @@ public void testToString() throws Exception { draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); assertEquals("Draft_6455 extension: DefaultExtension protocol: max frame size: 2147483647", draft_6455.toString()); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat"))); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); assertEquals("Draft_6455 extension: DefaultExtension max frame size: 2147483647", draft_6455.toString()); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); assertEquals("Draft_6455 extension: DefaultExtension protocol: chat max frame size: 2147483647", draft_6455.toString()); - draft_6455 = new Draft_6455(Collections.singletonList(new TestExtension()), - Collections.singletonList(new Protocol("chat"))); + draft_6455 = new Draft_6455(Collections.singletonList(new TestExtension()), + Collections.singletonList(new Protocol("chat"))); assertEquals("Draft_6455 extension: DefaultExtension max frame size: 2147483647", draft_6455.toString()); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); assertEquals("Draft_6455 extension: TestExtension protocol: chat max frame size: 2147483647", draft_6455.toString()); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")), 10); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")), 10); assertEquals("Draft_6455 extension: DefaultExtension max frame size: 10", draft_6455.toString()); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); @@ -240,8 +235,8 @@ public void testEquals() throws Exception { Draft draft0 = new Draft_6455(); Draft draft1 = draft0.copyInstance(); assertEquals(draft0, draft1); - Draft draft2 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat"))); + Draft draft2 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); Draft draft3 = draft2.copyInstance(); assertEquals(draft2, draft3); assertEquals(draft0, draft2); @@ -281,8 +276,8 @@ public void testEquals() throws Exception { public void testHashCode() throws Exception { Draft draft0 = new Draft_6455(); Draft draft1 = draft0.copyInstance(); - Draft draft2 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat"))); + Draft draft2 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); Draft draft3 = draft2.copyInstance(); assertEquals(draft2.hashCode(), draft3.hashCode()); assertEquals(draft0.hashCode(), draft2.hashCode()); @@ -337,8 +332,8 @@ public void acceptHandshakeAsServer() throws Exception { draft_6455.acceptHandshakeAsServer(handshakedataExtension)); assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension)); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat"))); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); assertEquals(HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsServer(handshakedata)); assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer(handshakedataProtocol)); assertEquals(HandshakeState.NOT_MATCHED, @@ -348,7 +343,7 @@ public void acceptHandshakeAsServer() throws Exception { ArrayList protocols = new ArrayList(); protocols.add(new Protocol("chat")); protocols.add(new Protocol("")); - draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer(handshakedata)); assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer(handshakedataProtocol)); assertEquals(HandshakeState.MATCHED, @@ -374,21 +369,21 @@ public void acceptHandshakeAsClient() throws Exception { assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); response.put("Sec-WebSocket-Protocol", "chat"); assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat"))); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); ArrayList protocols = new ArrayList(); protocols.add(new Protocol("")); protocols.add(new Protocol("chat")); - draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.emptyList()); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList()); assertEquals(HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); protocols.clear(); protocols.add(new Protocol("chat3")); protocols.add(new Protocol("3chat")); - draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); assertEquals(HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); } @@ -401,28 +396,28 @@ public void postProcessHandshakeRequestAsClient() throws Exception { assertEquals("Upgrade", request.getFieldValue("Connection")); assertEquals("13", request.getFieldValue("Sec-WebSocket-Version")); assertTrue(request.hasFieldValue("Sec-WebSocket-Key")); - assertTrue(!request.hasFieldValue("Sec-WebSocket-Extensions")); - assertTrue(!request.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(request.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(request.hasFieldValue("Sec-WebSocket-Protocol")); ArrayList protocols = new ArrayList(); protocols.add(new Protocol("chat")); - draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); request = new HandshakeImpl1Client(); draft_6455.postProcessHandshakeRequestAsClient(request); - assertTrue(!request.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(request.hasFieldValue("Sec-WebSocket-Extensions")); assertEquals("chat", request.getFieldValue("Sec-WebSocket-Protocol")); protocols.add(new Protocol("chat2")); - draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); request = new HandshakeImpl1Client(); draft_6455.postProcessHandshakeRequestAsClient(request); - assertTrue(!request.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(request.hasFieldValue("Sec-WebSocket-Extensions")); assertEquals("chat, chat2", request.getFieldValue("Sec-WebSocket-Protocol")); protocols.clear(); protocols.add(new Protocol("")); - draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); request = new HandshakeImpl1Client(); draft_6455.postProcessHandshakeRequestAsClient(request); - assertTrue(!request.hasFieldValue("Sec-WebSocket-Extensions")); - assertTrue(!request.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(request.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(request.hasFieldValue("Sec-WebSocket-Protocol")); } @Test @@ -439,66 +434,66 @@ public void postProcessHandshakeResponseAsServer() throws Exception { assertEquals("TooTallNate Java-WebSocket", response.getFieldValue("Server")); assertEquals("upgrade", response.getFieldValue("Connection")); assertEquals("websocket", response.getFieldValue("Upgrade")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Protocol")); response = new HandshakeImpl1Server(); draft_6455.acceptHandshakeAsServer(handshakedata); draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); response = new HandshakeImpl1Server(); draft_6455.acceptHandshakeAsServer(handshakedataProtocol); draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); response = new HandshakeImpl1Server(); draft_6455.acceptHandshakeAsServer(handshakedataExtension); draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); response = new HandshakeImpl1Server(); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); response = new HandshakeImpl1Server(); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat"))); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); draft_6455.acceptHandshakeAsServer(handshakedataProtocol); draft_6455.postProcessHandshakeResponseAsServer(request, response); assertEquals("chat", response.getFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); response = new HandshakeImpl1Server(); draft_6455.reset(); draft_6455.acceptHandshakeAsServer(handshakedataExtension); draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); response = new HandshakeImpl1Server(); draft_6455.reset(); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); draft_6455.postProcessHandshakeResponseAsServer(request, response); assertEquals("chat", response.getFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); ArrayList protocols = new ArrayList(); protocols.add(new Protocol("test")); protocols.add(new Protocol("chat")); - draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); draft_6455.acceptHandshakeAsServer(handshakedataProtocol); draft_6455.postProcessHandshakeResponseAsServer(request, response); assertEquals("test", response.getFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); response = new HandshakeImpl1Server(); draft_6455.reset(); draft_6455.acceptHandshakeAsServer(handshakedataExtension); draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); response = new HandshakeImpl1Server(); draft_6455.reset(); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); draft_6455.postProcessHandshakeResponseAsServer(request, response); assertEquals("test", response.getFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); // issue #1053 : check the exception - missing Sec-WebSocket-Key response = new HandshakeImpl1Server(); @@ -552,7 +547,7 @@ public void createFramesText() throws Exception { } - private class TestExtension extends DefaultExtension { + private static class TestExtension extends DefaultExtension { @Override public int hashCode() { diff --git a/src/test/java/org/java_websocket/exceptions/AllExceptionsTests.java b/src/test/java/org/java_websocket/exceptions/AllExceptionsTests.java deleted file mode 100644 index f0e121a8d..000000000 --- a/src/test/java/org/java_websocket/exceptions/AllExceptionsTests.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.exceptions; - - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.exceptions.IncompleteExceptionTest.class, - org.java_websocket.exceptions.IncompleteHandshakeExceptionTest.class, - org.java_websocket.exceptions.InvalidDataExceptionTest.class, - org.java_websocket.exceptions.InvalidEncodingExceptionTest.class, - org.java_websocket.exceptions.InvalidFrameExceptionTest.class, - org.java_websocket.exceptions.InvalidHandshakeExceptionTest.class, - org.java_websocket.exceptions.LimitExceededExceptionTest.class, - org.java_websocket.exceptions.NotSendableExceptionTest.class, - org.java_websocket.exceptions.WebsocketNotConnectedExceptionTest.class -}) -/** - * Start all tests for the exceptions - */ -public class AllExceptionsTests { - -} diff --git a/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java b/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java index 9a9916dea..de831c393 100644 --- a/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java @@ -25,9 +25,9 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * JUnit Test for the IncompleteException class @@ -37,6 +37,6 @@ public class IncompleteExceptionTest { @Test public void testConstructor() { IncompleteException incompleteException = new IncompleteException(42); - assertEquals("The argument should be set", 42, incompleteException.getPreferredSize()); + assertEquals(42, incompleteException.getPreferredSize(), "The argument should be set"); } } diff --git a/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java b/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java index 9cf1829fd..0506c1530 100644 --- a/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java @@ -25,9 +25,10 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * JUnit Test for the IncompleteHandshakeException class @@ -38,8 +39,8 @@ public class IncompleteHandshakeExceptionTest { public void testConstructor() { IncompleteHandshakeException incompleteHandshakeException = new IncompleteHandshakeException( 42); - assertEquals("The argument should be set", 42, incompleteHandshakeException.getPreferredSize()); + assertEquals( 42, incompleteHandshakeException.getPreferredSize(), "The argument should be set"); incompleteHandshakeException = new IncompleteHandshakeException(); - assertEquals("The default has to be 0", 0, incompleteHandshakeException.getPreferredSize()); + assertEquals(0, incompleteHandshakeException.getPreferredSize(), "The default has to be 0"); } } diff --git a/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java index c9c4e5849..332f8fd22 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java @@ -25,9 +25,10 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * JUnit Test for the InvalidDataException class @@ -37,19 +38,19 @@ public class InvalidDataExceptionTest { @Test public void testConstructor() { InvalidDataException invalidDataException = new InvalidDataException(42); - assertEquals("The close code has to be the argument", 42, invalidDataException.getCloseCode()); + assertEquals(42, invalidDataException.getCloseCode(), "The close code has to be the argument"); invalidDataException = new InvalidDataException(42, "Message"); - assertEquals("The close code has to be the argument", 42, invalidDataException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", - invalidDataException.getMessage()); + assertEquals(42, invalidDataException.getCloseCode(), "The close code has to be the argument"); + assertEquals( "Message", + invalidDataException.getMessage(), "The message has to be the argument"); Exception e = new Exception(); invalidDataException = new InvalidDataException(42, "Message", e); - assertEquals("The close code has to be the argument", 42, invalidDataException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", - invalidDataException.getMessage()); - assertEquals("The throwable has to be the argument", e, invalidDataException.getCause()); + assertEquals( 42, invalidDataException.getCloseCode(), "The close code has to be the argument"); + assertEquals( "Message", + invalidDataException.getMessage(), "The message has to be the argument"); + assertEquals(e, invalidDataException.getCause(), "The throwable has to be the argument"); invalidDataException = new InvalidDataException(42, e); - assertEquals("The close code has to be the argument", 42, invalidDataException.getCloseCode()); - assertEquals("The throwable has to be the argument", e, invalidDataException.getCause()); + assertEquals(42, invalidDataException.getCloseCode(), "The close code has to be the argument"); + assertEquals(e, invalidDataException.getCause(), "The throwable has to be the argument"); } } diff --git a/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java index 96e005be5..2edb0ad31 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java @@ -25,11 +25,12 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.Test; import java.io.UnsupportedEncodingException; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * JUnit Test for the InvalidEncodingException class @@ -41,8 +42,8 @@ public void testConstructor() { UnsupportedEncodingException unsupportedEncodingException = new UnsupportedEncodingException(); InvalidEncodingException invalidEncodingException = new InvalidEncodingException( unsupportedEncodingException); - assertEquals("The argument has to be the provided exception", unsupportedEncodingException, - invalidEncodingException.getEncodingException()); + assertEquals(unsupportedEncodingException, + invalidEncodingException.getEncodingException(), "The argument has to be the provided exception"); try { invalidEncodingException = new InvalidEncodingException(null); fail("IllegalArgumentException should be thrown"); diff --git a/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java index 27a2e0dbd..359e6d69b 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java @@ -25,10 +25,11 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertEquals; import org.java_websocket.framing.CloseFrame; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the InvalidFrameException class @@ -38,30 +39,29 @@ public class InvalidFrameExceptionTest { @Test public void testConstructor() { InvalidFrameException invalidFrameException = new InvalidFrameException(); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, - invalidFrameException.getCloseCode()); + assertEquals( CloseFrame.PROTOCOL_ERROR, + invalidFrameException.getCloseCode(), "The close code has to be PROTOCOL_ERROR"); invalidFrameException = new InvalidFrameException("Message"); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, - invalidFrameException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", - invalidFrameException.getMessage()); + assertEquals(CloseFrame.PROTOCOL_ERROR, + invalidFrameException.getCloseCode(), "The close code has to be PROTOCOL_ERROR"); + assertEquals("Message", + invalidFrameException.getMessage(), "The message has to be the argument"); Exception e = new Exception(); invalidFrameException = new InvalidFrameException("Message", e); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, - invalidFrameException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", - invalidFrameException.getMessage()); - assertEquals("The throwable has to be the argument", e, invalidFrameException.getCause()); + assertEquals(CloseFrame.PROTOCOL_ERROR, + invalidFrameException.getCloseCode(), "The close code has to be PROTOCOL_ERROR"); + assertEquals("Message", + invalidFrameException.getMessage(), "The message has to be the argument"); + assertEquals(e, invalidFrameException.getCause(), "The throwable has to be the argument"); invalidFrameException = new InvalidFrameException(e); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, - invalidFrameException.getCloseCode()); - assertEquals("The throwable has to be the argument", e, invalidFrameException.getCause()); + assertEquals(CloseFrame.PROTOCOL_ERROR, + invalidFrameException.getCloseCode(), "The close code has to be PROTOCOL_ERROR"); + assertEquals(e, invalidFrameException.getCause(), "The throwable has to be the argument"); } @Test public void testExtends() { InvalidFrameException invalidFrameException = new InvalidFrameException(); - assertEquals("InvalidFrameException must extend InvalidDataException", true, - invalidFrameException instanceof InvalidDataException); + assertInstanceOf(InvalidDataException.class, invalidFrameException, "InvalidFrameException must extend InvalidDataException"); } } diff --git a/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java index da9fdc94b..0b8863c0b 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java @@ -25,10 +25,10 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertEquals; - import org.java_websocket.framing.CloseFrame; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the InvalidHandshakeException class @@ -38,31 +38,30 @@ public class InvalidHandshakeExceptionTest { @Test public void testConstructor() { InvalidHandshakeException invalidHandshakeException = new InvalidHandshakeException(); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, - invalidHandshakeException.getCloseCode()); + assertEquals( CloseFrame.PROTOCOL_ERROR, + invalidHandshakeException.getCloseCode(), "The close code has to be PROTOCOL_ERROR"); invalidHandshakeException = new InvalidHandshakeException("Message"); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, - invalidHandshakeException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", - invalidHandshakeException.getMessage()); + assertEquals( CloseFrame.PROTOCOL_ERROR, + invalidHandshakeException.getCloseCode(), "The close code has to be PROTOCOL_ERROR"); + assertEquals( "Message", + invalidHandshakeException.getMessage(), "The message has to be the argument"); Exception e = new Exception(); invalidHandshakeException = new InvalidHandshakeException("Message", e); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, - invalidHandshakeException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", - invalidHandshakeException.getMessage()); - assertEquals("The throwable has to be the argument", e, invalidHandshakeException.getCause()); + assertEquals(CloseFrame.PROTOCOL_ERROR, + invalidHandshakeException.getCloseCode(), "The close code has to be PROTOCOL_ERROR"); + assertEquals( "Message", + invalidHandshakeException.getMessage(), "The message has to be the argument"); + assertEquals(e, invalidHandshakeException.getCause(), "The throwable has to be the argument"); invalidHandshakeException = new InvalidHandshakeException(e); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, - invalidHandshakeException.getCloseCode()); - assertEquals("The throwable has to be the argument", e, invalidHandshakeException.getCause()); + assertEquals(CloseFrame.PROTOCOL_ERROR, + invalidHandshakeException.getCloseCode(), "The close code has to be PROTOCOL_ERROR"); + assertEquals(e, invalidHandshakeException.getCause(), "The throwable has to be the argument"); } @Test public void testExtends() { InvalidHandshakeException invalidHandshakeException = new InvalidHandshakeException(); - assertEquals("InvalidHandshakeException must extend InvalidDataException", true, - invalidHandshakeException instanceof InvalidDataException); + assertInstanceOf(InvalidDataException.class, invalidHandshakeException, "InvalidHandshakeException must extend InvalidDataException"); } } diff --git a/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java b/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java index 4cc6ca9a6..1677da7b0 100644 --- a/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java @@ -25,10 +25,10 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertEquals; - import org.java_websocket.framing.CloseFrame; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the InvalidEncodingException class @@ -38,20 +38,19 @@ public class LimitExceededExceptionTest { @Test public void testConstructor() { LimitExceededException limitExceededException = new LimitExceededException(); - assertEquals("The close code has to be TOOBIG", CloseFrame.TOOBIG, - limitExceededException.getCloseCode()); - assertEquals("The message has to be empty", null, limitExceededException.getMessage()); + assertEquals(CloseFrame.TOOBIG, + limitExceededException.getCloseCode(), "The close code has to be TOOBIG"); + assertNull(limitExceededException.getMessage(), "The message has to be empty"); limitExceededException = new LimitExceededException("Message"); - assertEquals("The close code has to be TOOBIG", CloseFrame.TOOBIG, - limitExceededException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", - limitExceededException.getMessage()); + assertEquals(CloseFrame.TOOBIG, + limitExceededException.getCloseCode(), "The close code has to be TOOBIG"); + assertEquals( "Message", + limitExceededException.getMessage(), "The message has to be the argument"); } @Test public void testExtends() { LimitExceededException limitExceededException = new LimitExceededException(); - assertEquals("LimitExceededException must extend InvalidDataException", true, - limitExceededException instanceof InvalidDataException); + assertInstanceOf(InvalidDataException.class, limitExceededException, "LimitExceededException must extend InvalidDataException"); } } diff --git a/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java b/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java index 0fb2440fd..044e84d2c 100644 --- a/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java @@ -25,9 +25,9 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * JUnit Test for the NotSendableException class @@ -37,14 +37,14 @@ public class NotSendableExceptionTest { @Test public void testConstructor() { NotSendableException notSendableException = new NotSendableException("Message"); - assertEquals("The message has to be the argument", "Message", - notSendableException.getMessage()); + assertEquals("Message", + notSendableException.getMessage(), "The message has to be the argument"); Exception e = new Exception(); notSendableException = new NotSendableException(e); - assertEquals("The throwable has to be the argument", e, notSendableException.getCause()); + assertEquals( e, notSendableException.getCause(), "The throwable has to be the argument"); notSendableException = new NotSendableException("Message", e); - assertEquals("The message has to be the argument", "Message", - notSendableException.getMessage()); - assertEquals("The throwable has to be the argument", e, notSendableException.getCause()); + assertEquals("Message", + notSendableException.getMessage(), "The message has to be the argument"); + assertEquals(e, notSendableException.getCause(), "The throwable has to be the argument"); } } diff --git a/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java b/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java index e163b2260..3f21c4460 100644 --- a/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java @@ -25,9 +25,10 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertNotNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * JUnit Test for the WebsocketNotConnectedException class diff --git a/src/test/java/org/java_websocket/extensions/AllExtensionTests.java b/src/test/java/org/java_websocket/extensions/AllExtensionTests.java deleted file mode 100644 index 3cbf552e6..000000000 --- a/src/test/java/org/java_websocket/extensions/AllExtensionTests.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.extensions; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.extensions.DefaultExtensionTest.class, - org.java_websocket.extensions.CompressionExtensionTest.class -}) -/** - * Start all tests for extensions - */ -public class AllExtensionTests { - -} diff --git a/src/test/java/org/java_websocket/extensions/CompressionExtensionTest.java b/src/test/java/org/java_websocket/extensions/CompressionExtensionTest.java index 946e28ce7..74b8e3fb1 100644 --- a/src/test/java/org/java_websocket/extensions/CompressionExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/CompressionExtensionTest.java @@ -1,10 +1,11 @@ package org.java_websocket.extensions; -import static org.junit.Assert.fail; import org.java_websocket.framing.PingFrame; import org.java_websocket.framing.TextFrame; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; public class CompressionExtensionTest { diff --git a/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java b/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java index 6d373f15f..e4b29907d 100644 --- a/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java @@ -25,129 +25,127 @@ package org.java_websocket.extensions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.nio.ByteBuffer; + import org.java_websocket.framing.BinaryFrame; import org.java_websocket.framing.TextFrame; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class DefaultExtensionTest { - @Test - public void testDecodeFrame() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - BinaryFrame binaryFrame = new BinaryFrame(); - binaryFrame.setPayload(ByteBuffer.wrap("test".getBytes())); - defaultExtension.decodeFrame(binaryFrame); - assertEquals(ByteBuffer.wrap("test".getBytes()), binaryFrame.getPayloadData()); - } - - @Test - public void testEncodeFrame() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - BinaryFrame binaryFrame = new BinaryFrame(); - binaryFrame.setPayload(ByteBuffer.wrap("test".getBytes())); - defaultExtension.encodeFrame(binaryFrame); - assertEquals(ByteBuffer.wrap("test".getBytes()), binaryFrame.getPayloadData()); - } - - @Test - public void testAcceptProvidedExtensionAsServer() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - assertTrue(defaultExtension.acceptProvidedExtensionAsServer("Test")); - assertTrue(defaultExtension.acceptProvidedExtensionAsServer("")); - assertTrue(defaultExtension.acceptProvidedExtensionAsServer("Test, ASDC, as, ad")); - assertTrue(defaultExtension.acceptProvidedExtensionAsServer("ASDC, as,ad")); - assertTrue(defaultExtension.acceptProvidedExtensionAsServer("permessage-deflate")); - } - - @Test - public void testAcceptProvidedExtensionAsClient() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - assertTrue(defaultExtension.acceptProvidedExtensionAsClient("Test")); - assertTrue(defaultExtension.acceptProvidedExtensionAsClient("")); - assertTrue(defaultExtension.acceptProvidedExtensionAsClient("Test, ASDC, as, ad")); - assertTrue(defaultExtension.acceptProvidedExtensionAsClient("ASDC, as,ad")); - assertTrue(defaultExtension.acceptProvidedExtensionAsClient("permessage-deflate")); - } - - @Test - public void testIsFrameValid() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - TextFrame textFrame = new TextFrame(); - try { - defaultExtension.isFrameValid(textFrame); - } catch (Exception e) { - fail("This frame is valid"); + @Test + public void testDecodeFrame() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + BinaryFrame binaryFrame = new BinaryFrame(); + binaryFrame.setPayload(ByteBuffer.wrap("test".getBytes())); + defaultExtension.decodeFrame(binaryFrame); + assertEquals(ByteBuffer.wrap("test".getBytes()), binaryFrame.getPayloadData()); + } + + @Test + public void testEncodeFrame() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + BinaryFrame binaryFrame = new BinaryFrame(); + binaryFrame.setPayload(ByteBuffer.wrap("test".getBytes())); + defaultExtension.encodeFrame(binaryFrame); + assertEquals(ByteBuffer.wrap("test".getBytes()), binaryFrame.getPayloadData()); + } + + @Test + public void testAcceptProvidedExtensionAsServer() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + assertTrue(defaultExtension.acceptProvidedExtensionAsServer("Test")); + assertTrue(defaultExtension.acceptProvidedExtensionAsServer("")); + assertTrue(defaultExtension.acceptProvidedExtensionAsServer("Test, ASDC, as, ad")); + assertTrue(defaultExtension.acceptProvidedExtensionAsServer("ASDC, as,ad")); + assertTrue(defaultExtension.acceptProvidedExtensionAsServer("permessage-deflate")); + } + + @Test + public void testAcceptProvidedExtensionAsClient() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + assertTrue(defaultExtension.acceptProvidedExtensionAsClient("Test")); + assertTrue(defaultExtension.acceptProvidedExtensionAsClient("")); + assertTrue(defaultExtension.acceptProvidedExtensionAsClient("Test, ASDC, as, ad")); + assertTrue(defaultExtension.acceptProvidedExtensionAsClient("ASDC, as,ad")); + assertTrue(defaultExtension.acceptProvidedExtensionAsClient("permessage-deflate")); + } + + @Test + public void testIsFrameValid() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + TextFrame textFrame = new TextFrame(); + try { + defaultExtension.isFrameValid(textFrame); + } catch (Exception e) { + fail("This frame is valid"); + } + textFrame.setRSV1(true); + try { + defaultExtension.isFrameValid(textFrame); + fail("This frame is not valid"); + } catch (Exception e) { + // + } + textFrame.setRSV1(false); + textFrame.setRSV2(true); + try { + defaultExtension.isFrameValid(textFrame); + fail("This frame is not valid"); + } catch (Exception e) { + // + } + textFrame.setRSV2(false); + textFrame.setRSV3(true); + try { + defaultExtension.isFrameValid(textFrame); + fail("This frame is not valid"); + } catch (Exception e) { + // + } + } + + @Test + public void testGetProvidedExtensionAsClient() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + assertEquals("", defaultExtension.getProvidedExtensionAsClient()); + } + + @Test + public void testGetProvidedExtensionAsServer() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + assertEquals("", defaultExtension.getProvidedExtensionAsServer()); } - textFrame.setRSV1(true); - try { - defaultExtension.isFrameValid(textFrame); - fail("This frame is not valid"); - } catch (Exception e) { - // + + @Test + public void testCopyInstance() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + IExtension extensionCopy = defaultExtension.copyInstance(); + assertEquals(defaultExtension, extensionCopy); } - textFrame.setRSV1(false); - textFrame.setRSV2(true); - try { - defaultExtension.isFrameValid(textFrame); - fail("This frame is not valid"); - } catch (Exception e) { - // + + @Test + public void testToString() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + assertEquals("DefaultExtension", defaultExtension.toString()); } - textFrame.setRSV2(false); - textFrame.setRSV3(true); - try { - defaultExtension.isFrameValid(textFrame); - fail("This frame is not valid"); - } catch (Exception e) { - // + + @Test + public void testHashCode() throws Exception { + DefaultExtension defaultExtension0 = new DefaultExtension(); + DefaultExtension defaultExtension1 = new DefaultExtension(); + assertEquals(defaultExtension0.hashCode(), defaultExtension1.hashCode()); + } + + @Test + public void testEquals() throws Exception { + DefaultExtension defaultExtension0 = new DefaultExtension(); + DefaultExtension defaultExtension1 = new DefaultExtension(); + assertEquals(defaultExtension0, defaultExtension1); + assertNotEquals(null, defaultExtension0); + assertNotEquals(defaultExtension0, new Object()); } - } - - @Test - public void testGetProvidedExtensionAsClient() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - assertEquals("", defaultExtension.getProvidedExtensionAsClient()); - } - - @Test - public void testGetProvidedExtensionAsServer() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - assertEquals("", defaultExtension.getProvidedExtensionAsServer()); - } - - @Test - public void testCopyInstance() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - IExtension extensionCopy = defaultExtension.copyInstance(); - assertEquals(defaultExtension, extensionCopy); - } - - @Test - public void testToString() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - assertEquals("DefaultExtension", defaultExtension.toString()); - } - - @Test - public void testHashCode() throws Exception { - DefaultExtension defaultExtension0 = new DefaultExtension(); - DefaultExtension defaultExtension1 = new DefaultExtension(); - assertEquals(defaultExtension0.hashCode(), defaultExtension1.hashCode()); - } - - @Test - public void testEquals() throws Exception { - DefaultExtension defaultExtension0 = new DefaultExtension(); - DefaultExtension defaultExtension1 = new DefaultExtension(); - assertEquals(defaultExtension0, defaultExtension1); - assertFalse(defaultExtension0.equals(null)); - assertFalse(defaultExtension0.equals(new Object())); - } } \ No newline at end of file diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index a4e2c3661..5a86648f3 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -1,11 +1,5 @@ package org.java_websocket.extensions; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.nio.ByteBuffer; import java.util.Arrays; import java.util.zip.Deflater; @@ -14,7 +8,9 @@ import org.java_websocket.extensions.permessage_deflate.PerMessageDeflateExtension; import org.java_websocket.framing.ContinuousFrame; import org.java_websocket.framing.TextFrame; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class PerMessageDeflateExtensionTest { diff --git a/src/test/java/org/java_websocket/framing/AllFramingTests.java b/src/test/java/org/java_websocket/framing/AllFramingTests.java deleted file mode 100644 index 24265d8eb..000000000 --- a/src/test/java/org/java_websocket/framing/AllFramingTests.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.framing; - - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.framing.BinaryFrameTest.class, - org.java_websocket.framing.PingFrameTest.class, - org.java_websocket.framing.PongFrameTest.class, - org.java_websocket.framing.CloseFrameTest.class, - org.java_websocket.framing.TextFrameTest.class, - org.java_websocket.framing.ContinuousFrameTest.class, - org.java_websocket.framing.FramedataImpl1Test.class -}) -/** - * Start all tests for frames - */ -public class AllFramingTests { - -} diff --git a/src/test/java/org/java_websocket/framing/BinaryFrameTest.java b/src/test/java/org/java_websocket/framing/BinaryFrameTest.java index a14e4ef25..92a839717 100644 --- a/src/test/java/org/java_websocket/framing/BinaryFrameTest.java +++ b/src/test/java/org/java_websocket/framing/BinaryFrameTest.java @@ -25,12 +25,12 @@ package org.java_websocket.framing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the BinaryFrame class @@ -40,13 +40,13 @@ public class BinaryFrameTest { @Test public void testConstructor() { BinaryFrame frame = new BinaryFrame(); - assertEquals("Opcode must be equal", Opcode.BINARY, frame.getOpcode()); - assertEquals("Fin must be set", true, frame.isFin()); - assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); - assertEquals("Payload must be empty", 0, frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false, frame.isRSV1()); - assertEquals("RSV2 must be false", false, frame.isRSV2()); - assertEquals("RSV3 must be false", false, frame.isRSV3()); + assertEquals(Opcode.BINARY, frame.getOpcode(), "Opcode must be equal"); + assertTrue(frame.isFin(), "Fin must be set"); + assertFalse(frame.getTransfereMasked(), "TransferedMask must not be set"); + assertEquals(0, frame.getPayloadData().capacity(), "Payload must be empty"); + assertFalse(frame.isRSV1(), "RSV1 must be false"); + assertFalse(frame.isRSV2(), "RSV2 must be false"); + assertFalse(frame.isRSV3(), "RSV3 must be false"); try { frame.isValid(); } catch (InvalidDataException e) { @@ -57,7 +57,7 @@ public void testConstructor() { @Test public void testExtends() { BinaryFrame frame = new BinaryFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof DataFrame); + assertInstanceOf(DataFrame.class, frame, "Frame must extend dataframe"); } @Test diff --git a/src/test/java/org/java_websocket/framing/CloseFrameTest.java b/src/test/java/org/java_websocket/framing/CloseFrameTest.java index 4000b2c9d..b20224634 100644 --- a/src/test/java/org/java_websocket/framing/CloseFrameTest.java +++ b/src/test/java/org/java_websocket/framing/CloseFrameTest.java @@ -25,223 +25,222 @@ package org.java_websocket.framing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the CloseFrame class */ public class CloseFrameTest { - @Test - public void testConstructor() { - CloseFrame frame = new CloseFrame(); - assertEquals("Opcode must be equal", Opcode.CLOSING, frame.getOpcode()); - assertEquals("Fin must be set", true, frame.isFin()); - assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); - assertEquals("Payload must be 2 (close code)", 2, frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false, frame.isRSV1()); - assertEquals("RSV2 must be false", false, frame.isRSV2()); - assertEquals("RSV3 must be false", false, frame.isRSV3()); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); + @Test + public void testConstructor() { + CloseFrame frame = new CloseFrame(); + assertEquals(Opcode.CLOSING, frame.getOpcode(), "Opcode must be equal"); + assertTrue(frame.isFin(), "Fin must be set"); + assertFalse(frame.getTransfereMasked(), "TransferedMask must not be set"); + assertEquals( 2, frame.getPayloadData().capacity(), "Payload must be 2 (close code)"); + assertFalse(frame.isRSV1(), "RSV1 must be false"); + assertFalse(frame.isRSV2(), "RSV2 must be false"); + assertFalse(frame.isRSV3(), "RSV3 must be false"); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } } - } - @Test - public void testExtends() { - CloseFrame frame = new CloseFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof ControlFrame); - } + @Test + public void testExtends() { + CloseFrame frame = new CloseFrame(); + assertInstanceOf(ControlFrame.class, frame, "Frame must extend dataframe"); + } - @Test - public void testToString() { - CloseFrame frame = new CloseFrame(); - String frameString = frame.toString(); - frameString = frameString.replaceAll("payload:(.*)}", "payload: *}"); - assertEquals("Frame toString must include a close code", - "Framedata{ opcode:CLOSING, fin:true, rsv1:false, rsv2:false, rsv3:false, payload length:[pos:0, len:2], payload: *}code: 1000", - frameString); - } + @Test + public void testToString() { + CloseFrame frame = new CloseFrame(); + String frameString = frame.toString(); + frameString = frameString.replaceAll("payload:(.*)}", "payload: *}"); + assertEquals( + "Framedata{ opcode:CLOSING, fin:true, rsv1:false, rsv2:false, rsv3:false, payload length:[pos:0, len:2], payload: *}code: 1000", + frameString, "Frame toString must include a close code"); + } - @Test - public void testIsValid() { - CloseFrame frame = new CloseFrame(); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setFin(false); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setFin(true); - frame.setRSV1(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV1(false); - frame.setRSV2(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV2(false); - frame.setRSV3(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV3(false); - frame.setCode(CloseFrame.NORMAL); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.GOING_AWAY); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.PROTOCOL_ERROR); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.REFUSE); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.NOCODE); - assertEquals(0, frame.getPayloadData().capacity()); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.ABNORMAL_CLOSE); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.POLICY_VALIDATION); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.TOOBIG); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.EXTENSION); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.UNEXPECTED_CONDITION); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.SERVICE_RESTART); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.TRY_AGAIN_LATER); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.BAD_GATEWAY); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.TLS_ERROR); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.NEVER_CONNECTED); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.BUGGYCLOSE); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.FLASHPOLICY); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.NOCODE); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.NO_UTF8); - frame.setReason(null); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.NOCODE); - frame.setReason("Close"); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine + @Test + public void testIsValid() { + CloseFrame frame = new CloseFrame(); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setFin(false); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setFin(true); + frame.setRSV1(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV1(false); + frame.setRSV2(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV2(false); + frame.setRSV3(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV3(false); + frame.setCode(CloseFrame.NORMAL); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.GOING_AWAY); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.PROTOCOL_ERROR); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.REFUSE); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.NOCODE); + assertEquals(0, frame.getPayloadData().capacity()); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.ABNORMAL_CLOSE); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.POLICY_VALIDATION); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.TOOBIG); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.EXTENSION); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.UNEXPECTED_CONDITION); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.SERVICE_RESTART); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.TRY_AGAIN_LATER); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.BAD_GATEWAY); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.TLS_ERROR); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.NEVER_CONNECTED); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.BUGGYCLOSE); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.FLASHPOLICY); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.NOCODE); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.NO_UTF8); + frame.setReason(null); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.NOCODE); + frame.setReason("Close"); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } } - } } diff --git a/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java b/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java index db0f6f4b9..98c1fa266 100644 --- a/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java +++ b/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java @@ -25,12 +25,13 @@ package org.java_websocket.framing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + /** * JUnit Test for the ContinuousFrame class @@ -40,13 +41,13 @@ public class ContinuousFrameTest { @Test public void testConstructor() { ContinuousFrame frame = new ContinuousFrame(); - assertEquals("Opcode must be equal", Opcode.CONTINUOUS, frame.getOpcode()); - assertEquals("Fin must be set", true, frame.isFin()); - assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); - assertEquals("Payload must be empty", 0, frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false, frame.isRSV1()); - assertEquals("RSV2 must be false", false, frame.isRSV2()); - assertEquals("RSV3 must be false", false, frame.isRSV3()); + assertEquals(Opcode.CONTINUOUS, frame.getOpcode(), "Opcode must be equal"); + assertTrue(frame.isFin(), "Fin must be set"); + assertFalse(frame.getTransfereMasked(), "TransferedMask must not be set"); + assertEquals( 0, frame.getPayloadData().capacity(), "Payload must be empty"); + assertFalse(frame.isRSV1(), "RSV1 must be false"); + assertFalse(frame.isRSV2(), "RSV2 must be false"); + assertFalse(frame.isRSV3(), "RSV3 must be false"); try { frame.isValid(); } catch (InvalidDataException e) { @@ -57,7 +58,7 @@ public void testConstructor() { @Test public void testExtends() { ContinuousFrame frame = new ContinuousFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof DataFrame); + assertInstanceOf(DataFrame.class, frame, "Frame must extend dataframe"); } @Test diff --git a/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java b/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java index 9e7db85a3..b952091be 100644 --- a/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java +++ b/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java @@ -25,13 +25,12 @@ package org.java_websocket.framing; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import java.nio.ByteBuffer; import org.java_websocket.enums.Opcode; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the FramedataImpl1 class @@ -41,29 +40,29 @@ public class FramedataImpl1Test { @Test public void testDefaultValues() { FramedataImpl1 binary = FramedataImpl1.get(Opcode.BINARY); - assertEquals("Opcode must be equal", Opcode.BINARY, binary.getOpcode()); - assertEquals("Fin must be set", true, binary.isFin()); - assertEquals("TransferedMask must not be set", false, binary.getTransfereMasked()); - assertEquals("Payload must be empty", 0, binary.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false, binary.isRSV1()); - assertEquals("RSV2 must be false", false, binary.isRSV2()); - assertEquals("RSV3 must be false", false, binary.isRSV3()); + assertEquals(Opcode.BINARY, binary.getOpcode(), "Opcode must be equal"); + assertTrue(binary.isFin(), "Fin must be set"); + assertFalse(binary.getTransfereMasked(), "TransferedMask must not be set"); + assertEquals( 0, binary.getPayloadData().capacity(), "Payload must be empty"); + assertFalse(binary.isRSV1(), "RSV1 must be false"); + assertFalse(binary.isRSV2(), "RSV2 must be false"); + assertFalse(binary.isRSV3(), "RSV3 must be false"); } @Test public void testGet() { FramedataImpl1 binary = FramedataImpl1.get(Opcode.BINARY); - assertEquals("Frame must be binary", true, binary instanceof BinaryFrame); + assertInstanceOf(BinaryFrame.class, binary, "Frame must be binary"); FramedataImpl1 text = FramedataImpl1.get(Opcode.TEXT); - assertEquals("Frame must be text", true, text instanceof TextFrame); + assertInstanceOf(TextFrame.class, text, "Frame must be text"); FramedataImpl1 closing = FramedataImpl1.get(Opcode.CLOSING); - assertEquals("Frame must be closing", true, closing instanceof CloseFrame); + assertInstanceOf(CloseFrame.class, closing, "Frame must be closing"); FramedataImpl1 continuous = FramedataImpl1.get(Opcode.CONTINUOUS); - assertEquals("Frame must be continuous", true, continuous instanceof ContinuousFrame); + assertInstanceOf(ContinuousFrame.class, continuous, "Frame must be continuous"); FramedataImpl1 ping = FramedataImpl1.get(Opcode.PING); - assertEquals("Frame must be ping", true, ping instanceof PingFrame); + assertInstanceOf(PingFrame.class, ping, "Frame must be ping"); FramedataImpl1 pong = FramedataImpl1.get(Opcode.PONG); - assertEquals("Frame must be pong", true, pong instanceof PongFrame); + assertInstanceOf(PongFrame.class, pong, "Frame must be pong"); try { FramedataImpl1.get(null); fail("IllegalArgumentException should be thrown"); @@ -76,18 +75,18 @@ public void testGet() { public void testSetters() { FramedataImpl1 frame = FramedataImpl1.get(Opcode.BINARY); frame.setFin(false); - assertEquals("Fin must not be set", false, frame.isFin()); + assertFalse(frame.isFin(), "Fin must not be set"); frame.setTransferemasked(true); - assertEquals("TransferedMask must be set", true, frame.getTransfereMasked()); + assertTrue(frame.getTransfereMasked(), "TransferedMask must be set"); ByteBuffer buffer = ByteBuffer.allocate(100); frame.setPayload(buffer); - assertEquals("Payload must be of size 100", 100, frame.getPayloadData().capacity()); + assertEquals( 100, frame.getPayloadData().capacity(), "Payload must be of size 100"); frame.setRSV1(true); - assertEquals("RSV1 must be true", true, frame.isRSV1()); + assertTrue(frame.isRSV1(), "RSV1 must be true"); frame.setRSV2(true); - assertEquals("RSV2 must be true", true, frame.isRSV2()); + assertTrue(frame.isRSV2(), "RSV2 must be true"); frame.setRSV3(true); - assertEquals("RSV3 must be true", true, frame.isRSV3()); + assertTrue(frame.isRSV3(), "RSV3 must be true"); } @Test @@ -98,8 +97,8 @@ public void testAppend() { FramedataImpl1 frame1 = FramedataImpl1.get(Opcode.BINARY); frame1.setPayload(ByteBuffer.wrap("second".getBytes())); frame0.append(frame1); - assertEquals("Fin must be set", true, frame0.isFin()); - assertArrayEquals("Payload must be equal", "firstsecond".getBytes(), - frame0.getPayloadData().array()); + assertTrue(frame0.isFin(), "Fin must be set"); + assertArrayEquals( "firstsecond".getBytes(), + frame0.getPayloadData().array(), "Payload must be equal"); } } diff --git a/src/test/java/org/java_websocket/framing/PingFrameTest.java b/src/test/java/org/java_websocket/framing/PingFrameTest.java index e5c90d4dd..9ccdc7580 100644 --- a/src/test/java/org/java_websocket/framing/PingFrameTest.java +++ b/src/test/java/org/java_websocket/framing/PingFrameTest.java @@ -25,79 +25,78 @@ package org.java_websocket.framing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the PingFrame class */ public class PingFrameTest { - @Test - public void testConstructor() { - PingFrame frame = new PingFrame(); - assertEquals("Opcode must be equal", Opcode.PING, frame.getOpcode()); - assertEquals("Fin must be set", true, frame.isFin()); - assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); - assertEquals("Payload must be empty", 0, frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false, frame.isRSV1()); - assertEquals("RSV2 must be false", false, frame.isRSV2()); - assertEquals("RSV3 must be false", false, frame.isRSV3()); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); + @Test + public void testConstructor() { + PingFrame frame = new PingFrame(); + assertEquals(Opcode.PING, frame.getOpcode(), "Opcode must be equal"); + assertTrue(frame.isFin(), "Fin must be set"); + assertFalse(frame.getTransfereMasked(), "TransferedMask must not be set"); + assertEquals(0, frame.getPayloadData().capacity(), "Payload must be empty"); + assertFalse(frame.isRSV1(), "RSV1 must be false"); + assertFalse(frame.isRSV2(), "RSV2 must be false"); + assertFalse(frame.isRSV3(), "RSV3 must be false"); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } } - } - @Test - public void testExtends() { - PingFrame frame = new PingFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof ControlFrame); - } - - @Test - public void testIsValid() { - PingFrame frame = new PingFrame(); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setFin(false); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine + @Test + public void testExtends() { + PingFrame frame = new PingFrame(); + assertInstanceOf(ControlFrame.class, frame, "Frame must extend dataframe"); } - frame.setFin(true); - frame.setRSV1(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV1(false); - frame.setRSV2(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV2(false); - frame.setRSV3(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine + + @Test + public void testIsValid() { + PingFrame frame = new PingFrame(); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setFin(false); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setFin(true); + frame.setRSV1(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV1(false); + frame.setRSV2(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV2(false); + frame.setRSV3(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } } - } } diff --git a/src/test/java/org/java_websocket/framing/PongFrameTest.java b/src/test/java/org/java_websocket/framing/PongFrameTest.java index c98c09ccc..d2985b7a9 100644 --- a/src/test/java/org/java_websocket/framing/PongFrameTest.java +++ b/src/test/java/org/java_websocket/framing/PongFrameTest.java @@ -25,13 +25,13 @@ package org.java_websocket.framing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import java.nio.ByteBuffer; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the PongFrame class @@ -41,13 +41,13 @@ public class PongFrameTest { @Test public void testConstructor() { PongFrame frame = new PongFrame(); - assertEquals("Opcode must be equal", Opcode.PONG, frame.getOpcode()); - assertEquals("Fin must be set", true, frame.isFin()); - assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); - assertEquals("Payload must be empty", 0, frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false, frame.isRSV1()); - assertEquals("RSV2 must be false", false, frame.isRSV2()); - assertEquals("RSV3 must be false", false, frame.isRSV3()); + assertEquals(Opcode.PONG, frame.getOpcode(), "Opcode must be equal"); + assertTrue(frame.isFin(), "Fin must be set"); + assertFalse(frame.getTransfereMasked(), "TransferedMask must not be set"); + assertEquals( 0, frame.getPayloadData().capacity(),"Payload must be empty"); + assertFalse(frame.isRSV1(), "RSV1 must be false"); + assertFalse(frame.isRSV2(), "RSV2 must be false"); + assertFalse(frame.isRSV3(), "RSV3 must be false"); try { frame.isValid(); } catch (InvalidDataException e) { @@ -60,13 +60,13 @@ public void testCopyConstructor() { PingFrame pingFrame = new PingFrame(); pingFrame.setPayload(ByteBuffer.allocate(100)); PongFrame pongFrame = new PongFrame(pingFrame); - assertEquals("Payload must be equal", pingFrame.getPayloadData(), pongFrame.getPayloadData()); + assertEquals( pingFrame.getPayloadData(), pongFrame.getPayloadData(), "Payload must be equal"); } @Test public void testExtends() { PongFrame frame = new PongFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof ControlFrame); + assertInstanceOf(ControlFrame.class, frame, "Frame must extend dataframe"); } @Test diff --git a/src/test/java/org/java_websocket/framing/TextFrameTest.java b/src/test/java/org/java_websocket/framing/TextFrameTest.java index d4e0dabc6..21f83f1c9 100644 --- a/src/test/java/org/java_websocket/framing/TextFrameTest.java +++ b/src/test/java/org/java_websocket/framing/TextFrameTest.java @@ -25,13 +25,13 @@ package org.java_websocket.framing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import java.nio.ByteBuffer; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the TextFrame class @@ -41,13 +41,13 @@ public class TextFrameTest { @Test public void testConstructor() { TextFrame frame = new TextFrame(); - assertEquals("Opcode must be equal", Opcode.TEXT, frame.getOpcode()); - assertEquals("Fin must be set", true, frame.isFin()); - assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); - assertEquals("Payload must be empty", 0, frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false, frame.isRSV1()); - assertEquals("RSV2 must be false", false, frame.isRSV2()); - assertEquals("RSV3 must be false", false, frame.isRSV3()); + assertEquals(Opcode.TEXT, frame.getOpcode(), "Opcode must be equal"); + assertTrue(frame.isFin(), "Fin must be set"); + assertFalse(frame.getTransfereMasked(), "TransferedMask must not be set"); + assertEquals( 0, frame.getPayloadData().capacity(), "Payload must be empty"); + assertFalse(frame.isRSV1(), "RSV1 must be false"); + assertFalse(frame.isRSV2(), "RSV2 must be false"); + assertFalse(frame.isRSV3(), "RSV3 must be false"); try { frame.isValid(); } catch (InvalidDataException e) { @@ -58,7 +58,7 @@ public void testConstructor() { @Test public void testExtends() { TextFrame frame = new TextFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof DataFrame); + assertInstanceOf(DataFrame.class, frame, "Frame must extend dataframe"); } @Test diff --git a/src/test/java/org/java_websocket/issues/AllIssueTests.java b/src/test/java/org/java_websocket/issues/AllIssueTests.java deleted file mode 100644 index 3668bcb89..000000000 --- a/src/test/java/org/java_websocket/issues/AllIssueTests.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.issues; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.issues.Issue609Test.class, - org.java_websocket.issues.Issue621Test.class, - org.java_websocket.issues.Issue580Test.class, - org.java_websocket.issues.Issue598Test.class, - org.java_websocket.issues.Issue256Test.class, - org.java_websocket.issues.Issue661Test.class, - org.java_websocket.issues.Issue666Test.class, - org.java_websocket.issues.Issue677Test.class, - org.java_websocket.issues.Issue732Test.class, - org.java_websocket.issues.Issue764Test.class, - org.java_websocket.issues.Issue765Test.class, - org.java_websocket.issues.Issue825Test.class, - org.java_websocket.issues.Issue834Test.class, - org.java_websocket.issues.Issue962Test.class -}) -/** - * Start all tests for issues - */ -public class AllIssueTests { - -} diff --git a/src/test/java/org/java_websocket/issues/Issue1142Test.java b/src/test/java/org/java_websocket/issues/Issue1142Test.java index 21de76bb6..38ff93e4d 100644 --- a/src/test/java/org/java_websocket/issues/Issue1142Test.java +++ b/src/test/java/org/java_websocket/issues/Issue1142Test.java @@ -1,9 +1,5 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; @@ -23,13 +19,17 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SSLContextUtil; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.*; public class Issue1142Test { - @Test(timeout = 4000) + @Test + @Timeout(4000) public void testWithoutSSLSession() throws IOException, URISyntaxException, InterruptedException { int port = SocketUtil.getAvailablePort(); @@ -66,7 +66,8 @@ public void onError(Exception ex) { server.stop(); } - @Test(timeout = 4000) + @Test + @Timeout(4000) public void testWithSSLSession() throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { int port = SocketUtil.getAvailablePort(); diff --git a/src/test/java/org/java_websocket/issues/Issue1160Test.java b/src/test/java/org/java_websocket/issues/Issue1160Test.java index e456132cc..57983cdea 100644 --- a/src/test/java/org/java_websocket/issues/Issue1160Test.java +++ b/src/test/java/org/java_websocket/issues/Issue1160Test.java @@ -6,8 +6,8 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import java.net.InetSocketAddress; import java.net.URI; @@ -15,6 +15,9 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class Issue1160Test { private final CountDownLatch countServerStart = new CountDownLatch(1); @@ -45,7 +48,8 @@ public void onError(Exception ex) { } - @Test(timeout = 5000) + @Test + @Timeout(5000) public void nonFatalErrorShallBeHandledByServer() throws Exception { final AtomicInteger isServerOnErrorCalledCounter = new AtomicInteger(0); @@ -99,12 +103,13 @@ public void onStart() { client.closeBlocking(); } - Assert.assertEquals(CONNECTION_COUNT, isServerOnErrorCalledCounter.get()); + assertEquals(CONNECTION_COUNT, isServerOnErrorCalledCounter.get()); server.stop(); } - @Test(timeout = 5000) + @Test + @Timeout(5000) public void fatalErrorShallNotBeHandledByServer() throws Exception { int port = SocketUtil.getAvailablePort(); @@ -121,7 +126,7 @@ public void onClose(WebSocket conn, int code, String reason, boolean remote) { @Override public void onMessage(WebSocket conn, ByteBuffer message) { - throw new OutOfMemoryError("Some error"); + throw new OutOfMemoryError("Some intentional error"); } @Override @@ -154,6 +159,7 @@ public void onStart() { client.send(new byte[100]); countClientDownLatch.await(); countServerDownLatch.await(); - Assert.assertTrue(countClientDownLatch.getCount() == 0 && countServerDownLatch.getCount() == 0); + assertEquals(0,countClientDownLatch.getCount()); + assertEquals(0, countServerDownLatch.getCount()); } } diff --git a/src/test/java/org/java_websocket/issues/Issue1203Test.java b/src/test/java/org/java_websocket/issues/Issue1203Test.java index 32ef85235..45c4cd593 100644 --- a/src/test/java/org/java_websocket/issues/Issue1203Test.java +++ b/src/test/java/org/java_websocket/issues/Issue1203Test.java @@ -1,8 +1,5 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.net.InetSocketAddress; import java.net.URI; @@ -15,14 +12,18 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.assertFalse; + public class Issue1203Test { private final CountDownLatch countServerDownLatch = new CountDownLatch(1); private final CountDownLatch countClientDownLatch = new CountDownLatch(1); boolean isClosedCalled = false; - @Test(timeout = 50000) + @Test + @Timeout(50000) public void testIssue() throws Exception { int port = SocketUtil.getAvailablePort(); WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { @@ -88,7 +89,7 @@ public void run() { timer.schedule(task, 15000); countClientDownLatch.await(); Thread.sleep(30000); - Assert.assertFalse(isClosedCalled); + assertFalse(isClosedCalled); client.closeBlocking(); server.stop(); } diff --git a/src/test/java/org/java_websocket/issues/Issue256Test.java b/src/test/java/org/java_websocket/issues/Issue256Test.java index 4faf1fa14..30d461459 100644 --- a/src/test/java/org/java_websocket/issues/Issue256Test.java +++ b/src/test/java/org/java_websocket/issues/Issue256Test.java @@ -25,9 +25,6 @@ package org.java_websocket.issues; -import static org.hamcrest.core.Is.is; -import static org.junit.Assume.assumeThat; - import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; @@ -42,14 +39,16 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; import org.java_websocket.util.ThreadCheck; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(Parameterized.class) +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.fail; + +@ExtendWith(ThreadCheck.class) public class Issue256Test { private static final int NUMBER_OF_TESTS = 10; @@ -57,13 +56,8 @@ public class Issue256Test { private static int port; static CountDownLatch countServerDownLatch = new CountDownLatch(1); - @Rule - public ThreadCheck zombies = new ThreadCheck(); - @Parameterized.Parameter - public int count; - - @BeforeClass + @BeforeAll public static void startServer() throws Exception { port = SocketUtil.getAvailablePort(); ws = new WebSocketServer(new InetSocketAddress(port), 16) { @@ -84,10 +78,7 @@ public void onMessage(WebSocket conn, String message) { @Override public void onError(WebSocket conn, Exception ex) { - - ex.printStackTrace(); - assumeThat(true, is(false)); - System.out.println("There should be no exception!"); + fail("There should be no exception!"); } @Override @@ -121,9 +112,7 @@ public void onClose(int code, String reason, boolean remote) { @Override public void onError(Exception ex) { - ex.printStackTrace(); - assumeThat(true, is(false)); - System.out.println("There should be no exception!"); + fail("There should be no exception!"); } }; clt.connectBlocking(); @@ -137,12 +126,11 @@ public void onError(Exception ex) { clt.closeBlocking(); } - @AfterClass + @AfterAll public static void successTests() throws InterruptedException, IOException { ws.stop(); } - @Parameterized.Parameters public static Collection data() { List ret = new ArrayList(NUMBER_OF_TESTS); for (int i = 0; i < NUMBER_OF_TESTS; i++) { @@ -151,12 +139,16 @@ public static Collection data() { return ret; } - @Test(timeout = 5000) + @ParameterizedTest + @Timeout(5000) + @MethodSource("data") public void runReconnectSocketClose() throws Exception { runTestScenarioReconnect(false); } - @Test(timeout = 5000) + @ParameterizedTest + @Timeout(5000) + @MethodSource("data") public void runReconnectCloseBlocking() throws Exception { runTestScenarioReconnect(true); } diff --git a/src/test/java/org/java_websocket/issues/Issue580Test.java b/src/test/java/org/java_websocket/issues/Issue580Test.java index 4a2e31848..e50e5f839 100644 --- a/src/test/java/org/java_websocket/issues/Issue580Test.java +++ b/src/test/java/org/java_websocket/issues/Issue580Test.java @@ -38,22 +38,15 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; import org.java_websocket.util.ThreadCheck; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) +@ExtendWith(ThreadCheck.class) public class Issue580Test { private static final int NUMBER_OF_TESTS = 10; - @Parameterized.Parameter - public int count; - - - @Rule - public ThreadCheck zombies = new ThreadCheck(); private void runTestScenario(boolean closeBlocking) throws Exception { final CountDownLatch countServerDownLatch = new CountDownLatch(1); @@ -116,7 +109,6 @@ public void onError(Exception ex) { Thread.sleep(100); } - @Parameterized.Parameters public static Collection data() { List ret = new ArrayList(NUMBER_OF_TESTS); for (int i = 0; i < NUMBER_OF_TESTS; i++) { @@ -125,12 +117,15 @@ public static Collection data() { return ret; } - @Test + + @ParameterizedTest + @MethodSource("data") public void runNoCloseBlockingTestScenario() throws Exception { runTestScenario(false); } - @Test + @ParameterizedTest + @MethodSource("data") public void runCloseBlockingTestScenario() throws Exception { runTestScenario(true); } diff --git a/src/test/java/org/java_websocket/issues/Issue598Test.java b/src/test/java/org/java_websocket/issues/Issue598Test.java index c45f228cb..26c12f56a 100644 --- a/src/test/java/org/java_websocket/issues/Issue598Test.java +++ b/src/test/java/org/java_websocket/issues/Issue598Test.java @@ -44,7 +44,8 @@ import org.java_websocket.protocols.Protocol; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public class Issue598Test { @@ -189,43 +190,50 @@ public void onStart() { server.stop(); } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void runBelowLimitBytebuffer() throws Exception { runTestScenario(0); } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void runBelowSplitLimitBytebuffer() throws Exception { runTestScenario(1); } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void runBelowLimitString() throws Exception { runTestScenario(2); } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void runBelowSplitLimitString() throws Exception { runTestScenario(3); } @Test - //(timeout = 2000) + @Timeout(2000) public void runAboveLimitBytebuffer() throws Exception { runTestScenario(4); } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void runAboveSplitLimitBytebuffer() throws Exception { runTestScenario(5); } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void runAboveLimitString() throws Exception { runTestScenario(6); } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void runAboveSplitLimitString() throws Exception { runTestScenario(7); } diff --git a/src/test/java/org/java_websocket/issues/Issue609Test.java b/src/test/java/org/java_websocket/issues/Issue609Test.java index b84e3cfd9..4c89b784a 100644 --- a/src/test/java/org/java_websocket/issues/Issue609Test.java +++ b/src/test/java/org/java_websocket/issues/Issue609Test.java @@ -25,8 +25,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertTrue; - import java.net.InetSocketAddress; import java.net.URI; import java.util.concurrent.CountDownLatch; @@ -36,7 +34,10 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class Issue609Test { @@ -99,12 +100,12 @@ public void onStart() { server.start(); countServerDownLatch.await(); webSocket.connectBlocking(); - assertTrue("webSocket.isOpen()", webSocket.isOpen()); + assertTrue(webSocket.isOpen(), "webSocket.isOpen()"); webSocket.getSocket().close(); countDownLatch.await(); - assertTrue("!webSocket.isOpen()", !webSocket.isOpen()); - assertTrue("!wasOpenClient", !wasOpenClient); - assertTrue("!wasOpenServer", !wasOpenServer); + assertFalse(webSocket.isOpen(), "!webSocket.isOpen()"); + assertFalse(wasOpenClient, "!wasOpenClient"); + assertFalse(wasOpenServer, "!wasOpenServer"); server.stop(); } } diff --git a/src/test/java/org/java_websocket/issues/Issue621Test.java b/src/test/java/org/java_websocket/issues/Issue621Test.java index 1a6a173ad..f21c40071 100644 --- a/src/test/java/org/java_websocket/issues/Issue621Test.java +++ b/src/test/java/org/java_websocket/issues/Issue621Test.java @@ -25,8 +25,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertTrue; - import java.io.OutputStream; import java.io.PrintStream; import java.net.InetSocketAddress; @@ -38,7 +36,9 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; public class Issue621Test { @@ -114,7 +114,7 @@ public void onStart() { countServerDownLatch.await(); webSocket.connectBlocking(); countDownLatch.await(); - assertTrue("There was an error using System.err", !wasError); + assertFalse(wasError, "There was an error using System.err"); server.stop(); } } diff --git a/src/test/java/org/java_websocket/issues/Issue661Test.java b/src/test/java/org/java_websocket/issues/Issue661Test.java index bda984431..31cded8fc 100644 --- a/src/test/java/org/java_websocket/issues/Issue661Test.java +++ b/src/test/java/org/java_websocket/issues/Issue661Test.java @@ -25,9 +25,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.net.BindException; import java.net.InetSocketAddress; @@ -37,20 +34,22 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; import org.java_websocket.util.ThreadCheck; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.ExtendWith; -public class Issue661Test { +import static org.junit.jupiter.api.Assertions.*; - @Rule - public ThreadCheck zombies = new ThreadCheck(); +@ExtendWith(ThreadCheck.class) +public class Issue661Test { private CountDownLatch countServerDownLatch = new CountDownLatch(1); private boolean wasError = false; private boolean wasBindException = false; - @Test(timeout = 2000) + @Test + @Timeout(2000) public void testIssue() throws Exception { int port = SocketUtil.getAvailablePort(); WebSocketServer server0 = new WebSocketServer(new InetSocketAddress(port)) { @@ -120,7 +119,7 @@ public void onStart() { server1.stop(); server0.stop(); Thread.sleep(100); - assertFalse("There was an unexpected exception!", wasError); - assertTrue("There was no bind exception!", wasBindException); + assertFalse(wasError, "There was an unexpected exception!"); + assertTrue(wasBindException, "There was no bind exception!"); } } diff --git a/src/test/java/org/java_websocket/issues/Issue666Test.java b/src/test/java/org/java_websocket/issues/Issue666Test.java index a4f2523b5..163dd2366 100644 --- a/src/test/java/org/java_websocket/issues/Issue666Test.java +++ b/src/test/java/org/java_websocket/issues/Issue666Test.java @@ -29,6 +29,7 @@ import java.net.URI; import java.util.Map; import java.util.concurrent.CountDownLatch; + import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ClientHandshake; @@ -36,122 +37,127 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; import org.java_websocket.util.ThreadCheck; -import org.junit.Assert; -import org.junit.Test; - -public class Issue666Test { - - private CountDownLatch countServerDownLatch = new CountDownLatch(1); - - @Test - public void testServer() throws Exception { - Map mapBefore = ThreadCheck.getThreadMap(); - int port = SocketUtil.getAvailablePort(); - WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - } - - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - - } +import org.junit.jupiter.api.Test; - @Override - public void onMessage(WebSocket conn, String message) { +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; - } - - @Override - public void onError(WebSocket conn, Exception ex) { - - } +public class Issue666Test { - @Override - public void onStart() { - countServerDownLatch.countDown(); - } - }; - server.start(); - countServerDownLatch.await(); - Map mapAfter = ThreadCheck.getThreadMap(); - for (long key : mapBefore.keySet()) { - mapAfter.remove(key); + private CountDownLatch countServerDownLatch = new CountDownLatch(1); + + @Test + public void testServer() throws Exception { + Map mapBefore = ThreadCheck.getThreadMap(); + int port = SocketUtil.getAvailablePort(); + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + }; + server.start(); + countServerDownLatch.await(); + Map mapAfter = ThreadCheck.getThreadMap(); + for (long key : mapBefore.keySet()) { + mapAfter.remove(key); + } + for (Thread thread : mapAfter.values()) { + String name = thread.getName(); + if (!name.startsWith("WebSocketSelector-") && !name.startsWith("WebSocketWorker-") && !name + .startsWith("WebSocketConnectionLostChecker-") + && !name.startsWith("WebSocketConnectReadThread-")) { + fail("Thread not correctly named! Is: " + name); + } + } + server.stop(); } - for (Thread thread : mapAfter.values()) { - String name = thread.getName(); - if (!name.startsWith("WebSocketSelector-") && !name.startsWith("WebSocketWorker-") && !name - .startsWith("connectionLostChecker-")) { - Assert.fail("Thread not correctly named! Is: " + name); - } - } - server.stop(); - } - - @Test - public void testClient() throws Exception { - int port = SocketUtil.getAvailablePort(); - WebSocketClient client = new WebSocketClient(new URI("ws://localhost:" + port)) { - @Override - public void onOpen(ServerHandshake handshakedata) { - - } - @Override - public void onMessage(String message) { - - } - - @Override - public void onClose(int code, String reason, boolean remote) { - } - - @Override - public void onError(Exception ex) { - - } - }; - WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - } - - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - - } - - @Override - public void onMessage(WebSocket conn, String message) { - - } - - @Override - public void onError(WebSocket conn, Exception ex) { - - } - - @Override - public void onStart() { - countServerDownLatch.countDown(); - } - }; - server.start(); - countServerDownLatch.await(); - Map mapBefore = ThreadCheck.getThreadMap(); - client.connectBlocking(); - Map mapAfter = ThreadCheck.getThreadMap(); - for (long key : mapBefore.keySet()) { - mapAfter.remove(key); - } - for (Thread thread : mapAfter.values()) { - String name = thread.getName(); - if (!name.startsWith("connectionLostChecker-") && !name.startsWith("WebSocketWriteThread-") - && !name.startsWith("WebSocketConnectReadThread-")) { - Assert.fail("Thread not correctly named! Is: " + name); - } + @Test + public void testClient() throws Exception { + int port = SocketUtil.getAvailablePort(); + WebSocketClient client = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + + } + + @Override + public void onMessage(String message) { + + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + + } + }; + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + }; + server.start(); + countServerDownLatch.await(); + assertTrue(SocketUtil.waitForServerToStart(port), "Server Start Status"); + Map mapBefore = ThreadCheck.getThreadMap(); + client.connectBlocking(); + Map mapAfter = ThreadCheck.getThreadMap(); + for (long key : mapBefore.keySet()) { + mapAfter.remove(key); + } + for (Thread thread : mapAfter.values()) { + String name = thread.getName(); + if (!name.startsWith("WebSocketConnectionLostChecker-") && !name.startsWith("WebSocketWriteThread-") + && !name.startsWith("WebSocketConnectReadThread-") + && !name.startsWith("WebSocketWorker-")) { + fail("Thread not correctly named! Is: " + name); + } + } + client.close(); + server.stop(); } - client.close(); - server.stop(); - } } diff --git a/src/test/java/org/java_websocket/issues/Issue677Test.java b/src/test/java/org/java_websocket/issues/Issue677Test.java index 52dfc94b7..bf660d789 100644 --- a/src/test/java/org/java_websocket/issues/Issue677Test.java +++ b/src/test/java/org/java_websocket/issues/Issue677Test.java @@ -25,7 +25,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertTrue; import java.net.InetSocketAddress; import java.net.URI; @@ -37,7 +36,9 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; public class Issue677Test { @@ -113,14 +114,21 @@ public void onStart() { server.start(); countServerDownLatch.await(); webSocket0.connectBlocking(); - assertTrue("webSocket.isOpen()", webSocket0.isOpen()); + assertTrue(webSocket0.isOpen(), "webSocket.isOpen()"); webSocket0.close(); countDownLatch0.await(); - assertTrue("webSocket.isClosed()", webSocket0.isClosed()); + // Add some delay is since the latch will be decreased in the onClose before the state is reset + for (int i = 0; i < 5; i++) { + if (webSocket0.isClosed()) { + break; + } + Thread.sleep(5); + } + assertTrue(webSocket0.isClosed(), "webSocket.isClosed()"); webSocket1.connectBlocking(); - assertTrue("webSocket.isOpen()", webSocket1.isOpen()); + assertTrue(webSocket1.isOpen(), "webSocket.isOpen()"); webSocket1.closeConnection(CloseFrame.ABNORMAL_CLOSE, "Abnormal close!"); - assertTrue("webSocket.isClosed()", webSocket1.isClosed()); + assertTrue(webSocket1.isClosed(), "webSocket.isClosed()"); server.stop(); } } diff --git a/src/test/java/org/java_websocket/issues/Issue713Test.java b/src/test/java/org/java_websocket/issues/Issue713Test.java index 1b752aaf8..769f08f94 100644 --- a/src/test/java/org/java_websocket/issues/Issue713Test.java +++ b/src/test/java/org/java_websocket/issues/Issue713Test.java @@ -25,8 +25,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.fail; - import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; @@ -40,7 +38,10 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.fail; public class Issue713Test { @@ -49,7 +50,7 @@ public class Issue713Test { CountDownLatch countDownLatchBytebuffer = new CountDownLatch(10); @Test - public void testIllegalArgument() throws IOException { + public void testIllegalArgument() throws InterruptedException { WebSocketServer server = new WebSocketServer( new InetSocketAddress(SocketUtil.getAvailablePort())) { @Override @@ -91,7 +92,8 @@ public void onStart() { } } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void testIssue() throws Exception { final int port = SocketUtil.getAvailablePort(); WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { diff --git a/src/test/java/org/java_websocket/issues/Issue732Test.java b/src/test/java/org/java_websocket/issues/Issue732Test.java index e811f8aa0..d9e734bbe 100644 --- a/src/test/java/org/java_websocket/issues/Issue732Test.java +++ b/src/test/java/org/java_websocket/issues/Issue732Test.java @@ -25,7 +25,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.fail; import java.net.InetSocketAddress; import java.net.URI; @@ -37,18 +36,20 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; import org.java_websocket.util.ThreadCheck; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.ExtendWith; +import static org.junit.jupiter.api.Assertions.fail; + +@ExtendWith(ThreadCheck.class) public class Issue732Test { - @Rule - public ThreadCheck zombies = new ThreadCheck(); private CountDownLatch countServerDownLatch = new CountDownLatch(1); - @Test(timeout = 2000) + @Test + @Timeout(2000) public void testIssue() throws Exception { int port = SocketUtil.getAvailablePort(); final WebSocketClient webSocket = new WebSocketClient(new URI("ws://localhost:" + port)) { @@ -56,7 +57,7 @@ public void testIssue() throws Exception { public void onOpen(ServerHandshake handshakedata) { try { this.reconnect(); - Assert.fail("Exception should be thrown"); + fail("Exception should be thrown"); } catch (IllegalStateException e) { // } @@ -66,7 +67,7 @@ public void onOpen(ServerHandshake handshakedata) { public void onMessage(String message) { try { this.reconnect(); - Assert.fail("Exception should be thrown"); + fail("Exception should be thrown"); } catch (IllegalStateException e) { send("hi"); } @@ -76,7 +77,7 @@ public void onMessage(String message) { public void onClose(int code, String reason, boolean remote) { try { this.reconnect(); - Assert.fail("Exception should be thrown"); + fail("Exception should be thrown"); } catch (IllegalStateException e) { // } @@ -86,7 +87,7 @@ public void onClose(int code, String reason, boolean remote) { public void onError(Exception ex) { try { this.reconnect(); - Assert.fail("Exception should be thrown"); + fail("Exception should be thrown"); } catch (IllegalStateException e) { // } diff --git a/src/test/java/org/java_websocket/issues/Issue764Test.java b/src/test/java/org/java_websocket/issues/Issue764Test.java index 40be7ef6c..870f79ad9 100644 --- a/src/test/java/org/java_websocket/issues/Issue764Test.java +++ b/src/test/java/org/java_websocket/issues/Issue764Test.java @@ -45,14 +45,16 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SSLContextUtil; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public class Issue764Test { private CountDownLatch countClientDownLatch = new CountDownLatch(2); private CountDownLatch countServerDownLatch = new CountDownLatch(1); - @Test(timeout = 2000) + @Test + @Timeout(2000) public void testIssue() throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { int port = SocketUtil.getAvailablePort(); diff --git a/src/test/java/org/java_websocket/issues/Issue765Test.java b/src/test/java/org/java_websocket/issues/Issue765Test.java index a7a6188cd..5eff49468 100644 --- a/src/test/java/org/java_websocket/issues/Issue765Test.java +++ b/src/test/java/org/java_websocket/issues/Issue765Test.java @@ -38,8 +38,10 @@ import org.java_websocket.drafts.Draft; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class Issue765Test { @@ -49,9 +51,9 @@ public class Issue765Test { public void testIssue() { WebSocketServer webSocketServer = new MyWebSocketServer(); webSocketServer.setWebSocketFactory(new LocalWebSocketFactory()); - Assert.assertFalse("Close should not have been called yet", isClosedCalled); + assertFalse(isClosedCalled, "Close should not have been called yet"); webSocketServer.setWebSocketFactory(new LocalWebSocketFactory()); - Assert.assertTrue("Close has been called", isClosedCalled); + assertTrue(isClosedCalled, "Close has been called"); } private static class MyWebSocketServer extends WebSocketServer { diff --git a/src/test/java/org/java_websocket/issues/Issue811Test.java b/src/test/java/org/java_websocket/issues/Issue811Test.java index d438aa685..e2faf7ed2 100644 --- a/src/test/java/org/java_websocket/issues/Issue811Test.java +++ b/src/test/java/org/java_websocket/issues/Issue811Test.java @@ -33,13 +33,15 @@ import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public class Issue811Test { private CountDownLatch countServerDownLatch = new CountDownLatch(1); - @Test(timeout = 2000) + @Test + @Timeout(2000) public void testSetConnectionLostTimeout() throws IOException, InterruptedException { final MyWebSocketServer server = new MyWebSocketServer( new InetSocketAddress(SocketUtil.getAvailablePort())); diff --git a/src/test/java/org/java_websocket/issues/Issue825Test.java b/src/test/java/org/java_websocket/issues/Issue825Test.java index d878dddde..f846f9571 100644 --- a/src/test/java/org/java_websocket/issues/Issue825Test.java +++ b/src/test/java/org/java_websocket/issues/Issue825Test.java @@ -45,12 +45,14 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SSLContextUtil; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public class Issue825Test { - @Test(timeout = 15000) + @Test + @Timeout(15000) public void testIssue() throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { final CountDownLatch countClientOpenLatch = new CountDownLatch(3); diff --git a/src/test/java/org/java_websocket/issues/Issue834Test.java b/src/test/java/org/java_websocket/issues/Issue834Test.java index 350acf456..abd121179 100644 --- a/src/test/java/org/java_websocket/issues/Issue834Test.java +++ b/src/test/java/org/java_websocket/issues/Issue834Test.java @@ -7,13 +7,17 @@ import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.assertEquals; + public class Issue834Test { - @Test(timeout = 1000) - public void testNoNewThreads() throws IOException { + @Test + @Timeout(1000) + public void testNoNewThreads() throws InterruptedException { Set threadSet1 = Thread.getAllStackTraces().keySet(); @@ -42,7 +46,7 @@ public void onStart() { Set threadSet2 = Thread.getAllStackTraces().keySet(); //checks that no threads are started in the constructor - Assert.assertEquals(threadSet1, threadSet2); + assertEquals(threadSet1, threadSet2); } diff --git a/src/test/java/org/java_websocket/issues/Issue847Test.java b/src/test/java/org/java_websocket/issues/Issue847Test.java index f47e4fec5..870e18b07 100644 --- a/src/test/java/org/java_websocket/issues/Issue847Test.java +++ b/src/test/java/org/java_websocket/issues/Issue847Test.java @@ -26,8 +26,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.fail; - import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; @@ -45,13 +43,14 @@ import org.java_websocket.util.Charsetfunctions; import org.java_websocket.util.KeyUtils; import org.java_websocket.util.SocketUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.fail; -@RunWith(Parameterized.class) public class Issue847Test { private static Thread thread; @@ -60,10 +59,6 @@ public class Issue847Test { private static int port; private static final int NUMBER_OF_TESTS = 20; - @Parameterized.Parameter - public int size; - - @Parameterized.Parameters public static Collection data() { List ret = new ArrayList(NUMBER_OF_TESTS); for (int i = 1; i <= NUMBER_OF_TESTS + 1; i++) { @@ -72,7 +67,7 @@ public static Collection data() { return ret; } - @BeforeClass + @BeforeAll public static void startServer() throws Exception { port = SocketUtil.getAvailablePort(); thread = new Thread( @@ -138,19 +133,23 @@ public void run() { thread.start(); } - @AfterClass + @AfterAll public static void successTests() throws IOException { serverSocket.close(); thread.interrupt(); } - @Test(timeout = 5000) - public void testIncrementalFrameUnmasked() throws Exception { + @ParameterizedTest() + @Timeout(5000) + @MethodSource("data") + public void testIncrementalFrameUnmasked(int size) throws Exception { testIncrementalFrame(false, size); } - @Test(timeout = 5000) - public void testIncrementalFrameMsked() throws Exception { + @ParameterizedTest() + @Timeout(5000) + @MethodSource("data") + public void testIncrementalFrameMsked(int size) throws Exception { testIncrementalFrame(true, size); } diff --git a/src/test/java/org/java_websocket/issues/Issue855Test.java b/src/test/java/org/java_websocket/issues/Issue855Test.java index 9f919b87e..f094f067e 100644 --- a/src/test/java/org/java_websocket/issues/Issue855Test.java +++ b/src/test/java/org/java_websocket/issues/Issue855Test.java @@ -35,14 +35,16 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public class Issue855Test { CountDownLatch countServerDownLatch = new CountDownLatch(1); CountDownLatch countDownLatch = new CountDownLatch(1); - @Test(timeout = 2000) + @Test + @Timeout(2000) public void testIssue() throws Exception { int port = SocketUtil.getAvailablePort(); WebSocketClient webSocket = new WebSocketClient(new URI("ws://localhost:" + port)) { diff --git a/src/test/java/org/java_websocket/issues/Issue879Test.java b/src/test/java/org/java_websocket/issues/Issue879Test.java index bdd6fa1c0..504bec922 100644 --- a/src/test/java/org/java_websocket/issues/Issue879Test.java +++ b/src/test/java/org/java_websocket/issues/Issue879Test.java @@ -26,8 +26,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertFalse; - import java.io.IOException; import java.net.BindException; import java.net.InetSocketAddress; @@ -45,21 +43,21 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertFalse; -@RunWith(Parameterized.class) public class Issue879Test { private static final int NUMBER_OF_TESTS = 20; - @Parameterized.Parameter - public int numberOfConnections; - - - @Test(timeout = 10000) - public void QuickStopTest() throws IOException, InterruptedException, URISyntaxException { + @Timeout(10000) + @ParameterizedTest() + @MethodSource("data") + public void QuickStopTest(int numberOfConnections) throws InterruptedException, URISyntaxException { final boolean[] wasBindException = {false}; final boolean[] wasConcurrentException = new boolean[1]; final CountDownLatch countDownLatch = new CountDownLatch(1); @@ -122,11 +120,10 @@ public void onStart() { serverA.stop(); serverB.start(); clients.clear(); - assertFalse("There was a BindException", wasBindException[0]); - assertFalse("There was a ConcurrentModificationException", wasConcurrentException[0]); + assertFalse(wasBindException[0], "There was a BindException"); + assertFalse(wasConcurrentException[0], "There was a ConcurrentModificationException"); } - @Parameterized.Parameters public static Collection data() { List ret = new ArrayList(NUMBER_OF_TESTS); for (int i = 0; i < NUMBER_OF_TESTS; i++) { diff --git a/src/test/java/org/java_websocket/issues/Issue890Test.java b/src/test/java/org/java_websocket/issues/Issue890Test.java index 7f05a23a4..82c991bab 100644 --- a/src/test/java/org/java_websocket/issues/Issue890Test.java +++ b/src/test/java/org/java_websocket/issues/Issue890Test.java @@ -26,10 +26,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.InetSocketAddress; @@ -51,12 +47,16 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SSLContextUtil; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.*; public class Issue890Test { - @Test(timeout = 4000) + @Test + @Timeout(4000) public void testWithSSLSession() throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { int port = SocketUtil.getAvailablePort(); @@ -92,7 +92,8 @@ public void onError(Exception ex) { assertNotNull(testResult.sslSession); } - @Test(timeout = 4000) + @Test + @Timeout(4000) public void testWithOutSSLSession() throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { int port = SocketUtil.getAvailablePort(); diff --git a/src/test/java/org/java_websocket/issues/Issue900Test.java b/src/test/java/org/java_websocket/issues/Issue900Test.java index 952dca8ee..edc966e9f 100644 --- a/src/test/java/org/java_websocket/issues/Issue900Test.java +++ b/src/test/java/org/java_websocket/issues/Issue900Test.java @@ -40,14 +40,16 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public class Issue900Test { CountDownLatch serverStartLatch = new CountDownLatch(1); CountDownLatch closeCalledLatch = new CountDownLatch(1); - @Test(timeout = 2000) + @Test + @Timeout(2000) public void testIssue() throws Exception { int port = SocketUtil.getAvailablePort(); final WebSocketClient client = new WebSocketClient(new URI("ws://localhost:" + port)) { diff --git a/src/test/java/org/java_websocket/issues/Issue941Test.java b/src/test/java/org/java_websocket/issues/Issue941Test.java index a9aedbaef..eaf50fab3 100644 --- a/src/test/java/org/java_websocket/issues/Issue941Test.java +++ b/src/test/java/org/java_websocket/issues/Issue941Test.java @@ -25,7 +25,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertArrayEquals; import java.net.InetSocketAddress; import java.net.URI; @@ -39,7 +38,9 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; public class Issue941Test { diff --git a/src/test/java/org/java_websocket/issues/Issue962Test.java b/src/test/java/org/java_websocket/issues/Issue962Test.java index b7d107171..56baa6d34 100644 --- a/src/test/java/org/java_websocket/issues/Issue962Test.java +++ b/src/test/java/org/java_websocket/issues/Issue962Test.java @@ -31,6 +31,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; +import java.util.concurrent.CountDownLatch; import javax.net.SocketFactory; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; @@ -38,8 +39,10 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.*; public class Issue962Test { @@ -86,7 +89,8 @@ public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throw } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void testIssue() throws IOException, URISyntaxException, InterruptedException { int port = SocketUtil.getAvailablePort(); WebSocketClient client = new WebSocketClient(new URI("ws://127.0.0.1:" + port)) { @@ -104,11 +108,12 @@ public void onClose(int code, String reason, boolean remote) { @Override public void onError(Exception ex) { - Assert.fail(ex.toString() + " should not occur"); + fail(ex.toString() + " should not occur"); } }; String bindingAddress = "127.0.0.1"; + CountDownLatch serverStartedLatch = new CountDownLatch(1); client.setSocketFactory(new TestSocketFactory(bindingAddress)); @@ -131,14 +136,16 @@ public void onError(WebSocket conn, Exception ex) { @Override public void onStart() { + serverStartedLatch.countDown(); } }; server.start(); + serverStartedLatch.await(); client.connectBlocking(); - Assert.assertEquals(bindingAddress, client.getSocket().getLocalAddress().getHostAddress()); - Assert.assertNotEquals(0, client.getSocket().getLocalPort()); - Assert.assertTrue(client.getSocket().isConnected()); + assertEquals(bindingAddress, client.getSocket().getLocalAddress().getHostAddress()); + assertNotEquals(0, client.getSocket().getLocalPort()); + assertTrue(client.getSocket().isConnected()); } } diff --git a/src/test/java/org/java_websocket/issues/Issue997Test.java b/src/test/java/org/java_websocket/issues/Issue997Test.java index be227cef7..e72a338c2 100644 --- a/src/test/java/org/java_websocket/issues/Issue997Test.java +++ b/src/test/java/org/java_websocket/issues/Issue997Test.java @@ -27,9 +27,6 @@ */ -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; @@ -44,6 +41,7 @@ import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLParameters; + import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ClientHandshake; @@ -52,161 +50,171 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SSLContextUtil; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class Issue997Test { - @Test(timeout = 2000) - public void test_localServer_ServerLocalhost_Client127_CheckActive() - throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), - SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), - "HTTPS"); - assertFalse(client.onOpen); - assertTrue(client.onSSLError); - } - - @Test(timeout = 2000) - public void test_localServer_ServerLocalhost_Client127_CheckInactive() - throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), - SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), ""); - assertTrue(client.onOpen); - assertFalse(client.onSSLError); - } - - @Test(timeout = 2000) - public void test_localServer_ServerLocalhost_Client127_CheckDefault() - throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), - SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), null); - assertFalse(client.onOpen); - assertTrue(client.onSSLError); - } - - @Test(timeout = 2000) - public void test_localServer_ServerLocalhost_ClientLocalhost_CheckActive() - throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), - SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), - "HTTPS"); - assertTrue(client.onOpen); - assertFalse(client.onSSLError); - } - - @Test(timeout = 2000) - public void test_localServer_ServerLocalhost_ClientLocalhost_CheckInactive() - throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), - SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), ""); - assertTrue(client.onOpen); - assertFalse(client.onSSLError); - } - - @Test(timeout = 2000) - public void test_localServer_ServerLocalhost_ClientLocalhost_CheckDefault() - throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), - SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), null); - assertTrue(client.onOpen); - assertFalse(client.onSSLError); - } - - - public SSLWebSocketClient testIssueWithLocalServer(String address, int port, - SSLContext serverContext, SSLContext clientContext, String endpointIdentificationAlgorithm) - throws IOException, URISyntaxException, InterruptedException { - CountDownLatch countServerDownLatch = new CountDownLatch(1); - SSLWebSocketClient client = new SSLWebSocketClient(address, port, - endpointIdentificationAlgorithm); - WebSocketServer server = new SSLWebSocketServer(port, countServerDownLatch); - - server.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(serverContext)); - if (clientContext != null) { - client.setSocketFactory(clientContext.getSocketFactory()); + @Test + @Timeout(2000) + public void test_localServer_ServerLocalhost_Client127_CheckActive() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), + "HTTPS"); + assertFalse(client.onOpen, "client is not open"); + assertTrue(client.onSSLError, "client has caught a SSLHandshakeException"); } - server.start(); - countServerDownLatch.await(); - client.connectBlocking(1, TimeUnit.SECONDS); - return client; - } - - - private static class SSLWebSocketClient extends WebSocketClient { - private final String endpointIdentificationAlgorithm; - public boolean onSSLError = false; - public boolean onOpen = false; - - public SSLWebSocketClient(String address, int port, String endpointIdentificationAlgorithm) - throws URISyntaxException { - super(new URI("wss://" + address + ':' + port)); - this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm; + @Test + @Timeout(2000) + public void test_localServer_ServerLocalhost_Client127_CheckInactive() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), ""); + assertTrue(client.onOpen, "client is open"); + assertFalse(client.onSSLError, "client has not caught a SSLHandshakeException"); } - @Override - public void onOpen(ServerHandshake handshakedata) { - this.onOpen = true; + @Test + @Timeout(2000) + public void test_localServer_ServerLocalhost_Client127_CheckDefault() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), null); + assertFalse(client.onOpen, "client is not open"); + assertTrue(client.onSSLError, "client has caught a SSLHandshakeException"); } - @Override - public void onMessage(String message) { + @Test + @Timeout(2000) + public void test_localServer_ServerLocalhost_ClientLocalhost_CheckActive() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), + "HTTPS"); + assertTrue(client.onOpen, "client is open"); + assertFalse(client.onSSLError, "client has not caught a SSLHandshakeException"); } - @Override - public void onClose(int code, String reason, boolean remote) { + @Test + @Timeout(2000) + public void test_localServer_ServerLocalhost_ClientLocalhost_CheckInactive() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), ""); + assertTrue(client.onOpen, "client is open"); + assertFalse(client.onSSLError, "client has not caught a SSLHandshakeException"); } - @Override - public void onError(Exception ex) { - if (ex instanceof SSLHandshakeException) { - this.onSSLError = true; - } + @Test + @Timeout(2000) + public void test_localServer_ServerLocalhost_ClientLocalhost_CheckDefault() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), null); + assertTrue(client.onOpen, "client is open"); + assertFalse(client.onSSLError, "client has not caught a SSLHandshakeException"); } - @Override - protected void onSetSSLParameters(SSLParameters sslParameters) { - // Always call super to ensure hostname validation is active by default - super.onSetSSLParameters(sslParameters); - if (endpointIdentificationAlgorithm != null) { - sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm); - } + + public SSLWebSocketClient testIssueWithLocalServer(String address, int port, + SSLContext serverContext, SSLContext clientContext, String endpointIdentificationAlgorithm) + throws IOException, URISyntaxException, InterruptedException { + CountDownLatch countServerDownLatch = new CountDownLatch(1); + SSLWebSocketClient client = new SSLWebSocketClient(address, port, + endpointIdentificationAlgorithm); + WebSocketServer server = new SSLWebSocketServer(port, countServerDownLatch); + + server.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(serverContext)); + if (clientContext != null) { + client.setSocketFactory(clientContext.getSocketFactory()); + } + server.start(); + countServerDownLatch.await(); + client.connectBlocking(1, TimeUnit.SECONDS); + return client; } - } + private static class SSLWebSocketClient extends WebSocketClient { - private static class SSLWebSocketServer extends WebSocketServer { + private final String endpointIdentificationAlgorithm; + public boolean onSSLError = false; + public boolean onOpen = false; - private final CountDownLatch countServerDownLatch; + public SSLWebSocketClient(String address, int port, String endpointIdentificationAlgorithm) + throws URISyntaxException { + super(new URI("wss://" + address + ':' + port)); + this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm; + } + @Override + public void onOpen(ServerHandshake handshakedata) { + this.onOpen = true; + } - public SSLWebSocketServer(int port, CountDownLatch countServerDownLatch) { - super(new InetSocketAddress(port)); - this.countServerDownLatch = countServerDownLatch; - } + @Override + public void onMessage(String message) { + } - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - } + @Override + public void onClose(int code, String reason, boolean remote) { + } - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - } + @Override + public void onError(Exception ex) { + if (ex instanceof SSLHandshakeException) { + this.onSSLError = true; + } + } - @Override - public void onMessage(WebSocket conn, String message) { + @Override + protected void onSetSSLParameters(SSLParameters sslParameters) { + // Always call super to ensure hostname validation is active by default + super.onSetSSLParameters(sslParameters); + if (endpointIdentificationAlgorithm != null) { + sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm); + } + } } - @Override - public void onError(WebSocket conn, Exception ex) { - ex.printStackTrace(); - } - @Override - public void onStart() { - countServerDownLatch.countDown(); + private static class SSLWebSocketServer extends WebSocketServer { + + private final CountDownLatch countServerDownLatch; + + + public SSLWebSocketServer(int port, CountDownLatch countServerDownLatch) { + super(new InetSocketAddress(port)); + this.countServerDownLatch = countServerDownLatch; + } + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + ex.printStackTrace(); + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } } - } } diff --git a/src/test/java/org/java_websocket/misc/AllMiscTests.java b/src/test/java/org/java_websocket/misc/AllMiscTests.java deleted file mode 100644 index bd643c093..000000000 --- a/src/test/java/org/java_websocket/misc/AllMiscTests.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.misc; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.misc.OpeningHandshakeRejectionTest.class -}) -/** - * Start all tests for mics - */ -public class AllMiscTests { - -} diff --git a/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java b/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java index fe1805c1e..8290d5244 100644 --- a/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java +++ b/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java @@ -25,247 +25,265 @@ package org.java_websocket.misc; -import static org.junit.Assert.fail; - import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.net.URI; import java.util.Scanner; +import java.util.concurrent.CountDownLatch; + import org.java_websocket.client.WebSocketClient; import org.java_websocket.framing.CloseFrame; import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.util.Charsetfunctions; import org.java_websocket.util.SocketUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.*; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class OpeningHandshakeRejectionTest { - private static final String additionalHandshake = "Upgrade: websocket\r\nConnection: Upgrade\r\n\r\n"; - private static int counter = 0; - private static Thread thread; - private static ServerSocket serverSocket; + private int port = -1; + private Thread thread; + private ServerSocket serverSocket; - private static boolean debugPrintouts = false; + private static final String additionalHandshake = "Upgrade: websocket\r\nConnection: Upgrade\r\n\r\n"; - private static int port; + public void startServer() throws InterruptedException { + this.port = SocketUtil.getAvailablePort(); + this.thread = new Thread( + () -> { + try { + serverSocket = new ServerSocket(port); + serverSocket.setReuseAddress(true); + while (true) { + Socket client = null; + try { + client = serverSocket.accept(); + Scanner in = new Scanner(client.getInputStream()); + if (!in.hasNextLine()) { + continue; + } + String input = in.nextLine(); + String testCase = input.split(" ")[1]; + OutputStream os = client.getOutputStream(); + if ("/0".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.1 100 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/1".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.0 100 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/2".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP 100 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/3".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.1 200 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/4".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP 101 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/5".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.1 404 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/6".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/2.0 404 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/7".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.1 500 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/8".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("GET 302 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/9".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + "GET HTTP/1.1 101 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/10".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.1 101 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/11".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + "HTTP/1.1 101 Websocket Connection Upgrade\r\n" + additionalHandshake)); + os.flush(); + } + } catch (IOException e) { + // + } + } + } catch (Exception e) { + fail("There should not be an exception: " + e.getMessage() + " Port: " + port); + } + }); + this.thread.start(); + } - @BeforeClass - public static void startServer() throws Exception { - port = SocketUtil.getAvailablePort(); - thread = new Thread( - new Runnable() { - public void run() { - try { - serverSocket = new ServerSocket(port); - serverSocket.setReuseAddress(true); - while (true) { - Socket client = null; - try { - client = serverSocket.accept(); - Scanner in = new Scanner(client.getInputStream()); - String input = in.nextLine(); - String testCase = input.split(" ")[1]; - OutputStream os = client.getOutputStream(); - if ("/0".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP/1.1 100 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/1".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP/1.0 100 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/2".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP 100 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/3".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP/1.1 200 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/4".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP 101 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/5".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP/1.1 404 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/6".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP/2.0 404 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/7".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP/1.1 500 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/8".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("GET 302 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/9".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes( - "GET HTTP/1.1 101 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/10".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP/1.1 101 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/11".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes( - "HTTP/1.1 101 Websocket Connection Upgrade\r\n" + additionalHandshake)); - os.flush(); - } - } catch (IOException e) { - // - } - } - } catch (Exception e) { - fail("There should be no exception"); - } - } - }); - thread.start(); - } + @AfterEach + public void cleanUp() throws IOException { + if (serverSocket != null) { + serverSocket.close(); + } + if (thread != null) { + thread.interrupt(); + } + } - @AfterClass - public static void successTests() throws InterruptedException, IOException { - serverSocket.close(); - thread.interrupt(); - if (debugPrintouts) { - System.out.println(counter + " successful tests"); + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase0() throws Exception { + testHandshakeRejection(0); } - } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase0() throws Exception { - testHandshakeRejection(0); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase1() throws Exception { + testHandshakeRejection(1); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase1() throws Exception { - testHandshakeRejection(1); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase2() throws Exception { + testHandshakeRejection(2); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase2() throws Exception { - testHandshakeRejection(2); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase3() throws Exception { + testHandshakeRejection(3); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase3() throws Exception { - testHandshakeRejection(3); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase4() throws Exception { + testHandshakeRejection(4); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase4() throws Exception { - testHandshakeRejection(4); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase5() throws Exception { + testHandshakeRejection(5); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase5() throws Exception { - testHandshakeRejection(5); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase6() throws Exception { + testHandshakeRejection(6); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase6() throws Exception { - testHandshakeRejection(6); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase7() throws Exception { + testHandshakeRejection(7); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase7() throws Exception { - testHandshakeRejection(7); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase8() throws Exception { + testHandshakeRejection(8); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase8() throws Exception { - testHandshakeRejection(8); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase9() throws Exception { + testHandshakeRejection(9); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase9() throws Exception { - testHandshakeRejection(9); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase10() throws Exception { + testHandshakeRejection(10); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase10() throws Exception { - testHandshakeRejection(10); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase11() throws Exception { + testHandshakeRejection(11); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase11() throws Exception { - testHandshakeRejection(11); - } + private void testHandshakeRejection(int i) throws Exception { + startServer(); + assertTrue(SocketUtil.waitForServerToStart(this.port), "Server Start Status"); + final int finalI = i; + final CountDownLatch countDownLatch = new CountDownLatch(1); + WebSocketClient webSocketClient = new WebSocketClient( + new URI("ws://localhost:" + this.port + "/" + finalI)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + fail("There should not be a connection!"); + } - private void testHandshakeRejection(int i) throws Exception { - final int finalI = i; - final boolean[] threadReturned = {false}; - WebSocketClient webSocketClient = new WebSocketClient( - new URI("ws://localhost:" + port + "/" + finalI)) { - @Override - public void onOpen(ServerHandshake handshakedata) { - fail("There should not be a connection!"); - } + @Override + public void onMessage(String message) { + fail("There should not be a message!"); + } - @Override - public void onMessage(String message) { - fail("There should not be a message!"); - } + @Override + public void onClose(int code, String reason, boolean remote) { + if (finalI != 10 && finalI != 11) { + if (code != CloseFrame.PROTOCOL_ERROR) { + fail("There should be a protocol error!"); + } else if (reason.startsWith("Invalid status code received:") || reason + .startsWith("Invalid status line received:")) { + countDownLatch.countDown(); + } else { + fail("The reason should be included!"); + } + } else { + //Since we do not include a correct Sec-WebSocket-Accept, onClose will be called with reason 'Draft refuses handshake' + if (!reason.endsWith("refuses handshake")) { + fail("onClose should not be called!"); + } else { + countDownLatch.countDown(); + } + } + } - @Override - public void onClose(int code, String reason, boolean remote) { - if (finalI != 10 && finalI != 11) { - if (code != CloseFrame.PROTOCOL_ERROR) { - fail("There should be a protocol error!"); - } else if (reason.startsWith("Invalid status code received:") || reason - .startsWith("Invalid status line received:")) { - if (debugPrintouts) { - System.out.println("Protocol error for test case: " + finalI); + @Override + public void onError(Exception ex) { + fail("There should not be an exception: " + ex.getMessage() + " Port: " + port); } - threadReturned[0] = true; - counter++; - } else { - fail("The reason should be included!"); - } - } else { - //Since we do not include a correct Sec-WebSocket-Accept, onClose will be called with reason 'Draft refuses handshake' - if (!reason.endsWith("refuses handshake")) { - fail("onClose should not be called!"); - } else { - if (debugPrintouts) { - System.out.println("Refuses handshake error for test case: " + finalI); + }; + final AssertionError[] exc = new AssertionError[1]; + exc[0] = null; + Thread finalThread = new Thread(new Runnable() { + @Override + public void run() { + try { + webSocketClient.run(); + } catch (AssertionError e) { + exc[0] = e; + countDownLatch.countDown(); + } } - counter++; - threadReturned[0] = true; - } - } - } - - @Override - public void onError(Exception ex) { - fail("There should not be an exception"); - } - }; - Thread finalThread = new Thread(webSocketClient); - finalThread.start(); - finalThread.join(); - if (!threadReturned[0]) { - fail("Error"); + }); + finalThread.start(); + finalThread.join(); + if (exc[0] != null) { + throw exc[0]; + } + countDownLatch.await(); } - } } diff --git a/src/test/java/org/java_websocket/protocols/AllProtocolTests.java b/src/test/java/org/java_websocket/protocols/AllProtocolTests.java deleted file mode 100644 index 60c31ae02..000000000 --- a/src/test/java/org/java_websocket/protocols/AllProtocolTests.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.protocols; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.protocols.ProtocolTest.class, - ProtocolHandshakeRejectionTest.class -}) -/** - * Start all tests for protocols - */ -public class AllProtocolTests { - -} diff --git a/src/test/java/org/java_websocket/protocols/ProtocolHandshakeRejectionTest.java b/src/test/java/org/java_websocket/protocols/ProtocolHandshakeRejectionTest.java index f1249ff11..c8c1d69e3 100644 --- a/src/test/java/org/java_websocket/protocols/ProtocolHandshakeRejectionTest.java +++ b/src/test/java/org/java_websocket/protocols/ProtocolHandshakeRejectionTest.java @@ -25,10 +25,6 @@ package org.java_websocket.protocols; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; @@ -39,6 +35,8 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; +import java.util.concurrent.CountDownLatch; + import org.java_websocket.client.WebSocketClient; import org.java_websocket.drafts.Draft_6455; import org.java_websocket.extensions.IExtension; @@ -47,587 +45,621 @@ import org.java_websocket.util.Base64; import org.java_websocket.util.Charsetfunctions; import org.java_websocket.util.SocketUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.*; + +import static org.junit.jupiter.api.Assertions.*; public class ProtocolHandshakeRejectionTest { - private static final String additionalHandshake = "HTTP/1.1 101 Websocket Connection Upgrade\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"; - private static Thread thread; - private static ServerSocket serverSocket; - - private static int port; - - @BeforeClass - public static void startServer() throws Exception { - port = SocketUtil.getAvailablePort(); - thread = new Thread( - new Runnable() { - public void run() { - try { - serverSocket = new ServerSocket(port); - serverSocket.setReuseAddress(true); - while (true) { - Socket client = null; - try { - client = serverSocket.accept(); - Scanner in = new Scanner(client.getInputStream()); - String input = in.nextLine(); - String testCase = input.split(" ")[1]; - String seckey = ""; - String secproc = ""; - while (in.hasNext()) { - input = in.nextLine(); - if (input.startsWith("Sec-WebSocket-Key: ")) { - seckey = input.split(" ")[1]; - } - if (input.startsWith("Sec-WebSocket-Protocol: ")) { - secproc = input.split(" ")[1]; + private static final String additionalHandshake = "HTTP/1.1 101 Websocket Connection Upgrade\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"; + private Thread thread; + private ServerSocket serverSocket; + + private int port = -1; + + public void startServer() throws InterruptedException { + port = SocketUtil.getAvailablePort(); + thread = new Thread( + () -> { + try { + serverSocket = new ServerSocket(port); + serverSocket.setReuseAddress(true); + while (true) { + Socket client = null; + try { + client = serverSocket.accept(); + Scanner in = new Scanner(client.getInputStream()); + if (!in.hasNextLine()) { + continue; + } + String input = in.nextLine(); + String testCase = input.split(" ")[1]; + String seckey = ""; + String secproc = ""; + while (in.hasNext()) { + input = in.nextLine(); + if (input.startsWith("Sec-WebSocket-Key: ")) { + seckey = input.split(" ")[1]; + } + if (input.startsWith("Sec-WebSocket-Protocol: ")) { + secproc = input.split(" ")[1]; + } + //Last + if (input.startsWith("Upgrade")) { + break; + } + } + OutputStream os = client.getOutputStream(); + if ("/0".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); + os.flush(); + } + if ("/1".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: chat" + + "\r\n\r\n")); + os.flush(); + } + if ("/2".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat, chat2" + "\r\n\r\n")); + os.flush(); + } + if ("/3".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/4".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat\r\nSec-WebSocket-Protocol: chat2,chat3" + + "\r\n\r\n")); + os.flush(); + } + if ("/5".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); + os.flush(); + } + if ("/6".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: chat" + + "\r\n\r\n")); + os.flush(); + } + if ("/7".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat, chat2" + "\r\n\r\n")); + os.flush(); + } + if ("/8".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/9".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat\r\nSec-WebSocket-Protocol: chat2,chat3" + + "\r\n\r\n")); + os.flush(); + } + if ("/10".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/11".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat2, chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/12".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat2\r\nSec-WebSocket-Protocol: chat3" + + "\r\n\r\n")); + os.flush(); + } + if ("/13".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat2\r\nSec-WebSocket-Protocol: chat" + + "\r\n\r\n")); + os.flush(); + } + if ("/14".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat2,chat" + "\r\n\r\n")); + os.flush(); + } + if ("/15".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: chat3" + + "\r\n\r\n")); + os.flush(); + } + if ("/16".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); + os.flush(); + } + if ("/17".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); + os.flush(); + } + if ("/18".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + "Sec-WebSocket-Accept: abc\r\n" + "\r\n")); + os.flush(); + } + if ("/19".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + "\r\n")); + os.flush(); + } + // Order check + if ("/20".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/21".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/22".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/23".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/24".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/25".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: abc" + + "\r\n\r\n")); + os.flush(); + } + if ("/26".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n\r\n")); + os.flush(); + } + if ("/27".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/28".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: abc" + + "\r\n\r\n")); + os.flush(); + } + if ("/29".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n\r\n")); + os.flush(); + } + } catch (IOException e) { + // + } + } + } catch (Exception e) { + fail("There should be no exception", e); } - //Last - if (input.startsWith("Upgrade")) { - break; + }); + thread.start(); + } + + private static String getSecKey(String seckey) { + return "Sec-WebSocket-Accept: " + generateFinalKey(seckey) + "\r\n"; + } + + @AfterEach + public void successTests() throws IOException { + if (serverSocket != null) { + serverSocket.close(); + } + if (thread != null) { + thread.interrupt(); + } + } + + @Test + @Timeout(5000) + public void testProtocolRejectionTestCase0() throws Exception { + testProtocolRejection(0, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase1() throws Exception { + testProtocolRejection(1, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase2() throws Exception { + testProtocolRejection(2, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase3() throws Exception { + testProtocolRejection(3, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase4() throws Exception { + testProtocolRejection(4, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase5() throws Exception { + testProtocolRejection(5, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase6() throws Exception { + testProtocolRejection(6, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase7() throws Exception { + testProtocolRejection(7, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase8() throws Exception { + testProtocolRejection(8, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase9() throws Exception { + testProtocolRejection(9, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase10() throws Exception { + testProtocolRejection(10, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase11() throws Exception { + testProtocolRejection(11, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase12() throws Exception { + testProtocolRejection(12, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase13() throws Exception { + testProtocolRejection(13, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase14() throws Exception { + ArrayList protocols = new ArrayList<>(); + protocols.add(new Protocol("chat")); + protocols.add(new Protocol("chat2")); + testProtocolRejection(14, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase15() throws Exception { + ArrayList protocols = new ArrayList<>(); + protocols.add(new Protocol("chat")); + protocols.add(new Protocol("chat2")); + testProtocolRejection(15, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase16() throws Exception { + ArrayList protocols = new ArrayList<>(); + protocols.add(new Protocol("chat")); + protocols.add(new Protocol("chat2")); + testProtocolRejection(16, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase17() throws Exception { + ArrayList protocols = new ArrayList<>(); + protocols.add(new Protocol("chat")); + protocols.add(new Protocol("")); + testProtocolRejection(17, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase18() throws Exception { + testProtocolRejection(18, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase19() throws Exception { + testProtocolRejection(19, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase20() throws Exception { + testProtocolRejection(20, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase21() throws Exception { + ArrayList protocols = new ArrayList<>(); + protocols.add(new Protocol("chat1")); + protocols.add(new Protocol("chat2")); + protocols.add(new Protocol("chat3")); + testProtocolRejection(21, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase22() throws Exception { + ArrayList protocols = new ArrayList<>(); + protocols.add(new Protocol("chat2")); + protocols.add(new Protocol("chat3")); + protocols.add(new Protocol("chat1")); + testProtocolRejection(22, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase23() throws Exception { + ArrayList protocols = new ArrayList<>(); + protocols.add(new Protocol("chat3")); + protocols.add(new Protocol("chat2")); + protocols.add(new Protocol("chat1")); + testProtocolRejection(23, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase24() throws Exception { + testProtocolRejection(24, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase25() throws Exception { + testProtocolRejection(25, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase26() throws Exception { + testProtocolRejection(26, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase27() throws Exception { + testProtocolRejection(27, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("opc")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase28() throws Exception { + testProtocolRejection(28, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("opc")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase29() throws Exception { + testProtocolRejection(29, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("opc")))); + } + + private void testProtocolRejection(int i, Draft_6455 draft) throws Exception { + startServer(); + assertTrue(SocketUtil.waitForServerToStart(this.port), "Server Start Status"); + final int finalI = i; + final CountDownLatch countDownLatch = new CountDownLatch(1); + final WebSocketClient webSocketClient = new WebSocketClient( + new URI("ws://localhost:" + port + "/" + finalI), draft) { + @Override + public void onOpen(ServerHandshake handshakedata) { + switch (finalI) { + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 13: + case 14: + case 17: + case 20: + case 21: + case 22: + case 23: + case 24: + case 25: + case 26: + countDownLatch.countDown(); + closeConnection(CloseFrame.ABNORMAL_CLOSE, "Bye"); + break; + default: + fail("There should not be a connection!"); + } + } + + @Override + public void onMessage(String message) { + fail("There should not be a message!"); + } + + @Override + public void onClose(int code, String reason, boolean remote) { + switch (finalI) { + case 0: + case 1: + case 2: + case 3: + case 4: + case 17: + case 20: + case 24: + case 25: + case 26: + assertEquals("", getProtocol().getProvidedProtocol()); + break; + case 5: + case 9: + case 10: + case 11: + case 12: + case 13: + case 15: + case 16: + case 18: + case 19: + case 27: + case 28: + case 29: + assertNull(getProtocol()); + break; + case 6: + case 7: + case 8: + case 14: + assertEquals("chat", getProtocol().getProvidedProtocol()); + break; + case 22: + assertEquals("chat2", getProtocol().getProvidedProtocol()); + break; + case 21: + assertEquals("chat1", getProtocol().getProvidedProtocol()); + break; + case 23: + assertEquals("chat3", getProtocol().getProvidedProtocol()); + break; + default: + fail(); + } + if (code == CloseFrame.ABNORMAL_CLOSE) { + switch (finalI) { + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 13: + case 14: + case 17: + case 20: + case 21: + case 22: + case 23: + case 24: + case 25: + case 26: + return; } - } - OutputStream os = client.getOutputStream(); - if ("/0".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); - os.flush(); - } - if ("/1".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes( - additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: chat" - + "\r\n\r\n")); - os.flush(); - } - if ("/2".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat, chat2" + "\r\n\r\n")); - os.flush(); - } - if ("/3".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat,chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/4".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat\r\nSec-WebSocket-Protocol: chat2,chat3" - + "\r\n\r\n")); - os.flush(); - } - if ("/5".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); - os.flush(); - } - if ("/6".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes( - additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: chat" - + "\r\n\r\n")); - os.flush(); - } - if ("/7".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat, chat2" + "\r\n\r\n")); - os.flush(); - } - if ("/8".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat,chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/9".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat\r\nSec-WebSocket-Protocol: chat2,chat3" - + "\r\n\r\n")); - os.flush(); - } - if ("/10".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/11".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat2, chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/12".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat2\r\nSec-WebSocket-Protocol: chat3" - + "\r\n\r\n")); - os.flush(); - } - if ("/13".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat2\r\nSec-WebSocket-Protocol: chat" - + "\r\n\r\n")); - os.flush(); - } - if ("/14".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat2,chat" + "\r\n\r\n")); - os.flush(); - } - if ("/15".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes( - additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: chat3" - + "\r\n\r\n")); - os.flush(); - } - if ("/16".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); - os.flush(); - } - if ("/17".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); - os.flush(); - } - if ("/18".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes( - additionalHandshake + "Sec-WebSocket-Accept: abc\r\n" + "\r\n")); - os.flush(); - } - if ("/19".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + "\r\n")); - os.flush(); - } - // Order check - if ("/20".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/21".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/22".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/23".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/24".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/25".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes( - additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: abc" - + "\r\n\r\n")); - os.flush(); - } - if ("/26".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n\r\n")); - os.flush(); - } - if ("/27".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/28".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes( - additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: abc" - + "\r\n\r\n")); - os.flush(); - } - if ("/29".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n\r\n")); - os.flush(); - } - } catch (IOException e) { - // } - } - } catch (Exception e) { - e.printStackTrace(); - fail("There should be no exception"); + if (code != CloseFrame.PROTOCOL_ERROR) { + fail("There should be a protocol error! " + finalI + " " + code); + } else if (reason.endsWith("refuses handshake")) { + countDownLatch.countDown(); + } else { + fail("The reason should be included!"); + } } - } + + @Override + public void onError(Exception ex) { + fail("There should not be an exception: " + ex.getMessage() + " Port: " + port); + } + }; + final AssertionError[] exc = new AssertionError[1]; + exc[0] = null; + Thread finalThread = new Thread(new Runnable() { + @Override + public void run() { + try { + webSocketClient.run(); + } catch (AssertionError e) { + exc[0] = e; + countDownLatch.countDown(); + } + } + }); - thread.start(); - } - - private static String getSecKey(String seckey) { - return "Sec-WebSocket-Accept: " + generateFinalKey(seckey) + "\r\n"; - } - - @AfterClass - public static void successTests() throws IOException { - serverSocket.close(); - thread.interrupt(); - } - - @Test(timeout = 5000) - public void testProtocolRejectionTestCase0() throws Exception { - testProtocolRejection(0, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase1() throws Exception { - testProtocolRejection(1, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase2() throws Exception { - testProtocolRejection(2, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase3() throws Exception { - testProtocolRejection(3, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase4() throws Exception { - testProtocolRejection(4, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase5() throws Exception { - testProtocolRejection(5, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase6() throws Exception { - testProtocolRejection(6, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase7() throws Exception { - testProtocolRejection(7, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase8() throws Exception { - testProtocolRejection(8, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase9() throws Exception { - testProtocolRejection(9, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase10() throws Exception { - testProtocolRejection(10, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase11() throws Exception { - testProtocolRejection(11, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase12() throws Exception { - testProtocolRejection(12, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase13() throws Exception { - testProtocolRejection(13, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase14() throws Exception { - ArrayList protocols = new ArrayList<>(); - protocols.add(new Protocol("chat")); - protocols.add(new Protocol("chat2")); - testProtocolRejection(14, new Draft_6455(Collections.emptyList(), protocols)); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase15() throws Exception { - ArrayList protocols = new ArrayList<>(); - protocols.add(new Protocol("chat")); - protocols.add(new Protocol("chat2")); - testProtocolRejection(15, new Draft_6455(Collections.emptyList(), protocols)); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase16() throws Exception { - ArrayList protocols = new ArrayList<>(); - protocols.add(new Protocol("chat")); - protocols.add(new Protocol("chat2")); - testProtocolRejection(16, new Draft_6455(Collections.emptyList(), protocols)); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase17() throws Exception { - ArrayList protocols = new ArrayList<>(); - protocols.add(new Protocol("chat")); - protocols.add(new Protocol("")); - testProtocolRejection(17, new Draft_6455(Collections.emptyList(), protocols)); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase18() throws Exception { - testProtocolRejection(18, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase19() throws Exception { - testProtocolRejection(19, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase20() throws Exception { - testProtocolRejection(20, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase21() throws Exception { - ArrayList protocols = new ArrayList<>(); - protocols.add(new Protocol("chat1")); - protocols.add(new Protocol("chat2")); - protocols.add(new Protocol("chat3")); - testProtocolRejection(21, new Draft_6455(Collections.emptyList(), protocols)); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase22() throws Exception { - ArrayList protocols = new ArrayList<>(); - protocols.add(new Protocol("chat2")); - protocols.add(new Protocol("chat3")); - protocols.add(new Protocol("chat1")); - testProtocolRejection(22, new Draft_6455(Collections.emptyList(), protocols)); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase23() throws Exception { - ArrayList protocols = new ArrayList<>(); - protocols.add(new Protocol("chat3")); - protocols.add(new Protocol("chat2")); - protocols.add(new Protocol("chat1")); - testProtocolRejection(23, new Draft_6455(Collections.emptyList(), protocols)); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase24() throws Exception { - testProtocolRejection(24, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase25() throws Exception { - testProtocolRejection(25, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase26() throws Exception { - testProtocolRejection(26, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase27() throws Exception { - testProtocolRejection(27, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("opc")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase28() throws Exception { - testProtocolRejection(28, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("opc")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase29() throws Exception { - testProtocolRejection(29, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("opc")))); - } - - private void testProtocolRejection(int i, Draft_6455 draft) throws Exception { - final int finalI = i; - final boolean[] threadReturned = {false}; - final WebSocketClient webSocketClient = new WebSocketClient( - new URI("ws://localhost:" + port + "/" + finalI), draft) { - @Override - public void onOpen(ServerHandshake handshakedata) { - switch (finalI) { - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - case 8: - case 9: - case 13: - case 14: - case 17: - case 20: - case 21: - case 22: - case 23: - case 24: - case 25: - case 26: - threadReturned[0] = true; - closeConnection(CloseFrame.ABNORMAL_CLOSE, "Bye"); - break; - default: - fail("There should not be a connection!"); - } - } - - @Override - public void onMessage(String message) { - fail("There should not be a message!"); - } - - @Override - public void onClose(int code, String reason, boolean remote) { - switch (finalI) { - case 0: - case 1: - case 2: - case 3: - case 4: - case 17: - case 20: - case 24: - case 25: - case 26: - assertEquals("", getProtocol().getProvidedProtocol()); - break; - case 5: - case 9: - case 10: - case 11: - case 12: - case 13: - case 15: - case 16: - case 18: - case 19: - case 27: - case 28: - case 29: - assertNull(getProtocol()); - break; - case 6: - case 7: - case 8: - case 14: - assertEquals("chat", getProtocol().getProvidedProtocol()); - break; - case 22: - assertEquals("chat2", getProtocol().getProvidedProtocol()); - break; - case 21: - assertEquals("chat1", getProtocol().getProvidedProtocol()); - break; - case 23: - assertEquals("chat3", getProtocol().getProvidedProtocol()); - break; - default: - fail(); - } - if (code == CloseFrame.ABNORMAL_CLOSE) { - switch (finalI) { - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - case 8: - case 9: - case 13: - case 14: - case 17: - case 20: - case 21: - case 22: - case 23: - case 24: - case 25: - case 26: - return; - } - } - if (code != CloseFrame.PROTOCOL_ERROR) { - fail("There should be a protocol error! " + finalI + " " + code); - } else if (reason.endsWith("refuses handshake")) { - threadReturned[0] = true; - } else { - fail("The reason should be included!"); + finalThread.start(); + finalThread.join(); + if (exc[0] != null) { + throw exc[0]; } - } - - @Override - public void onError(Exception ex) { - fail("There should not be an exception"); - } - }; - final AssertionError[] exc = new AssertionError[1]; - exc[0] = null; - Thread finalThread = new Thread(new Runnable() { - @Override - public void run() { + + countDownLatch.await(); + + } + + /** + * Generate a final key from a input string + * + * @param in the input string + * @return a final key + */ + private static String generateFinalKey(String in) { + String seckey = in.trim(); + String acc = seckey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + MessageDigest sh1; try { - webSocketClient.run(); - }catch(AssertionError e){ - exc[0] = e; + sh1 = MessageDigest.getInstance("SHA1"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); } - } - - }); - finalThread.start(); - finalThread.join(); - if (exc[0] != null) { - throw exc[0]; - } - - if (!threadReturned[0]) { - fail("Error"); - } - - } - - /** - * Generate a final key from a input string - * - * @param in the input string - * @return a final key - */ - private static String generateFinalKey(String in) { - String seckey = in.trim(); - String acc = seckey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; - MessageDigest sh1; - try { - sh1 = MessageDigest.getInstance("SHA1"); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException(e); - } - return Base64.encodeBytes(sh1.digest(acc.getBytes())); - } + return Base64.encodeBytes(sh1.digest(acc.getBytes())); + } } diff --git a/src/test/java/org/java_websocket/protocols/ProtocolTest.java b/src/test/java/org/java_websocket/protocols/ProtocolTest.java index e07119535..895b5a4f1 100644 --- a/src/test/java/org/java_websocket/protocols/ProtocolTest.java +++ b/src/test/java/org/java_websocket/protocols/ProtocolTest.java @@ -25,13 +25,9 @@ package org.java_websocket.protocols; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; public class ProtocolTest { @@ -94,11 +90,11 @@ public void testEquals() throws Exception { Protocol protocol0 = new Protocol(""); Protocol protocol1 = new Protocol("protocol"); Protocol protocol2 = new Protocol("protocol"); - assertTrue(!protocol0.equals(protocol1)); - assertTrue(!protocol0.equals(protocol2)); - assertTrue(protocol1.equals(protocol2)); - assertTrue(!protocol1.equals(null)); - assertTrue(!protocol1.equals(new Object())); + assertNotEquals(protocol0, protocol1); + assertNotEquals(protocol0, protocol2); + assertEquals(protocol1, protocol2); + assertNotEquals(null, protocol1); + assertNotEquals(new Object(), protocol1); } @Test diff --git a/src/test/java/org/java_websocket/server/AllServerTests.java b/src/test/java/org/java_websocket/server/AllServerTests.java deleted file mode 100644 index f1f84fc90..000000000 --- a/src/test/java/org/java_websocket/server/AllServerTests.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.server; - -import org.java_websocket.protocols.ProtocolHandshakeRejectionTest; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.server.DefaultWebSocketServerFactoryTest.class, - ProtocolHandshakeRejectionTest.class -}) -/** - * Start all tests for the server - */ -public class AllServerTests { - -} diff --git a/src/test/java/org/java_websocket/server/CustomSSLWebSocketServerFactoryTest.java b/src/test/java/org/java_websocket/server/CustomSSLWebSocketServerFactoryTest.java index 1fa2d8a9a..a83d8de07 100644 --- a/src/test/java/org/java_websocket/server/CustomSSLWebSocketServerFactoryTest.java +++ b/src/test/java/org/java_websocket/server/CustomSSLWebSocketServerFactoryTest.java @@ -1,8 +1,5 @@ package org.java_websocket.server; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; @@ -19,7 +16,10 @@ import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_6455; import org.java_websocket.handshake.Handshakedata; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; public class CustomSSLWebSocketServerFactoryTest { @@ -82,10 +82,10 @@ public void testCreateWebSocket() throws NoSuchAlgorithmException { CustomWebSocketAdapter webSocketAdapter = new CustomWebSocketAdapter(); WebSocketImpl webSocketImpl = webSocketServerFactory .createWebSocket(webSocketAdapter, new Draft_6455()); - assertNotNull("webSocketImpl != null", webSocketImpl); + assertNotNull(webSocketImpl, "webSocketImpl != null"); webSocketImpl = webSocketServerFactory .createWebSocket(webSocketAdapter, Collections.singletonList(new Draft_6455())); - assertNotNull("webSocketImpl != null", webSocketImpl); + assertNotNull(webSocketImpl, "webSocketImpl != null"); } @Test diff --git a/src/test/java/org/java_websocket/server/DaemonThreadTest.java b/src/test/java/org/java_websocket/server/DaemonThreadTest.java index f1b25c6f0..9047a97da 100644 --- a/src/test/java/org/java_websocket/server/DaemonThreadTest.java +++ b/src/test/java/org/java_websocket/server/DaemonThreadTest.java @@ -1,24 +1,27 @@ package org.java_websocket.server; -import java.io.IOException; import java.net.*; import java.util.Set; import java.util.concurrent.CountDownLatch; import org.java_websocket.WebSocket; import org.java_websocket.handshake.*; import org.java_websocket.client.*; -import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class DaemonThreadTest { - @Test(timeout = 1000) - public void test_AllCreatedThreadsAreDaemon() throws Throwable { + @Test + @Timeout(1000) + public void test_AllCreatedThreadsAreDaemon() throws InterruptedException { Set threadSet1 = Thread.getAllStackTraces().keySet(); final CountDownLatch ready = new CountDownLatch(1); + final CountDownLatch serverStarted = new CountDownLatch(1); WebSocketServer server = new WebSocketServer(new InetSocketAddress(SocketUtil.getAvailablePort())) { @Override @@ -30,12 +33,13 @@ public void onMessage(WebSocket conn, String message) {} @Override public void onError(WebSocket conn, Exception ex) {} @Override - public void onStart() {} + public void onStart() {serverStarted.countDown();} }; server.setDaemon(true); server.setDaemon(false); server.setDaemon(true); server.start(); + serverStarted.await(); WebSocketClient client = new WebSocketClient(URI.create("ws://localhost:" + server.getPort())) { @Override @@ -57,10 +61,10 @@ public void onError(Exception ex) {} Set threadSet2 = Thread.getAllStackTraces().keySet(); threadSet2.removeAll(threadSet1); - assertTrue("new threads created (no new threads indicates issue in test)", !threadSet2.isEmpty()); + assertFalse(threadSet2.isEmpty(), "new threads created (no new threads indicates issue in test)"); for (Thread t : threadSet2) - assertTrue(t.getName(), t.isDaemon()); + assertTrue(t.isDaemon(), t.getName()); boolean exception = false; try { @@ -68,7 +72,7 @@ public void onError(Exception ex) {} } catch(IllegalStateException e) { exception = true; } - assertTrue("exception was thrown when calling setDaemon on a running server", exception); + assertTrue(exception, "exception was thrown when calling setDaemon on a running server"); server.stop(); } diff --git a/src/test/java/org/java_websocket/server/DefaultSSLWebSocketServerFactoryTest.java b/src/test/java/org/java_websocket/server/DefaultSSLWebSocketServerFactoryTest.java index 7872697ba..c8330a551 100644 --- a/src/test/java/org/java_websocket/server/DefaultSSLWebSocketServerFactoryTest.java +++ b/src/test/java/org/java_websocket/server/DefaultSSLWebSocketServerFactoryTest.java @@ -1,8 +1,5 @@ package org.java_websocket.server; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; @@ -19,7 +16,10 @@ import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_6455; import org.java_websocket.handshake.Handshakedata; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; public class DefaultSSLWebSocketServerFactoryTest { @@ -62,10 +62,10 @@ public void testCreateWebSocket() throws NoSuchAlgorithmException { CustomWebSocketAdapter webSocketAdapter = new CustomWebSocketAdapter(); WebSocketImpl webSocketImpl = webSocketServerFactory .createWebSocket(webSocketAdapter, new Draft_6455()); - assertNotNull("webSocketImpl != null", webSocketImpl); + assertNotNull(webSocketImpl,"webSocketImpl != null"); webSocketImpl = webSocketServerFactory .createWebSocket(webSocketAdapter, Collections.singletonList(new Draft_6455())); - assertNotNull("webSocketImpl != null", webSocketImpl); + assertNotNull( webSocketImpl, "webSocketImpl != null"); } @Test diff --git a/src/test/java/org/java_websocket/server/DefaultWebSocketServerFactoryTest.java b/src/test/java/org/java_websocket/server/DefaultWebSocketServerFactoryTest.java index a5c07ea43..77dafa56f 100644 --- a/src/test/java/org/java_websocket/server/DefaultWebSocketServerFactoryTest.java +++ b/src/test/java/org/java_websocket/server/DefaultWebSocketServerFactoryTest.java @@ -1,7 +1,5 @@ package org.java_websocket.server; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; import java.net.InetSocketAddress; import java.net.Socket; @@ -14,7 +12,10 @@ import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_6455; import org.java_websocket.handshake.Handshakedata; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; public class DefaultWebSocketServerFactoryTest { @@ -24,10 +25,10 @@ public void testCreateWebSocket() { CustomWebSocketAdapter webSocketAdapter = new CustomWebSocketAdapter(); WebSocketImpl webSocketImpl = webSocketServerFactory .createWebSocket(webSocketAdapter, new Draft_6455()); - assertNotNull("webSocketImpl != null", webSocketImpl); + assertNotNull(webSocketImpl, "webSocketImpl != null"); webSocketImpl = webSocketServerFactory .createWebSocket(webSocketAdapter, Collections.singletonList(new Draft_6455())); - assertNotNull("webSocketImpl != null", webSocketImpl); + assertNotNull(webSocketImpl, "webSocketImpl != null"); } @Test @@ -35,7 +36,7 @@ public void testWrapChannel() { DefaultWebSocketServerFactory webSocketServerFactory = new DefaultWebSocketServerFactory(); SocketChannel channel = (new Socket()).getChannel(); SocketChannel result = webSocketServerFactory.wrapChannel(channel, null); - assertSame("channel == result", channel, result); + assertSame(channel, result, "channel == result"); } @Test diff --git a/src/test/java/org/java_websocket/server/SSLParametersWebSocketServerFactoryTest.java b/src/test/java/org/java_websocket/server/SSLParametersWebSocketServerFactoryTest.java index 5ac83337d..00715d231 100644 --- a/src/test/java/org/java_websocket/server/SSLParametersWebSocketServerFactoryTest.java +++ b/src/test/java/org/java_websocket/server/SSLParametersWebSocketServerFactoryTest.java @@ -1,8 +1,5 @@ package org.java_websocket.server; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; @@ -20,7 +17,10 @@ import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_6455; import org.java_websocket.handshake.Handshakedata; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; public class SSLParametersWebSocketServerFactoryTest { @@ -57,10 +57,10 @@ public void testCreateWebSocket() throws NoSuchAlgorithmException { CustomWebSocketAdapter webSocketAdapter = new CustomWebSocketAdapter(); WebSocketImpl webSocketImpl = webSocketServerFactory .createWebSocket(webSocketAdapter, new Draft_6455()); - assertNotNull("webSocketImpl != null", webSocketImpl); + assertNotNull(webSocketImpl, "webSocketImpl != null"); webSocketImpl = webSocketServerFactory .createWebSocket(webSocketAdapter, Collections.singletonList(new Draft_6455())); - assertNotNull("webSocketImpl != null", webSocketImpl); + assertNotNull(webSocketImpl, "webSocketImpl != null"); } @Test diff --git a/src/test/java/org/java_websocket/server/WebSocketServerTest.java b/src/test/java/org/java_websocket/server/WebSocketServerTest.java index 5bebf8028..9af9d10e8 100644 --- a/src/test/java/org/java_websocket/server/WebSocketServerTest.java +++ b/src/test/java/org/java_websocket/server/WebSocketServerTest.java @@ -26,9 +26,6 @@ package org.java_websocket.server; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.fail; import java.io.IOException; import java.net.InetSocketAddress; @@ -43,7 +40,9 @@ import org.java_websocket.drafts.Draft_6455; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class WebSocketServerTest { @@ -111,7 +110,7 @@ public void testConstructor() { @Test - public void testGetAddress() throws IOException { + public void testGetAddress() throws InterruptedException { int port = SocketUtil.getAvailablePort(); InetSocketAddress inetSocketAddress = new InetSocketAddress(port); MyWebSocketServer server = new MyWebSocketServer(port); @@ -145,9 +144,9 @@ public void testGetPort() throws IOException, InterruptedException { @Test public void testMaxPendingConnections() { MyWebSocketServer server = new MyWebSocketServer(1337); - assertEquals(server.getMaxPendingConnections(), -1); + assertEquals(-1, server.getMaxPendingConnections()); server.setMaxPendingConnections(10); - assertEquals(server.getMaxPendingConnections(), 10); + assertEquals(10, server.getMaxPendingConnections()); } @Test diff --git a/src/test/java/org/java_websocket/util/Base64Test.java b/src/test/java/org/java_websocket/util/Base64Test.java index 4382aab60..0d546db50 100644 --- a/src/test/java/org/java_websocket/util/Base64Test.java +++ b/src/test/java/org/java_websocket/util/Base64Test.java @@ -25,27 +25,24 @@ package org.java_websocket.util; +import org.junit.jupiter.api.Test; + import java.io.IOException; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -public class Base64Test { +import static org.junit.jupiter.api.Assertions.*; - @Rule - public final ExpectedException thrown = ExpectedException.none(); +public class Base64Test { @Test public void testEncodeBytes() throws IOException { - Assert.assertEquals("", Base64.encodeBytes(new byte[0])); - Assert.assertEquals("QHE=", + assertEquals("", Base64.encodeBytes(new byte[0])); + assertEquals("QHE=", Base64.encodeBytes(new byte[]{49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 2, 2, 0)); assertGzipEncodedBytes("H4sIAAAAAAAA", "MEALfv3IMBAAAA", Base64.encodeBytes(new byte[]{49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 0, 1, 6)); assertGzipEncodedBytes("H4sIAAAAAAAA", "MoBABQHKKWAgAAAA==", Base64.encodeBytes(new byte[]{49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 2, 2, 18)); - Assert.assertEquals("F63=", + assertEquals("F63=", Base64.encodeBytes(new byte[]{49, 121, 64, 113, 63, 43, -24, 62, 4, 48}, 2, 2, 32)); assertGzipEncodedBytes("6sg7--------", "Bc0-0F699L-V----==", Base64.encodeBytes(new byte[]{49, 121, 64, 113, 63, 43, -24, 62, 4, 48}, 2, 2, 34)); @@ -53,57 +50,56 @@ public void testEncodeBytes() throws IOException { // see https://bugs.openjdk.org/browse/JDK-8253142 private void assertGzipEncodedBytes(String expectedPrefix, String expectedSuffix, String actual) { - Assert.assertTrue(actual.startsWith(expectedPrefix)); - Assert.assertTrue(actual.endsWith(expectedSuffix)); + assertTrue(actual.startsWith(expectedPrefix)); + assertTrue(actual.endsWith(expectedSuffix)); } @Test - public void testEncodeBytes2() throws IOException { - thrown.expect(IllegalArgumentException.class); - Base64.encodeBytes(new byte[0], -2, -2, -56); + public void testEncodeBytes2() { + assertThrows(IllegalArgumentException.class, () -> + Base64.encodeBytes(new byte[0], -2, -2, -56)); } @Test - public void testEncodeBytes3() throws IOException { - thrown.expect(IllegalArgumentException.class); + public void testEncodeBytes3() { + assertThrows(IllegalArgumentException.class, () -> Base64.encodeBytes(new byte[]{64, -128, 32, 18, 16, 16, 0, 18, 16}, - 2064072977, -2064007440, 10); + 2064072977, -2064007440, 10)); } @Test public void testEncodeBytes4() { - thrown.expect(NullPointerException.class); - Base64.encodeBytes(null); + assertThrows(NullPointerException.class, () -> Base64.encodeBytes(null)); } @Test - public void testEncodeBytes5() throws IOException { - thrown.expect(IllegalArgumentException.class); - Base64.encodeBytes(null, 32766, 0, 8); + public void testEncodeBytes5() { + assertThrows(IllegalArgumentException.class, () -> + Base64.encodeBytes(null, 32766, 0, 8)); } @Test public void testEncodeBytesToBytes1() throws IOException { - Assert.assertArrayEquals(new byte[]{95, 68, 111, 78, 55, 45, 61, 61}, + assertArrayEquals(new byte[]{95, 68, 111, 78, 55, 45, 61, 61}, Base64.encodeBytesToBytes(new byte[]{-108, -19, 24, 32}, 0, 4, 32)); - Assert.assertArrayEquals(new byte[]{95, 68, 111, 78, 55, 67, 111, 61}, + assertArrayEquals(new byte[]{95, 68, 111, 78, 55, 67, 111, 61}, Base64.encodeBytesToBytes(new byte[]{-108, -19, 24, 32, -35}, 0, 5, 40)); - Assert.assertArrayEquals(new byte[]{95, 68, 111, 78, 55, 67, 111, 61}, + assertArrayEquals(new byte[]{95, 68, 111, 78, 55, 67, 111, 61}, Base64.encodeBytesToBytes(new byte[]{-108, -19, 24, 32, -35}, 0, 5, 32)); - Assert.assertArrayEquals(new byte[]{87, 50, 77, 61}, + assertArrayEquals(new byte[]{87, 50, 77, 61}, Base64.encodeBytesToBytes(new byte[]{115, 42, 123, 99, 10, -33, 75, 30, 91, 99}, 8, 2, 48)); - Assert.assertArrayEquals(new byte[]{87, 50, 77, 61}, + assertArrayEquals(new byte[]{87, 50, 77, 61}, Base64.encodeBytesToBytes(new byte[]{115, 42, 123, 99, 10, -33, 75, 30, 91, 99}, 8, 2, 56)); - Assert.assertArrayEquals(new byte[]{76, 53, 66, 61}, + assertArrayEquals(new byte[]{76, 53, 66, 61}, Base64.encodeBytesToBytes(new byte[]{113, 42, 123, 99, 10, -33, 75, 30, 88, 99}, 8, 2, 36)); - Assert.assertArrayEquals(new byte[]{87, 71, 77, 61}, + assertArrayEquals(new byte[]{87, 71, 77, 61}, Base64.encodeBytesToBytes(new byte[]{113, 42, 123, 99, 10, -33, 75, 30, 88, 99}, 8, 2, 4)); } @Test - public void testEncodeBytesToBytes2() throws IOException { - thrown.expect(IllegalArgumentException.class); - Base64.encodeBytesToBytes(new byte[]{83, 10, 91, 67, 42, -1, 107, 62, 91, 67}, 8, 6, 26); + public void testEncodeBytesToBytes2() { + assertThrows(IllegalArgumentException.class, () -> + Base64.encodeBytesToBytes(new byte[]{83, 10, 91, 67, 42, -1, 107, 62, 91, 67}, 8, 6, 26)); } @Test @@ -129,6 +125,6 @@ public void testEncodeBytesToBytes3() throws IOException { 119, 61 }; - Assert.assertArrayEquals(excepted, Base64.encodeBytesToBytes(src, 0, 62, 8)); + assertArrayEquals(excepted, Base64.encodeBytesToBytes(src, 0, 62, 8)); } } diff --git a/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java b/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java index 40523418e..a694bac31 100644 --- a/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java +++ b/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java @@ -25,13 +25,11 @@ package org.java_websocket.util; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the new ByteBufferUtils class @@ -51,14 +49,14 @@ public class ByteBufferUtilsTest { @Test public void testEmptyByteBufferCapacity() { ByteBuffer byteBuffer = ByteBufferUtils.getEmptyByteBuffer(); - assertEquals("capacity must be 0", 0, byteBuffer.capacity()); + assertEquals( 0, byteBuffer.capacity(), "capacity must be 0"); } @Test public void testEmptyByteBufferNewObject() { ByteBuffer byteBuffer0 = ByteBufferUtils.getEmptyByteBuffer(); ByteBuffer byteBuffer1 = ByteBufferUtils.getEmptyByteBuffer(); - assertTrue("Allocated new object", byteBuffer0 != byteBuffer1); + assertNotSame(byteBuffer0, byteBuffer1, "Allocated new object"); } @Test @@ -66,8 +64,8 @@ public void testTransferByteBufferSmallToEmpty() { ByteBuffer small = ByteBuffer.wrap(smallArray); ByteBuffer empty = ByteBufferUtils.getEmptyByteBuffer(); ByteBufferUtils.transferByteBuffer(small, empty); - assertArrayEquals("Small bytebuffer should not change", smallArray, small.array()); - assertEquals("Capacity of the empty bytebuffer should still be 0", 0, empty.capacity()); + assertArrayEquals( smallArray, small.array(), "Small bytebuffer should not change"); + assertEquals( 0, empty.capacity(), "Capacity of the empty bytebuffer should still be 0"); } @Test @@ -75,16 +73,16 @@ public void testTransferByteBufferSmallToBig() { ByteBuffer small = ByteBuffer.wrap(smallArray); ByteBuffer big = ByteBuffer.wrap(bigArray); ByteBufferUtils.transferByteBuffer(small, big); - assertArrayEquals("Small bytebuffer should not change", smallArray, small.array()); - assertEquals("Big bytebuffer not same to source 0", smallArray[0], big.get(0)); - assertEquals("Big bytebuffer not same to source 1", smallArray[1], big.get(1)); - assertEquals("Big bytebuffer not same to source 2", smallArray[2], big.get(2)); - assertEquals("Big bytebuffer not same to source 3", smallArray[3], big.get(3)); - assertEquals("Big bytebuffer not same to source 4", smallArray[4], big.get(4)); - assertEquals("Big bytebuffer not same to source 5", bigArray[5], big.get(5)); - assertEquals("Big bytebuffer not same to source 6", bigArray[6], big.get(6)); - assertEquals("Big bytebuffer not same to source 7", bigArray[7], big.get(7)); - assertEquals("Big bytebuffer not same to source 8", bigArray[8], big.get(8)); + assertArrayEquals( smallArray, small.array(), "Small bytebuffer should not change"); + assertEquals( smallArray[0], big.get(0), "Big bytebuffer not same to source 0"); + assertEquals( smallArray[1], big.get(1), "Big bytebuffer not same to source 1"); + assertEquals( smallArray[2], big.get(2), "Big bytebuffer not same to source 2"); + assertEquals( smallArray[3], big.get(3), "Big bytebuffer not same to source 3"); + assertEquals( smallArray[4], big.get(4), "Big bytebuffer not same to source 4"); + assertEquals( bigArray[5], big.get(5), "Big bytebuffer not same to source 5"); + assertEquals( bigArray[6], big.get(6), "Big bytebuffer not same to source 6"); + assertEquals( bigArray[7], big.get(7), "Big bytebuffer not same to source 7"); + assertEquals( bigArray[8], big.get(8), "Big bytebuffer not same to source 8"); } @Test @@ -92,12 +90,12 @@ public void testTransferByteBufferBigToSmall() { ByteBuffer small = ByteBuffer.wrap(smallArray); ByteBuffer big = ByteBuffer.wrap(bigArray); ByteBufferUtils.transferByteBuffer(big, small); - assertArrayEquals("Big bytebuffer should not change", bigArray, big.array()); - assertEquals("Small bytebuffer not same to source 0", bigArray[0], small.get(0)); - assertEquals("Small bytebuffer not same to source 1", bigArray[1], small.get(1)); - assertEquals("Small bytebuffer not same to source 2", bigArray[2], small.get(2)); - assertEquals("Small bytebuffer not same to source 3", bigArray[3], small.get(3)); - assertEquals("Small bytebuffer not same to source 4", bigArray[4], small.get(4)); + assertArrayEquals( bigArray, big.array(), "Big bytebuffer should not change"); + assertEquals( bigArray[0], small.get(0), "Small bytebuffer not same to source 0"); + assertEquals( bigArray[1], small.get(1), "Small bytebuffer not same to source 1"); + assertEquals( bigArray[2], small.get(2), "Small bytebuffer not same to source 2"); + assertEquals( bigArray[3], small.get(3), "Small bytebuffer not same to source 3"); + assertEquals( bigArray[4], small.get(4), "Small bytebuffer not same to source 4"); } @Test diff --git a/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java b/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java index 4d8ef3ae9..1a7ed29e1 100644 --- a/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java +++ b/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java @@ -27,53 +27,54 @@ import java.nio.ByteBuffer; import org.java_websocket.exceptions.InvalidDataException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class CharsetfunctionsTest { @Test public void testAsciiBytes() { - Assert.assertArrayEquals(new byte[]{102, 111, 111}, Charsetfunctions.asciiBytes("foo")); + assertArrayEquals(new byte[]{102, 111, 111}, Charsetfunctions.asciiBytes("foo")); } @Test public void testStringUtf8ByteBuffer() throws InvalidDataException { - Assert.assertEquals("foo", + assertEquals("foo", Charsetfunctions.stringUtf8(ByteBuffer.wrap(new byte[]{102, 111, 111}))); } @Test public void testIsValidUTF8off() { - Assert.assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{100}), 2)); - Assert.assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{(byte) 128}), 0)); + assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{100}), 2)); + assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{(byte) 128}), 0)); - Assert.assertTrue(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{100}), 0)); + assertTrue(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{100}), 0)); } @Test public void testIsValidUTF8() { - Assert.assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{(byte) 128}))); + assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{(byte) 128}))); - Assert.assertTrue(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{100}))); + assertTrue(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{100}))); } @Test public void testStringAscii1() { - Assert.assertEquals("oBar", + assertEquals("oBar", Charsetfunctions.stringAscii(new byte[]{102, 111, 111, 66, 97, 114}, 2, 4)); } @Test public void testStringAscii2() { - Assert.assertEquals("foo", Charsetfunctions.stringAscii(new byte[]{102, 111, 111})); + assertEquals("foo", Charsetfunctions.stringAscii(new byte[]{102, 111, 111})); } @Test public void testUtf8Bytes() { - Assert.assertArrayEquals(new byte[]{102, 111, 111, 66, 97, 114}, + assertArrayEquals(new byte[]{102, 111, 111, 66, 97, 114}, Charsetfunctions.utf8Bytes("fooBar")); } } diff --git a/src/test/java/org/java_websocket/util/SocketUtil.java b/src/test/java/org/java_websocket/util/SocketUtil.java index e43c7fe3d..dd8d82a16 100644 --- a/src/test/java/org/java_websocket/util/SocketUtil.java +++ b/src/test/java/org/java_websocket/util/SocketUtil.java @@ -27,18 +27,40 @@ import java.io.IOException; import java.net.ServerSocket; +import java.net.Socket; public class SocketUtil { - public static int getAvailablePort() throws IOException { - ServerSocket srv = null; - try { - srv = new ServerSocket(0); - return srv.getLocalPort(); - } finally { - if (srv != null) { - srv.close(); - } + public static int getAvailablePort() throws InterruptedException { + while (true) { + try (ServerSocket srv = new ServerSocket(0)) { + return srv.getLocalPort(); + } catch (IOException e) { + // Retry + } + Thread.sleep(5); + } + } + public static boolean waitForServerToStart(int port) throws InterruptedException { + Socket socket = null; + for (int i = 0; i < 50; i++) { + try { + socket = new Socket("localhost", port); + if (socket.isConnected()) { + return true; + } + } catch (IOException ignore) { + // Ignore + } finally { + if (socket != null) { + try { + socket.close(); + } catch (IOException ignore) { + } + } + } + Thread.sleep(10); + } + return false; } - } } diff --git a/src/test/java/org/java_websocket/util/ThreadCheck.java b/src/test/java/org/java_websocket/util/ThreadCheck.java index 449a2b69d..208f8edcf 100644 --- a/src/test/java/org/java_websocket/util/ThreadCheck.java +++ b/src/test/java/org/java_websocket/util/ThreadCheck.java @@ -25,26 +25,33 @@ package org.java_websocket.util; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.Extension; +import org.junit.jupiter.api.extension.ExtensionContext; + import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.LockSupport; -import org.junit.Assert; -import org.junit.rules.ExternalResource; + +import static org.junit.jupiter.api.Assertions.fail; /** * Makes test fail if new threads are still alive after tear-down. */ -public class ThreadCheck extends ExternalResource { +public class ThreadCheck implements AfterEachCallback, BeforeEachCallback { private Map map = new HashMap(); @Override - protected void before() throws Throwable { + public void beforeEach(ExtensionContext context) throws Exception { map = getThreadMap(); } @Override - protected void after() { + public void afterEach(ExtensionContext context) throws Exception { long time = System.currentTimeMillis(); do { LockSupport.parkNanos(10000000); @@ -71,7 +78,7 @@ private boolean checkZombies(boolean testOnly) { } } if (zombies > 0 && !testOnly) { - Assert.fail("Found " + zombies + " zombie thread(s) "); + fail("Found " + zombies + " zombie thread(s) "); } return zombies > 0; @@ -82,7 +89,9 @@ public static Map getThreadMap() { Thread[] threads = new Thread[Thread.activeCount() * 2]; int actualNb = Thread.enumerate(threads); for (int i = 0; i < actualNb; i++) { - map.put(threads[i].getId(), threads[i]); + if (threads[i].getName().contains("WebSocket")) { + map.put(threads[i].getId(), threads[i]); + } } return map; } @@ -94,4 +103,6 @@ private static void appendStack(Thread th, StringBuilder s) { s.append(st[i]); } } + + } From d8688879a335ddef109024ad7e4187d01ab1028f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20P=C3=A9ter?= Date: Sun, 16 Feb 2025 22:19:34 +0100 Subject: [PATCH 163/165] Fix JUnit 5 config for gradle Fixes #1457 --- build.gradle | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 3c4723581..e6891cf02 100644 --- a/build.gradle +++ b/build.gradle @@ -37,5 +37,9 @@ publishing { dependencies { implementation group: 'org.slf4j', name: 'slf4j-api', version: '2.0.15' testImplementation group: 'org.slf4j', name: 'slf4j-simple', version: '2.0.15' - testImplementation group: 'org.junit', name: 'junit-bom', version: '5.11.4', ext: 'pom' + testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter', version: '5.11.4' +} + +test { + useJUnitPlatform() // This is required for JUnit 5 } From 611d8977d2e957fdbf8c62f40257b09ed602585e Mon Sep 17 00:00:00 2001 From: Yuval Roth Date: Sat, 19 Apr 2025 16:37:07 +0300 Subject: [PATCH 164/165] Added reconnectBlocking overload that supports timeout in WebSocketClient.java --- .../org/java_websocket/client/WebSocketClient.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 1ac2df071..45e0246cc 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -327,6 +327,20 @@ public boolean reconnectBlocking() throws InterruptedException { return connectBlocking(); } + /** + * Same as reconnect but blocks with a timeout until the websocket connected or failed + * to do so.
      + * + * @param timeout The connect timeout + * @param timeUnit The timeout time unit + * @return Returns whether it succeeded or not. + * @throws InterruptedException Thrown when the threads get interrupted + */ + public boolean reconnectBlocking(long timeout, TimeUnit timeUnit) throws InterruptedException { + reset(); + return connectBlocking(timeout, timeUnit); + } + /** * Reset everything relevant to allow a reconnect * From 3d8b96f48aeddc13e20c675328541b18a5321bdf Mon Sep 17 00:00:00 2001 From: Yuval Roth Date: Sat, 19 Apr 2025 17:12:27 +0300 Subject: [PATCH 165/165] Added since 1.6.1 in method doc --- src/main/java/org/java_websocket/client/WebSocketClient.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 45e0246cc..0e38326d3 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -335,6 +335,7 @@ public boolean reconnectBlocking() throws InterruptedException { * @param timeUnit The timeout time unit * @return Returns whether it succeeded or not. * @throws InterruptedException Thrown when the threads get interrupted + * @since 1.6.1 */ public boolean reconnectBlocking(long timeout, TimeUnit timeUnit) throws InterruptedException { reset();