diff --git a/.github/workflows/checkstyle.yml b/.github/workflows/checkstyle.yml index 8b74e7db5..197b3f3aa 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,11 @@ 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' + 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 7c81f7ff0..145292c6c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,26 +1,33 @@ name: Continuous Integration -on: [push] +on: [push, pull_request] 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' + distribution: 'temurin' + - name: Maven Version + run: mvn --version - name: Build run: mvn -DskipTests package --file pom.xml Test: runs-on: ubuntu-latest + timeout-minutes: 15 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' + distribution: 'temurin' + - name: Maven Version + run: mvn --version - name: Test run: mvn test --file pom.xml diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml new file mode 100644 index 000000000..538a5665b --- /dev/null +++ b/.github/workflows/sonar.yml @@ -0,0 +1,35 @@ +name: SonarQube +on: + push: + branches: + - master +jobs: + build: + name: SonarQube + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + - name: Set up JDK 17 + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'temurin' + - 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 -Dmaven.test.failure.ignore=true diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b62db7b9..6dfbb71ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,134 @@ # 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) + +#### 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) + +#### 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 + +* [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) + +#### 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 + +* [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 + +* [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,13 +137,15 @@ In this release 1 issue and 1 pull request were closed. +############################################################################### + ## Version Release 1.5.0 (2020/05/06) #### Breaking Changes 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). @@ -318,4 +449,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..75607d3a2 100644 --- a/README.markdown +++ b/README.markdown @@ -1,9 +1,7 @@ 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 @@ -15,8 +13,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 @@ -31,7 +29,7 @@ To use maven add this dependency to your pom.xml: org.java-websocket Java-WebSocket - 1.5.1 + 1.6.0 ``` @@ -42,7 +40,11 @@ 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.6.0" +``` +Or this option if you use gradle 7.0 and above. +```xml +implementation 'org.java-websocket:Java-WebSocket:1.6.0' ``` #### Logging @@ -76,14 +78,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 @@ -94,7 +96,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. @@ -111,7 +113,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 e18733fae..e6891cf02 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-publish' +} repositories { mavenLocal() @@ -9,35 +10,36 @@ repositories { } group = 'org.java-websocket' -version = '1.5.2-SNAPSHOT' -sourceCompatibility = 1.6 -targetCompatibility = 1.6 +version = '1.6.1-SNAPSHOT' +sourceCompatibility = 1.8 +targetCompatibility = 1.8 -configurations { - deployerJars +compileJava { + options.compilerArgs += ['-encoding', 'UTF-8'] } -configure(install.repositories.mavenInstaller) { - pom.version = project.version - pom.groupId = "org.java-websocket" - pom.artifactId = 'Java-WebSocket' +javadoc { + options.encoding = 'UTF-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.12' - testCompile group: 'org.json', name: 'json', version: '20180813' +publishing { + publications { + maven(MavenPublication) { + groupId = project.group + artifactId = 'Java-WebSocket' + version = project.version + + from components.java + } + } } +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.jupiter', name: 'junit-jupiter', version: '5.11.4' +} -//deploy to maven repository -//uploadArchives { -// repositories.mavenDeployer { -// configuration = configurations.deployerJars -// repository(url: repositoryUrl) { -// authentication(userName: repositoryUsername, password: repositoryPassword) -// } -// } -//} +test { + useJUnitPlatform() // This is required for JUnit 5 +} diff --git a/pom.xml b/pom.xml index 99f5c2701..fa2caa283 100644 --- a/pom.xml +++ b/pom.xml @@ -5,29 +5,32 @@ org.java-websocket Java-WebSocket jar - 1.5.2-SNAPSHOT + 1.6.1-SNAPSHOT Java-WebSocket A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket + 1.8 + 1.8 UTF-8 - 1.7.25 + 2.0.16 - 4.12 - 20180813 + 5.11.4 - 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 - 1.6.8 - + 3.3.0 + 3.5.0 + 3.4.1 + 3.2.1 + 1.6.13 + org.java-websocket:Java-WebSocket + marci4-github + https://sonarcloud.io @@ -56,16 +59,11 @@ test - junit - junit + org.junit + junit-bom ${junit.version} - test - - - org.json - json - ${org.json.version} - test + pom + import @@ -84,10 +82,12 @@ @@ -97,10 +97,32 @@ org.apache.maven.plugins maven-compiler-plugin ${maven.compiler.plugin.version} - - 1.7 - 1.7 - + + + default-compile + + compile + + + 8 + + + + + module-compile + compile + + compile + + + 9 + + ${project.basedir}/src/main/java9 + + true + + + org.apache.maven.plugins @@ -130,6 +152,10 @@ org.apache.maven.plugins maven-javadoc-plugin ${maven.javadoc.plugin.version} + + src/main/java + -Xdoclint:none + attach-javadocs @@ -156,6 +182,7 @@ + org.sonatype.plugins @@ -181,6 +208,7 @@ ${maven.checkstyle.plugin.version} google_checks.xml + **/module-info.java warning checkstyle-suppressions.xml checkstyle.suppressions.file @@ -223,7 +251,8 @@ true ossrh - true + false + https://oss.sonatype.org/ @@ -233,72 +262,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 + @@ -325,13 +291,8 @@ test - junit - junit - test - - - org.json - json + org.junit.jupiter + junit-jupiter test 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 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 +} 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/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 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 a6709f0aa..ae9ce1824 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 @@ -90,11 +90,30 @@ 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 */ 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 * @@ -126,7 +145,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) { @@ -182,20 +201,23 @@ protected void startConnectionLostTimer() { private void restartConnectionLostTimer() { cancelConnectionLostTimer(); connectionLostCheckerService = Executors - .newSingleThreadScheduledExecutor(new NamedThreadFactory("connectionLostChecker")); + .newSingleThreadScheduledExecutor(new NamedThreadFactory("WebSocketConnectionLostChecker", daemon)); Runnable connectionLostChecker = new Runnable() { /** * 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); } @@ -305,4 +327,50 @@ 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; + } + + /** + * 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/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. * diff --git a/src/main/java/org/java_websocket/SSLSocketChannel2.java b/src/main/java/org/java_websocket/SSLSocketChannel2.java index d9b9a4c31..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; } @@ -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() { 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(); 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/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index 2fc312e64..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 * @@ -190,7 +185,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 +203,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) { @@ -224,10 +219,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); @@ -410,6 +406,15 @@ 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); + wsl.onWebsocketError(this, exception); + String errorMessage = "Got error " + e.getClass().getName(); + close(CloseFrame.UNEXPECTED_CONDITION, errorMessage); } } @@ -666,7 +671,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)); @@ -752,6 +757,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/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/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 992eb9670..0e38326d3 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; @@ -43,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; @@ -223,7 +224,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 +270,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); } @@ -326,6 +327,21 @@ 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 + * @since 1.6.1 + */ + public boolean reconnectBlocking(long timeout, TimeUnit timeUnit) throws InterruptedException { + reset(); + return connectBlocking(timeout, timeUnit); + } + /** * Reset everything relevant to allow a reconnect * @@ -338,13 +354,21 @@ private void reset() { "You cannot initialize a reconnect out of the websocket thread. Use reconnect in another thread to ensure a successful cleanup."); } try { + // 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(); + 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(); @@ -370,6 +394,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(); } @@ -397,7 +422,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(); } /** @@ -461,30 +492,23 @@ public void 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(); - } + boolean upgradeSocketToSSLSocket = prepareSocket(); socket.setTcpNoDelay(isTcpNoDelay()); socket.setReuseAddress(isReuseAddr()); + int receiveBufferSize = getReceiveBufferSize(); + if (receiveBufferSize > 0) { + socket.setReceiveBufferSize(receiveBufferSize); + } 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); } // 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 (upgradeSocketToSSLSocket && "wss".equals(uri.getScheme())) { + upgradeSocketToSSL(); } if (socket instanceof SSLSocket) { @@ -514,10 +538,20 @@ public void run() { throw e; } + if (writeThread != null) { + writeThread.interrupt(); + try { + writeThread.join(); + } catch (InterruptedException e) { + /* ignore */ + } + } writeThread = new Thread(new WebsocketWriteThread(this)); + 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 { @@ -532,7 +566,36 @@ public void run() { onError(e); engine.closeConnection(CloseFrame.ABNORMAL_CLOSE, e.getMessage()); } - 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 { + factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); + } + 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; } /** @@ -778,7 +841,6 @@ public void run() { handleIOException(e); } finally { closeSocket(); - writeThread = null; } } @@ -932,12 +994,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/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/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index f7e59fc41..eb4879976 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; @@ -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 */ @@ -150,7 +160,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 @@ -229,10 +239,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; @@ -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; } /** @@ -442,13 +453,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); } @@ -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" @@ -700,7 +723,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 @@ -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/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..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 @@ -44,55 +42,99 @@ 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; // 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 final int compressionLevel; + + private final Inflater inflater; + private final Deflater deflater; - private Inflater inflater = new Inflater(true); - private Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); + /** + * 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); + } - public Inflater getInflater() { - return inflater; + /** + * 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 PerMessageDeflateExtension(int compressionLevel) { + this.compressionLevel = compressionLevel; + this.deflater = new Deflater(this.compressionLevel, true); + this.inflater = new Inflater(true); } - public void setInflater(Inflater inflater) { - this.inflater = inflater; + /** + * Get the compression level used for the compressor. + * @return the compression level + */ + public int getCompressionLevel() { + return this.compressionLevel; } - public Deflater getDeflater() { - return 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; } - public void setDeflater(Deflater deflater) { - this.deflater = deflater; + /** + * 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; } /** - * @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; @@ -112,6 +154,10 @@ 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, @@ -132,7 +178,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); } @@ -140,18 +186,13 @@ 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) { 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())); @@ -180,12 +221,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. @@ -211,8 +256,7 @@ public void encodeFrame(Framedata inputFrame) { } if (serverNoContextTakeover) { - deflater.end(); - deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); + deflater.reset(); } } @@ -224,7 +268,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; } @@ -297,7 +341,11 @@ public String getProvidedExtensionAsServer() { @Override public IExtension copyInstance() { - return new PerMessageDeflateExtension(); + PerMessageDeflateExtension clone = new PerMessageDeflateExtension(this.getCompressionLevel()); + clone.setThreshold(this.getThreshold()); + clone.setClientNoContextTakeover(this.isClientNoContextTakeover()); + clone.setServerNoContextTakeover(this.isServerNoContextTakeover()); + return clone; } /** @@ -306,10 +354,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( @@ -323,4 +367,6 @@ public void isFrameValid(Framedata inputFrame) throws InvalidDataException { public String toString() { return "PerMessageDeflateExtension"; } + + } 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..8d11bcf48 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. */ @@ -181,9 +181,33 @@ 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. + * 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 @@ -221,10 +245,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); @@ -245,7 +269,13 @@ 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 { + stop(timeout, ""); } /** @@ -257,10 +287,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; @@ -270,11 +301,11 @@ 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) { - ws.close(CloseFrame.GOING_AWAY); + ws.close(CloseFrame.GOING_AWAY, closeMessage); } wsf.close(); @@ -287,7 +318,7 @@ public void stop(int timeout) throws InterruptedException { } } - public void stop() throws IOException, InterruptedException { + public void stop() throws InterruptedException { stop(0); } @@ -300,7 +331,7 @@ public void stop() throws IOException, InterruptedException { */ public Collection getConnections() { synchronized (connections) { - return Collections.unmodifiableCollection(new ArrayList(connections)); + return Collections.unmodifiableCollection(new ArrayList<>(connections)); } } @@ -321,6 +352,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 * @@ -337,6 +382,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 +393,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; @@ -536,10 +583,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); @@ -554,12 +599,22 @@ 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(); - socket.setReceiveBufferSize(WebSocketImpl.RCVBUF); + int receiveBufferSize = getReceiveBufferSize(); + if (receiveBufferSize > 0) { + 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(); @@ -634,7 +689,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 { @@ -680,6 +736,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,16 +756,6 @@ private void handleFatal(WebSocket conn, Exception e) { 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 @@ -866,7 +923,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); @@ -874,7 +931,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 @@ -885,7 +942,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) **/ @@ -913,7 +970,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) **/ @@ -1004,10 +1061,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 +1111,7 @@ public class WebSocketWorker extends Thread { private BlockingQueue iqueue; public WebSocketWorker() { - iqueue = new LinkedBlockingQueue(); + iqueue = new LinkedBlockingQueue<>(); setName("WebSocketWorker-" + getId()); setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override @@ -1082,8 +1139,17 @@ public void run() { } } catch (InterruptedException e) { Thread.currentThread().interrupt(); - } catch (RuntimeException e) { - handleFatal(ws, e); + } catch (VirtualMachineError | ThreadDeath | LinkageError e) { + log.error("Got fatal error in worker thread {}", getName()); + 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); + onWebsocketError(ws, exception); + ws.close(); + } } } 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 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/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; +} 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/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); - } -} 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 new file mode 100644 index 000000000..bb4741043 --- /dev/null +++ b/src/test/java/org/java_websocket/client/ConnectBlockingTest.java @@ -0,0 +1,78 @@ +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.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 { + + 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(); + + 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( 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(); + + 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/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 0f6bc84df..b0b9bc847 100644 --- a/src/test/java/org/java_websocket/example/AutobahnServerTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnServerTest.java @@ -90,19 +90,21 @@ 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; } + 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/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 624748318..5a86648f3 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -1,25 +1,23 @@ 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; -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; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; 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 +27,103 @@ 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 testDecodeFrameNoCompression() throws InvalidDataException { + PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(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(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(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 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 +135,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 +179,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 { @@ -154,35 +260,45 @@ 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()); + assertEquals(deflateExtension.getCompressionLevel(), newDeflateExtension.getCompressionLevel()); - @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()); - } + deflateExtension = new PerMessageDeflateExtension(Deflater.BEST_COMPRESSION); + deflateExtension.setThreshold(512); + deflateExtension.setServerNoContextTakeover(false); + deflateExtension.setClientNoContextTakeover(true); + newDeflateExtension = (PerMessageDeflateExtension)deflateExtension.copyInstance(); - @Test - public void testGetDeflater() { - PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - assertEquals(deflateExtension.getDeflater().finished(), - new Deflater(Deflater.DEFAULT_COMPRESSION, true).finished()); + assertEquals(deflateExtension.getThreshold(), newDeflateExtension.getThreshold()); + assertEquals(deflateExtension.isClientNoContextTakeover(), newDeflateExtension.isClientNoContextTakeover()); + assertEquals(deflateExtension.isServerNoContextTakeover(), newDeflateExtension.isServerNoContextTakeover()); + assertEquals(deflateExtension.getCompressionLevel(), newDeflateExtension.getCompressionLevel()); + + + deflateExtension = new PerMessageDeflateExtension(Deflater.NO_COMPRESSION); + 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()); + assertEquals(deflateExtension.getCompressionLevel(), newDeflateExtension.getCompressionLevel()); } @Test - public void testSetDeflater() { + public void testDefaults() { PerMessageDeflateExtension deflateExtension = new PerMessageDeflateExtension(); - deflateExtension.setDeflater(new Deflater(Deflater.DEFAULT_COMPRESSION, false)); - assertEquals(deflateExtension.getDeflater().finished(), - new Deflater(Deflater.DEFAULT_COMPRESSION, false).finished()); + assertFalse(deflateExtension.isClientNoContextTakeover()); + assertTrue(deflateExtension.isServerNoContextTakeover()); + assertEquals(1024, deflateExtension.getThreshold()); + assertEquals(Deflater.DEFAULT_COMPRESSION, deflateExtension.getCompressionLevel()); } } 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 new file mode 100644 index 000000000..38ff93e4d --- /dev/null +++ b/src/test/java/org/java_websocket/issues/Issue1142Test.java @@ -0,0 +1,139 @@ +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; +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.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.*; + +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(); + } + } +} 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..57983cdea --- /dev/null +++ b/src/test/java/org/java_websocket/issues/Issue1160Test.java @@ -0,0 +1,165 @@ +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.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.net.InetSocketAddress; +import java.net.URI; +import java.nio.ByteBuffer; +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); + + 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(); + } + + 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 intentional 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(); + 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 new file mode 100644 index 000000000..45c4cd593 --- /dev/null +++ b/src/test/java/org/java_websocket/issues/Issue1203Test.java @@ -0,0 +1,96 @@ +package org.java_websocket.issues; + + +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.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) + 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); + 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 d35fed8a3..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,15 +114,21 @@ public void onStart() { server.start(); countServerDownLatch.await(); webSocket0.connectBlocking(); - assertTrue("webSocket.isOpen()", webSocket0.isOpen()); + assertTrue(webSocket0.isOpen(), "webSocket.isOpen()"); webSocket0.close(); - assertTrue("webSocket.isClosing()", webSocket0.isClosing()); 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 ae403d7ba..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, - 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 deleted file mode 100644 index 270fab805..000000000 --- a/src/test/java/org/java_websocket/protocols/ProtoclHandshakeRejectionTest.java +++ /dev/null @@ -1,618 +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 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; -import java.net.Socket; -import java.net.URI; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Scanner; -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 { - - 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/ProtocolHandshakeRejectionTest.java b/src/test/java/org/java_websocket/protocols/ProtocolHandshakeRejectionTest.java new file mode 100644 index 000000000..c8c1d69e3 --- /dev/null +++ b/src/test/java/org/java_websocket/protocols/ProtocolHandshakeRejectionTest.java @@ -0,0 +1,665 @@ +/* + * 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 java.io.IOException; +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.URI; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +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; +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.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 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); + } + }); + 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; + } + } + 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(); + } + } + + }); + finalThread.start(); + finalThread.join(); + if (exc[0] != null) { + throw exc[0]; + } + + 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 { + 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 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 9f7683552..000000000 --- a/src/test/java/org/java_websocket/server/AllServerTests.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.server; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - 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 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 new file mode 100644 index 000000000..9047a97da --- /dev/null +++ b/src/test/java/org/java_websocket/server/DaemonThreadTest.java @@ -0,0 +1,79 @@ +package org.java_websocket.server; + +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.util.SocketUtil; +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 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 + 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() {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 + 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); + + assertFalse(threadSet2.isEmpty(), "new threads created (no new threads indicates issue in test)"); + + for (Thread t : threadSet2) + assertTrue(t.isDaemon(), t.getName()); + + boolean exception = false; + try { + server.setDaemon(false); + } catch(IllegalStateException e) { + exception = true; + } + 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 decac6c28..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); @@ -142,6 +141,14 @@ public void testGetPort() throws IOException, InterruptedException { assertNotEquals(0, server.getPort()); } + @Test + public void testMaxPendingConnections() { + MyWebSocketServer server = new MyWebSocketServer(1337); + assertEquals(-1, server.getMaxPendingConnections()); + server.setMaxPendingConnections(10); + assertEquals(10, server.getMaxPendingConnections()); + } + @Test public void testBroadcast() { MyWebSocketServer server = new MyWebSocketServer(1337); diff --git a/src/test/java/org/java_websocket/util/Base64Test.java b/src/test/java/org/java_websocket/util/Base64Test.java index 41122d779..0d546db50 100644 --- a/src/test/java/org/java_websocket/util/Base64Test.java +++ b/src/test/java/org/java_websocket/util/Base64Test.java @@ -25,79 +25,81 @@ 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)); - 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=", + 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) { + 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 @@ -123,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]); } } + + }