From 042c71886f712ff491944049f81c31dee857be50 Mon Sep 17 00:00:00 2001 From: Alexander Zagniotov Date: Tue, 23 Jan 2024 22:48:57 -0800 Subject: [PATCH] Added Spotless Gradle plugin and adopted Apache v2.0 license (#493) --- ...alexander.zagniotov-apache-2.0-license.txt | 16 + LICENSE | 222 +- build.gradle | 5 + conf/gradle/spotless.gradle | 18 + .../azagniotov/stubby4j/AdminPortalTest.java | 106 +- .../azagniotov/stubby4j/HttpClientUtils.java | 59 +- .../github/azagniotov/stubby4j/HttpUtils.java | 42 +- .../stubby4j/ProxyConfigWithStubsTest.java | 174 +- .../stubby4j/StubsAdminPortalsTest.java | 169 +- .../StubsPortalHttp11OverTlsTests.java | 48 +- ...tubsPortalHttp11WebSocketOverTlsTests.java | 125 +- .../StubsPortalHttp11WebSocketTests.java | 164 +- .../StubsPortalHttp20ClearTextTests.java | 66 +- ...talHttp20OverTlsWithAlpnProtocolTests.java | 85 +- .../stubby4j/StubsPortalRaisedIssueTests.java | 120 +- .../azagniotov/stubby4j/StubsPortalTest.java | 281 ++- .../stubby4j/client/StubbyClientTest.java | 170 +- .../client/StubbyClientYamlessTest.java | 37 +- .../cli/CommandLineInterpreterTest.java | 144 +- .../stubby4j/parser/json/JSONAssertTest.java | 16 + .../ssl/CustomHostnameVerifierTest.java | 29 +- .../stubby4j/server/ssl/SslUtilsTest.java | 23 +- .../stubby4j/stubs/StubRepositoryTest.java | 566 +++-- .../stubby4j/utils/ConsoleUtilsTest.java | 50 +- .../stubby4j/utils/HandlerUtilsTest.java | 23 +- .../stubby4j/utils/JarUtilsTest.java | 23 +- .../stubby4j/yaml/YamlParserLoadTest.java | 33 +- .../stubby4j/yaml/YamlParserTest.java | 796 ++++--- .../github/azagniotov/stubby4j/HttpUtils.java | 41 +- .../azagniotov/stubby4j/PortTestUtils.java | 20 +- .../stubby4j/SpringSocketUtils.java | 32 +- .../stubby4j/StubsPortalLoadTest.java | 59 +- .../io/github/azagniotov/stubby4j/Main.java | 77 +- .../GeneratedCodeClassCoverageExclusion.java | 20 +- .../GeneratedCodeMethodCoverageExclusion.java | 20 +- .../annotations/PotentiallyFlaky.java | 17 +- .../annotations/VisibleForTesting.java | 19 +- .../azagniotov/stubby4j/caching/Cache.java | 22 +- .../caching/NoOpStubHttpLifecycleCache.java | 24 +- .../stubby4j/caching/RegexPatternCache.java | 27 +- .../caching/StubHttpLifecycleCache.java | 25 +- .../azagniotov/stubby4j/cli/ANSITerminal.java | 20 +- .../stubby4j/cli/CommandLineInterpreter.java | 100 +- .../azagniotov/stubby4j/cli/EmptyLogger.java | 53 +- .../stubby4j/client/Authorization.java | 17 +- .../stubby4j/client/StubbyClient.java | 335 ++- .../stubby4j/client/StubbyRequest.java | 49 +- .../stubby4j/client/StubbyResponse.java | 22 +- .../azagniotov/stubby4j/common/Common.java | 37 +- .../filesystem/ExternalFilesScanner.java | 51 +- .../filesystem/MainIncludedYamlScanner.java | 56 +- .../stubby4j/filesystem/MainYamlScanner.java | 47 +- .../handlers/AbstractHandlerExtension.java | 31 +- .../stubby4j/handlers/AdminPortalHandler.java | 42 +- .../handlers/AjaxEndpointStatsHandler.java | 36 +- .../handlers/AjaxResourceContentHandler.java | 81 +- .../stubby4j/handlers/FaviconHandler.java | 45 +- .../stubby4j/handlers/JsonErrorHandler.java | 66 +- .../stubby4j/handlers/StatusPageHandler.java | 197 +- .../StubDataRefreshActionHandler.java | 38 +- .../stubby4j/handlers/StubsPortalHandler.java | 39 +- .../admin/AdminResponseHandlingStrategy.java | 41 +- .../AdminResponseHandlingStrategyFactory.java | 20 +- .../admin/DeleteHandlingStrategy.java | 52 +- .../strategy/admin/GetHandlingStrategy.java | 40 +- .../strategy/admin/HttpVerbsEnum.java | 17 +- .../strategy/admin/NullHandlingStrategy.java | 30 +- .../strategy/admin/PostHandlingStrategy.java | 29 +- .../strategy/admin/PutHandlingStrategy.java | 60 +- .../DefaultResponseHandlingStrategy.java | 43 +- .../NotFoundResponseHandlingStrategy.java | 27 +- .../RedirectResponseHandlingStrategy.java | 27 +- .../stubs/StubResponseHandlingStrategy.java | 17 +- .../StubsResponseHandlingStrategyFactory.java | 42 +- .../UnauthorizedResponseHandlingStrategy.java | 36 +- .../stubby4j/http/HttpMethodExtended.java | 21 +- .../stubby4j/http/StubbyHttpTransport.java | 111 +- .../stubby4j/server/JettyContext.java | 16 + .../stubby4j/server/JettyFactory.java | 229 +- .../stubby4j/server/StubbyManager.java | 31 +- .../stubby4j/server/StubbyManagerFactory.java | 41 +- .../server/ssl/CustomHostnameVerifier.java | 17 +- .../ssl/DefaultExtendedX509TrustManager.java | 46 +- .../stubby4j/server/ssl/LanIPv4Validator.java | 24 +- .../stubby4j/server/ssl/SslUtils.java | 98 +- .../websocket/StubsServerWebSocket.java | 178 +- .../websocket/StubsWebSocketCreator.java | 44 +- .../stubby4j/stubs/AbstractBuilder.java | 20 +- .../stubby4j/stubs/ReflectableStub.java | 20 +- .../stubby4j/stubs/RegexParser.java | 47 +- .../stubby4j/stubs/StubHttpLifecycle.java | 36 +- .../stubby4j/stubs/StubMatcher.java | 111 +- .../stubby4j/stubs/StubRepository.java | 167 +- .../stubby4j/stubs/StubRequest.java | 87 +- .../stubby4j/stubs/StubResponse.java | 53 +- .../stubby4j/stubs/StubSearchResult.java | 17 +- .../azagniotov/stubby4j/stubs/StubTypes.java | 16 + .../stubs/StubbableAuthorizationType.java | 17 +- ...tubby4jMatchesRegexPlaceholderHandler.java | 43 +- ...XmlUnitPlaceholderDifferenceEvaluator.java | 102 +- .../stubby4j/stubs/proxy/StubProxyConfig.java | 68 +- .../stubs/proxy/StubProxyStrategy.java | 20 +- .../websocket/StubWebSocketClientRequest.java | 55 +- .../stubs/websocket/StubWebSocketConfig.java | 61 +- .../websocket/StubWebSocketMessageType.java | 21 +- .../StubWebSocketOnMessageLifeCycle.java | 17 +- .../StubWebSocketServerResponse.java | 58 +- .../StubWebSocketServerResponsePolicy.java | 24 +- .../stubby4j/utils/CollectionUtils.java | 28 +- .../stubby4j/utils/ConsoleUtils.java | 109 +- .../stubby4j/utils/DateTimeUtils.java | 21 +- .../azagniotov/stubby4j/utils/FileUtils.java | 157 +- .../stubby4j/utils/HandlerUtils.java | 63 +- .../stubby4j/utils/HttpRequestUtils.java | 108 +- .../azagniotov/stubby4j/utils/JarUtils.java | 27 +- .../stubby4j/utils/NetworkPortUtils.java | 25 +- .../stubby4j/utils/ObjectUtils.java | 21 +- .../stubby4j/utils/ReflectionUtils.java | 40 +- .../stubby4j/utils/SpringSocketUtils.java | 33 +- .../stubby4j/utils/StringUtils.java | 46 +- .../yaml/ConfigurableYAMLProperty.java | 21 +- .../azagniotov/stubby4j/yaml/SnakeYaml.java | 24 +- .../azagniotov/stubby4j/yaml/YamlBuilder.java | 177 +- .../stubby4j/yaml/YamlParseResultSet.java | 36 +- .../azagniotov/stubby4j/yaml/YamlParser.java | 268 ++- .../stubby4j/caching/CacheTest.java | 23 +- .../NoOpStubHttpLifecycleCacheTest.java | 27 +- .../cli/CommandLineInterpreterTest.java | 188 +- .../AbstractHandlerExtensionTest.java | 52 +- .../AjaxResourceContentHandlerTest.java | 240 +- .../handlers/StubsPortalHandlerTest.java | 68 +- .../DefaultResponseHandlingStrategyTest.java | 74 +- .../strategy/HandlingStrategyFactoryTest.java | 58 +- .../RedirectResponseHandlingStrategyTest.java | 78 +- ...bsResponseHandlingStrategyFactoryTest.java | 28 +- .../server/ssl/LanIPv4ValidatorTest.java | 22 +- .../websocket/StubsServerWebSocketTest.java | 124 +- .../stubby4j/stubs/RegexParserTest.java | 101 +- .../stubs/StubHttpLifecycleBuilderTest.java | 306 ++- .../stubby4j/stubs/StubMatcherTest.java | 694 +++--- .../stubs/StubProxyConfigBuilderTest.java | 93 +- .../stubby4j/stubs/StubRepositoryTest.java | 977 +++++--- .../stubs/StubRequestBuilderTest.java | 1976 +++++++++-------- .../stubs/StubResponseBuilderTest.java | 80 +- .../StubWebSocketClientRequestTest.java | 45 +- .../StubWebSocketMessageTypeTest.java | 22 +- ...StubWebSocketServerResponsePolicyTest.java | 28 +- .../StubWebSocketServerResponseTest.java | 49 +- .../stubby4j/utils/CollectionUtilsTest.java | 159 +- .../stubby4j/utils/DateTimeUtilsTest.java | 26 +- .../stubby4j/utils/FileUtilsTest.java | 19 +- .../stubby4j/utils/HandlerUtilsTest.java | 61 +- .../stubby4j/utils/ReflectionUtilsTest.java | 47 +- .../stubby4j/utils/StringUtilsTest.java | 91 +- .../stubby4j/yaml/YamlBuilderTest.java | 351 ++- .../stubby4j/yaml/YamlParserTest.java | 23 +- 156 files changed, 9574 insertions(+), 5532 deletions(-) create mode 100644 .spotless/alexander.zagniotov-apache-2.0-license.txt create mode 100644 conf/gradle/spotless.gradle diff --git a/.spotless/alexander.zagniotov-apache-2.0-license.txt b/.spotless/alexander.zagniotov-apache-2.0-license.txt new file mode 100644 index 000000000..459903621 --- /dev/null +++ b/.spotless/alexander.zagniotov-apache-2.0-license.txt @@ -0,0 +1,16 @@ +/* + * Copyright (c) $YEAR Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + diff --git a/LICENSE b/LICENSE index 92055be19..261eeb9e9 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,201 @@ -MIT License - -Copyright (c) 2012 - 2022 Alexander Zagniotov - -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. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/build.gradle b/build.gradle index 45f802089..c9c0d97d1 100644 --- a/build.gradle +++ b/build.gradle @@ -9,6 +9,10 @@ buildscript { } } } + dependencies { + // From v6.14.0 (inc.) Java 8 support is dropped + classpath("com.diffplug.spotless:spotless-plugin-gradle:6.13.0") + } } apply plugin: "java-library" @@ -48,3 +52,4 @@ apply from: "$rootDir/conf/gradle/tests.gradle" apply from: "$rootDir/conf/gradle/jacoco.gradle" apply from: "$rootDir/conf/gradle/artifacts.gradle" apply from: "$rootDir/conf/gradle/sonatype.gradle" +apply from: "$rootDir/conf/gradle/spotless.gradle" diff --git a/conf/gradle/spotless.gradle b/conf/gradle/spotless.gradle new file mode 100644 index 000000000..3638e0b23 --- /dev/null +++ b/conf/gradle/spotless.gradle @@ -0,0 +1,18 @@ +apply plugin: "com.diffplug.spotless" + +spotless { + java { + // ratchetFrom "origin/master" // only format files which have changed since origin/master + + target "src/**/*.java" + + importOrder() + removeUnusedImports() + palantirJavaFormat() + + licenseHeaderFile(rootProject.file(".spotless/alexander.zagniotov-apache-2.0-license.txt")). + named("alexander.zagniotov"). + updateYearWithLatest(true) + } +} + diff --git a/src/functionalTest/java/io/github/azagniotov/stubby4j/AdminPortalTest.java b/src/functionalTest/java/io/github/azagniotov/stubby4j/AdminPortalTest.java index a5adcd1c3..b96e95d63 100644 --- a/src/functionalTest/java/io/github/azagniotov/stubby4j/AdminPortalTest.java +++ b/src/functionalTest/java/io/github/azagniotov/stubby4j/AdminPortalTest.java @@ -1,5 +1,23 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; +import static com.google.common.truth.Truth.assertThat; + import com.google.api.client.http.HttpMethods; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; @@ -9,17 +27,14 @@ import io.github.azagniotov.stubby4j.utils.NetworkPortUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; import io.github.azagniotov.stubby4j.yaml.YamlBuilder; +import java.io.InputStream; +import java.net.URL; import org.eclipse.jetty.http.HttpStatus; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import java.io.InputStream; -import java.net.URL; - -import static com.google.common.truth.Truth.assertThat; - public class AdminPortalTest { private static final int STUBS_PORT = NetworkPortUtils.findAvailableTcpPort(); @@ -134,7 +149,8 @@ public void should_ReturnCompleteYAMLConfig_WhenSuccessfulGetMade_ToAdminPortalR } @Test - public void should_ReturnSingleStubbedRequestAsYAML_WhenSuccessfulGetMade_ToAdminPortalRootWithValidIndexURI() throws Exception { + public void should_ReturnSingleStubbedRequestAsYAML_WhenSuccessfulGetMade_ToAdminPortalRootWithValidIndexURI() + throws Exception { final String requestUrl = String.format("%s%s", ADMIN_URL, "/0"); final HttpRequest httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); @@ -150,7 +166,8 @@ public void should_ReturnSingleStubbedRequestAsYAML_WhenSuccessfulGetMade_ToAdmi } @Test - public void should_ReturnExpectedError_WhenSuccessfulGetMade_ToAdminPortalRootWithInvalidIndexURI() throws Exception { + public void should_ReturnExpectedError_WhenSuccessfulGetMade_ToAdminPortalRootWithInvalidIndexURI() + throws Exception { final int invalidIndex = 88888888; final String requestUrl = String.format("%s/%s", ADMIN_URL, invalidIndex); @@ -161,7 +178,8 @@ public void should_ReturnExpectedError_WhenSuccessfulGetMade_ToAdminPortalRootWi } @Test - public void should_ReturnExpectedError_WhenSuccessfulGetMade_ToAdminPortalRootWithNonExistentUuid() throws Exception { + public void should_ReturnExpectedError_WhenSuccessfulGetMade_ToAdminPortalRootWithNonExistentUuid() + throws Exception { final String nonExistentUuid = "kshdfsdy894kwbkf"; final String requestUrl = String.format("%s/%s", ADMIN_URL, nonExistentUuid); @@ -183,11 +201,12 @@ public void should_ReturnExpectedError_WhenSuccessfulPutMade_ToAdminPortalRoot() assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.METHOD_NOT_ALLOWED_405); assertThat(statusMessage).isEqualTo("Method Not Allowed"); - //assertThat(responseMessage).isEqualTo("Method PUT is not allowed on URI /"); + // assertThat(responseMessage).isEqualTo("Method PUT is not allowed on URI /"); } @Test - public void should_ReturnExpectedError_WhenSuccessfulEmptyPutMade_ToAdminPortalRootWithValidIndexURI() throws Exception { + public void should_ReturnExpectedError_WhenSuccessfulEmptyPutMade_ToAdminPortalRootWithValidIndexURI() + throws Exception { final String requestUrl = String.format("%s/1", ADMIN_URL); final HttpRequest httpPuttRequest = HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl); @@ -197,7 +216,8 @@ public void should_ReturnExpectedError_WhenSuccessfulEmptyPutMade_ToAdminPortalR } @Test - public void should_ReturnExpectedError_WhenSuccessfulEmptyPutMade_ToAdminPortalRootWithValidUuid() throws Exception { + public void should_ReturnExpectedError_WhenSuccessfulEmptyPutMade_ToAdminPortalRootWithValidUuid() + throws Exception { final String uuid = "9136d8b7-f7a7-478d-97a5-53292484aaf6"; @@ -209,7 +229,8 @@ public void should_ReturnExpectedError_WhenSuccessfulEmptyPutMade_ToAdminPortalR } @Test - public void should_ReturnExpectedError_WhenSuccessfulPutMade_ToAdminPortalRootWithInvalidIndexURI() throws Exception { + public void should_ReturnExpectedError_WhenSuccessfulPutMade_ToAdminPortalRootWithInvalidIndexURI() + throws Exception { final int invalidIndex = 88888888; final String requestUrl = String.format("%s/%s", ADMIN_URL, invalidIndex); @@ -220,7 +241,8 @@ public void should_ReturnExpectedError_WhenSuccessfulPutMade_ToAdminPortalRootWi } @Test - public void should_ReturnExpectedError_WhenSuccessfulPutMade_ToAdminPortalRootWithNonExistentUuid() throws Exception { + public void should_ReturnExpectedError_WhenSuccessfulPutMade_ToAdminPortalRootWithNonExistentUuid() + throws Exception { final String nonExistentUuid = "fdsfsdfsd07f9sd7"; final String requestUrl = String.format("%s/%s", ADMIN_URL, nonExistentUuid); @@ -232,7 +254,8 @@ public void should_ReturnExpectedError_WhenSuccessfulPutMade_ToAdminPortalRootWi } @Test - public void should_UpdateStubbedRequest_WhenSuccessfulPutMade_ToAdminPortalRootWithValidIndexURI() throws Exception { + public void should_UpdateStubbedRequest_WhenSuccessfulPutMade_ToAdminPortalRootWithValidIndexURI() + throws Exception { final String requestUrl = String.format("%s%s", ADMIN_URL, "/0"); HttpRequest httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); @@ -266,7 +289,6 @@ public void should_UpdateStubbedRequest_WhenSuccessfulPutMade_ToAdminPortalRootW assertThat(putResponseLocationHeader).isEqualTo("^/resources/something/new?someKey=someValue"); assertThat(putResponseContent).isEqualTo("Stub request index#0 updated successfully"); - httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); httpGetResponse = httpGetRequest.execute(); getResponseContent = httpGetResponse.parseAsString().trim(); @@ -409,7 +431,6 @@ public void should_UpdateStubbedRequest_WithJsonRequest_ToAdminPortalRootWithVal assertThat(putResponseLocationHeader).isEqualTo("^/resources/something/new?someKey=someValue"); assertThat(putResponseContent).isEqualTo("Stub request index#0 updated successfully"); - httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); httpGetResponse = httpGetRequest.execute(); getResponseContent = httpGetResponse.parseAsString().trim(); @@ -426,7 +447,9 @@ public void should_UpdateStubbedRequest_WithJsonRequest_ToAdminPortalRootWithVal } @Test - public void should_UpdateStubbedRequest_WithEnquotedForwardSlashesEscapedJsonRequest_ToAdminPortalRootWithValidIndexURI() throws Exception { + public void + should_UpdateStubbedRequest_WithEnquotedForwardSlashesEscapedJsonRequest_ToAdminPortalRootWithValidIndexURI() + throws Exception { final String requestUrl = String.format("%s%s", ADMIN_URL, "/0"); HttpRequest httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); @@ -443,7 +466,8 @@ public void should_UpdateStubbedRequest_WithEnquotedForwardSlashesEscapedJsonReq final InputStream jsonInputStream = url.openStream(); final String escapedJsonToUpdate = StringUtils.inputStreamToString(jsonInputStream); - final HttpRequest httpPutRequest = HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl, escapedJsonToUpdate); + final HttpRequest httpPutRequest = + HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl, escapedJsonToUpdate); final HttpResponse httpPutResponse = httpPutRequest.execute(); final String putResponseContent = httpPutResponse.parseAsString().trim(); @@ -453,7 +477,6 @@ public void should_UpdateStubbedRequest_WithEnquotedForwardSlashesEscapedJsonReq assertThat(putResponseLocationHeader).isEqualTo("^/resources/something/new?someKey=someValue"); assertThat(putResponseContent).isEqualTo("Stub request index#0 updated successfully"); - httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); httpGetResponse = httpGetRequest.execute(); getResponseContent = httpGetResponse.parseAsString().trim(); @@ -470,7 +493,8 @@ public void should_UpdateStubbedRequest_WithEnquotedForwardSlashesEscapedJsonReq } @Test - public void should_UpdateStubbedRequest_WithForwardSlashesEscapedJsonRequest_ToAdminPortalRootWithValidIndexURI() throws Exception { + public void should_UpdateStubbedRequest_WithForwardSlashesEscapedJsonRequest_ToAdminPortalRootWithValidIndexURI() + throws Exception { final String requestUrl = String.format("%s%s", ADMIN_URL, "/0"); HttpRequest httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); @@ -487,7 +511,8 @@ public void should_UpdateStubbedRequest_WithForwardSlashesEscapedJsonRequest_ToA final InputStream jsonInputStream = url.openStream(); final String escapedJsonToUpdate = StringUtils.inputStreamToString(jsonInputStream); - final HttpRequest httpPutRequest = HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl, escapedJsonToUpdate); + final HttpRequest httpPutRequest = + HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl, escapedJsonToUpdate); final HttpResponse httpPutResponse = httpPutRequest.execute(); final String putResponseContent = httpPutResponse.parseAsString().trim(); @@ -497,7 +522,6 @@ public void should_UpdateStubbedRequest_WithForwardSlashesEscapedJsonRequest_ToA assertThat(putResponseLocationHeader).isEqualTo("^/resources/something/new?someKey=someValue"); assertThat(putResponseContent).isEqualTo("Stub request index#0 updated successfully"); - httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); httpGetResponse = httpGetRequest.execute(); getResponseContent = httpGetResponse.parseAsString().trim(); @@ -514,7 +538,8 @@ public void should_UpdateStubbedRequest_WithForwardSlashesEscapedJsonRequest_ToA } @Test - public void should_ReturnExpectedError_WhenSuccessfulDeleteMade_ToAdminPortalRootWithInvalidIndexURI() throws Exception { + public void should_ReturnExpectedError_WhenSuccessfulDeleteMade_ToAdminPortalRootWithInvalidIndexURI() + throws Exception { final int invalidIndex = 88888888; final String requestUrl = String.format("%s/%s", ADMIN_URL, invalidIndex); @@ -525,7 +550,8 @@ public void should_ReturnExpectedError_WhenSuccessfulDeleteMade_ToAdminPortalRoo } @Test - public void should_DeleteStubbedRequest_WhenSuccessfulDeleteMade_ToAdminPortalRootWithValidIndexURI() throws Exception { + public void should_DeleteStubbedRequest_WhenSuccessfulDeleteMade_ToAdminPortalRootWithValidIndexURI() + throws Exception { final String requestUrl = String.format("%s%s", ADMIN_URL, "/2"); HttpRequest httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); @@ -534,11 +560,12 @@ public void should_DeleteStubbedRequest_WhenSuccessfulDeleteMade_ToAdminPortalRo assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode()); assertThat(getResponseContent).contains("request"); - assertThat(getResponseContent).contains("url: ^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+\\?paramOne=[a-zA-Z]{3,8}¶mTwo=[a-zA-Z]{3,8}"); + assertThat(getResponseContent) + .contains( + "url: ^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+\\?paramOne=[a-zA-Z]{3,8}¶mTwo=[a-zA-Z]{3,8}"); assertThat(getResponseContent).contains("response"); assertThat(getResponseContent).contains("content-type: application/json"); - final HttpRequest httpDeleteRequest = HttpUtils.constructHttpRequest(HttpMethods.DELETE, requestUrl); final HttpResponse httpDeleteResponse = httpDeleteRequest.execute(); @@ -552,7 +579,9 @@ public void should_DeleteStubbedRequest_WhenSuccessfulDeleteMade_ToAdminPortalRo getResponseContent = httpGetResponse.parseAsString().trim(); assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode()); - assertThat(getResponseContent).doesNotContain("url: ^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+\\?paramOne=[a-zA-Z]{3,8}¶mTwo=[a-zA-Z]{3,8}"); + assertThat(getResponseContent) + .doesNotContain( + "url: ^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+\\?paramOne=[a-zA-Z]{3,8}¶mTwo=[a-zA-Z]{3,8}"); } @Test @@ -565,11 +594,13 @@ public void should_DeleteStubbedRequest_WhenSuccessfulDeleteMade_ToAdminPortalRo final String deleteResponseContent = httpDeleteResponse.parseAsString().trim(); assertThat(HttpStatus.OK_200).isEqualTo(httpDeleteResponse.getStatusCode()); - assertThat(deleteResponseContent).isEqualTo("Stub request uuid#9136d8b7-f7a7-478d-97a5-53292484aaf6 deleted successfully"); + assertThat(deleteResponseContent) + .isEqualTo("Stub request uuid#9136d8b7-f7a7-478d-97a5-53292484aaf6 deleted successfully"); } @Test - public void should_ReturnExpectedError_WhenSuccessfulDeleteMade_ToAdminPortalRootWithInvalidUuid() throws Exception { + public void should_ReturnExpectedError_WhenSuccessfulDeleteMade_ToAdminPortalRootWithInvalidUuid() + throws Exception { final String requestUrl = String.format("%s%s", ADMIN_URL, "/this-uuid-does-not-exist"); final HttpRequest httpDeleteRequest = HttpUtils.constructHttpRequest(HttpMethods.DELETE, requestUrl); @@ -579,7 +610,8 @@ public void should_ReturnExpectedError_WhenSuccessfulDeleteMade_ToAdminPortalRoo } @Test - public void should_DeleteAllStubbedRequests_WhenSuccessfulDeleteMade_ToAdminPortalRootWithValidIndexURI() throws Exception { + public void should_DeleteAllStubbedRequests_WhenSuccessfulDeleteMade_ToAdminPortalRootWithValidIndexURI() + throws Exception { final String requestUrl = String.format("%s%s", ADMIN_URL, "/2"); HttpRequest httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); @@ -588,11 +620,12 @@ public void should_DeleteAllStubbedRequests_WhenSuccessfulDeleteMade_ToAdminPort assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode()); assertThat(getResponseContent).contains("request"); - assertThat(getResponseContent).contains("url: ^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+\\?paramOne=[a-zA-Z]{3,8}¶mTwo=[a-zA-Z]{3,8}"); + assertThat(getResponseContent) + .contains( + "url: ^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+\\?paramOne=[a-zA-Z]{3,8}¶mTwo=[a-zA-Z]{3,8}"); assertThat(getResponseContent).contains("response"); assertThat(getResponseContent).contains("content-type: application/json"); - final String deleteAllRequestUrl = String.format("%s", ADMIN_URL); final HttpRequest httpDeleteRequest = HttpUtils.constructHttpRequest(HttpMethods.DELETE, deleteAllRequestUrl); @@ -610,7 +643,6 @@ public void should_DeleteAllStubbedRequests_WhenSuccessfulDeleteMade_ToAdminPort assertThat(getResponseContent).isEmpty(); } - @Test public void should_ReturnExpectedError_WhenSuccessfulPostMade_ToAdminPortalRootWithAnIndexURI() throws Exception { @@ -624,7 +656,7 @@ public void should_ReturnExpectedError_WhenSuccessfulPostMade_ToAdminPortalRootW assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.METHOD_NOT_ALLOWED_405); assertThat(statusMessage).isEqualTo("Method Not Allowed"); - //assertThat(responseMessage).isEqualTo("Method POST is not allowed on URI /5"); + // assertThat(responseMessage).isEqualTo("Method POST is not allowed on URI /5"); } @Test @@ -641,7 +673,8 @@ public void should_ReturnExpectedError_WhenSuccessfulEmptyPostMade_ToAdminPortal public void should_ReturnExpectedError_WhenSuccessfulInvalidPostMade_ToAdminPortalRoot() throws Exception { final String requestUrl = String.format("%s/", ADMIN_URL); - final HttpRequest httpPuttRequest = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, "unparseable rubbish post content"); + final HttpRequest httpPuttRequest = + HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, "unparseable rubbish post content"); final HttpResponse httpResponse = httpPuttRequest.execute(); assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST_400); @@ -656,7 +689,8 @@ public void should_Return400_WhenCreatingWholeStubsConfig_WithDuplicateUUIDs() t final InputStream jsonInputStream = url.openStream(); final String jsonToCreate = StringUtils.inputStreamToString(jsonInputStream); - final HttpRequest httpDeleteRequest = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, jsonToCreate); + final HttpRequest httpDeleteRequest = + HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, jsonToCreate); final HttpResponse httpDeleteResponse = httpDeleteRequest.execute(); assertThat(httpDeleteResponse.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST_400); diff --git a/src/functionalTest/java/io/github/azagniotov/stubby4j/HttpClientUtils.java b/src/functionalTest/java/io/github/azagniotov/stubby4j/HttpClientUtils.java index 927137f64..f081388d6 100644 --- a/src/functionalTest/java/io/github/azagniotov/stubby4j/HttpClientUtils.java +++ b/src/functionalTest/java/io/github/azagniotov/stubby4j/HttpClientUtils.java @@ -1,6 +1,29 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; +import static java.util.Arrays.asList; + import io.github.azagniotov.stubby4j.server.ssl.SslUtils; +import java.net.ProxySelector; +import java.util.HashSet; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; import org.apache.http.client.config.RequestConfig; import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; @@ -13,45 +36,34 @@ import org.eclipse.jetty.http2.client.http.HttpClientTransportOverHTTP2; import org.eclipse.jetty.util.ssl.SslContextFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLEngine; -import java.net.ProxySelector; -import java.util.HashSet; -import java.util.concurrent.TimeUnit; - -import static java.util.Arrays.asList; - public final class HttpClientUtils { - private HttpClientUtils() { - - } + private HttpClientUtils() {} static CloseableHttpClient buildHttpClient(final String tlsVersion) throws Exception { return buildHttpClient(tlsVersion, buildSSLContextWithRemoteCertificateLoaded(tlsVersion)); } - private static CloseableHttpClient buildHttpClient(final String tlsVersion, final SSLContext sslContext) throws Exception { + private static CloseableHttpClient buildHttpClient(final String tlsVersion, final SSLContext sslContext) + throws Exception { System.out.println("Running tests using TLS version: " + tlsVersion); SSLEngine engine = sslContext.createSSLEngine(); - engine.setEnabledProtocols(new String[]{tlsVersion}); + engine.setEnabledProtocols(new String[] {tlsVersion}); System.out.println("SSLEngine [client] enabled protocols: "); System.out.println(new HashSet<>(asList(engine.getEnabledProtocols()))); - final SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory( - sslContext, - new DefaultHostnameVerifier()); + final SSLConnectionSocketFactory sslSocketFactory = + new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier()); return HttpClientBuilder.create() - .setDefaultRequestConfig(RequestConfig - .custom() + .setDefaultRequestConfig(RequestConfig.custom() .setSocketTimeout(45000) .setConnectTimeout(45000) .build()) // When .useSystemProperties(), the FakeX509TrustManager gets exercised - //.useSystemProperties() + // .useSystemProperties() .setSSLSocketFactory(sslSocketFactory) .setMaxConnTotal(200) .setMaxConnPerRoute(20) @@ -61,8 +73,10 @@ private static CloseableHttpClient buildHttpClient(final String tlsVersion, fina // In ProxyConfigWithStubsTest.shouldReturnProxiedRequestResponse_WhenStubsWereNotMatched(): // - // I had to set this header to avoid "Not in GZIP format java.util.zip.ZipException: Not in GZIP format" error: - // The 'null' overrides the default value "gzip", also I had to .disableContentCompression() on WEB_CLIENT + // I had to set this header to avoid "Not in GZIP format java.util.zip.ZipException: Not in GZIP format" + // error: + // The 'null' overrides the default value "gzip", also I had to .disableContentCompression() on + // WEB_CLIENT .disableContentCompression() .disableAutomaticRetries() .build(); @@ -89,7 +103,8 @@ static SSLContext buildSSLContextWithRemoteCertificateLoaded(final String tlsVer // 4. Load the generated FILE_NAME.jks file into the trust store of SSLContext, which then can be // used to create an SSL socket factory for your web client. The STUBBY_SELF_SIGNED_TRUST_STORE // was created using the following code: - // https://github.com/azagniotov/stubby4j/blob/737f1f16650ce78a9a63f8f3e23c60ba2769cdb4/src/main/java/io/github/azagniotov/stubby4j/server/ssl/SslUtils.java#L168-L172 + // + // https://github.com/azagniotov/stubby4j/blob/737f1f16650ce78a9a63f8f3e23c60ba2769cdb4/src/main/java/io/github/azagniotov/stubby4j/server/ssl/SslUtils.java#L168-L172 // --------------------------------------------------------------------------------- return SSLContexts.custom() .setProtocol(tlsVersion) diff --git a/src/functionalTest/java/io/github/azagniotov/stubby4j/HttpUtils.java b/src/functionalTest/java/io/github/azagniotov/stubby4j/HttpUtils.java index d17e2c23b..fc3ccbdc8 100644 --- a/src/functionalTest/java/io/github/azagniotov/stubby4j/HttpUtils.java +++ b/src/functionalTest/java/io/github/azagniotov/stubby4j/HttpUtils.java @@ -1,18 +1,32 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; +import static io.github.azagniotov.stubby4j.HttpClientUtils.buildHttpClient; +import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.TLS_v1_2; + import com.google.api.client.http.ByteArrayContent; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.apache.v2.ApacheHttpTransport; import io.github.azagniotov.stubby4j.utils.StringUtils; -import org.apache.http.impl.client.CloseableHttpClient; - import java.io.IOException; - -import static io.github.azagniotov.stubby4j.HttpClientUtils.buildHttpClient; -import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.TLS_v1_2; - +import org.apache.http.impl.client.CloseableHttpClient; final class HttpUtils { @@ -32,19 +46,15 @@ final class HttpUtils { }); } - private HttpUtils() { - - } + private HttpUtils() {} static HttpRequest constructHttpRequest(final String method, final String targetUrl) throws IOException { - return WEB_CLIENT.buildRequest(method, - new GenericUrl(targetUrl), - null); + return WEB_CLIENT.buildRequest(method, new GenericUrl(targetUrl), null); } - static HttpRequest constructHttpRequest(final String method, final String targetUrl, final String content) throws IOException { - return WEB_CLIENT.buildRequest(method, - new GenericUrl(targetUrl), - new ByteArrayContent(null, StringUtils.getBytesUtf8(content))); + static HttpRequest constructHttpRequest(final String method, final String targetUrl, final String content) + throws IOException { + return WEB_CLIENT.buildRequest( + method, new GenericUrl(targetUrl), new ByteArrayContent(null, StringUtils.getBytesUtf8(content))); } } diff --git a/src/functionalTest/java/io/github/azagniotov/stubby4j/ProxyConfigWithStubsTest.java b/src/functionalTest/java/io/github/azagniotov/stubby4j/ProxyConfigWithStubsTest.java index c47106c7d..bab5a0216 100644 --- a/src/functionalTest/java/io/github/azagniotov/stubby4j/ProxyConfigWithStubsTest.java +++ b/src/functionalTest/java/io/github/azagniotov/stubby4j/ProxyConfigWithStubsTest.java @@ -1,5 +1,26 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_CONFIG; +import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_RESPONSE; +import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; + import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpMethods; import com.google.api.client.http.HttpRequest; @@ -11,6 +32,8 @@ import io.github.azagniotov.stubby4j.utils.NetworkPortUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; import io.github.azagniotov.stubby4j.yaml.YamlBuilder; +import java.io.InputStream; +import java.net.URL; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpStatus; import org.junit.After; @@ -21,14 +44,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import java.io.InputStream; -import java.net.URL; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_CONFIG; -import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_RESPONSE; -import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; - public class ProxyConfigWithStubsTest { private static final int STUBS_PORT = NetworkPortUtils.findAvailableTcpPort(); @@ -83,18 +98,17 @@ public void should_ReturnCompleteYAMLConfig_WhenSuccessfulGetMade_ToAdminPortalR final String responseContentAsString = httpResponse.parseAsString().trim(); assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat(responseContentAsString).contains( - "- proxy-config:\n" + - " description: this is a catch-all proxy config\n" + - " strategy: as-is\n" + - " properties:\n" + - " endpoint: https://jsonplaceholder.typicode.com" - ); + assertThat(responseContentAsString) + .contains("- proxy-config:\n" + " description: this is a catch-all proxy config\n" + + " strategy: as-is\n" + + " properties:\n" + + " endpoint: https://jsonplaceholder.typicode.com"); } @Test @PotentiallyFlaky("This test sending the request over the wire to https://jsonplaceholder.typicode.com") - public void shouldReturnProxiedResponseUsingDefaultProxyConfig_WhenStubsWereNotMatched_PotentiallyFlaky() throws Exception { + public void shouldReturnProxiedResponseUsingDefaultProxyConfig_WhenStubsWereNotMatched_PotentiallyFlaky() + throws Exception { // https://jsonplaceholder.typicode.com/todos/1 final String targetUriPath = "/todos/1"; @@ -113,21 +127,22 @@ public void shouldReturnProxiedResponseUsingDefaultProxyConfig_WhenStubsWereNotM final HttpResponse response = request.execute(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat(response.getHeaders().containsKey(HEADER_X_STUBBY_PROXY_RESPONSE)).isTrue(); + assertThat(response.getHeaders().containsKey(HEADER_X_STUBBY_PROXY_RESPONSE)) + .isTrue(); final String responseContent = response.parseAsString().trim(); - assertThat(responseContent).isEqualTo( - "{" + BR + - " \"userId\": 1," + BR + - " \"id\": 1," + BR + - " \"title\": \"delectus aut autem\"," + BR + - " \"completed\": false" + BR + - "}"); + assertThat(responseContent) + .isEqualTo("{" + BR + " \"userId\": 1," + + BR + " \"id\": 1," + + BR + " \"title\": \"delectus aut autem\"," + + BR + " \"completed\": false" + + BR + "}"); } @Test @PotentiallyFlaky("This test sending the request over the wire to https://jsonplaceholder.typicode.com") - public void shouldReturnProxiedResponseUsingSpecificProxyConfig_WhenStubsWereNotMatched_PotentiallyFlaky() throws Exception { + public void shouldReturnProxiedResponseUsingSpecificProxyConfig_WhenStubsWereNotMatched_PotentiallyFlaky() + throws Exception { // https://jsonplaceholder.typicode.com/todos/1 final String targetUriPath = "/todos/1"; @@ -141,23 +156,24 @@ public void shouldReturnProxiedResponseUsingSpecificProxyConfig_WhenStubsWereNot // The 'null' overrides the default value "gzip", also I had to .disableContentCompression() on WEB_CLIENT httpHeaders.setAcceptEncoding(null); - // The 'some-unique-name' is actually set in 'proxy-config' object defined in resources/yaml/include-proxy-config.yaml + // The 'some-unique-name' is actually set in 'proxy-config' object defined in + // resources/yaml/include-proxy-config.yaml httpHeaders.set(HEADER_X_STUBBY_PROXY_CONFIG, "some-unique-name"); request.setHeaders(httpHeaders); final HttpResponse response = request.execute(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat(response.getHeaders().containsKey(HEADER_X_STUBBY_PROXY_RESPONSE)).isTrue(); + assertThat(response.getHeaders().containsKey(HEADER_X_STUBBY_PROXY_RESPONSE)) + .isTrue(); final String responseContent = response.parseAsString().trim(); - assertThat(responseContent).isEqualTo( - "{" + BR + - " \"userId\": 1," + BR + - " \"id\": 1," + BR + - " \"title\": \"delectus aut autem\"," + BR + - " \"completed\": false" + BR + - "}"); + assertThat(responseContent) + .isEqualTo("{" + BR + " \"userId\": 1," + + BR + " \"id\": 1," + + BR + " \"title\": \"delectus aut autem\"," + + BR + " \"completed\": false" + + BR + "}"); } @Test @@ -173,15 +189,13 @@ public void should_UpdateStubbedProxyConfig_WithJsonRequest_ByValidUuid() throws String getResponseContent = httpGetResponse.parseAsString().trim(); assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode()); - assertThat(getResponseContent).isEqualTo( - "- proxy-config:\n" + - " uuid: some-unique-name\n" + - " strategy: additive\n" + - " headers:\n" + - " x-original-stubby4j-custom-header: custom/value\n" + - " properties:\n" + - " endpoint: https://jsonplaceholder.typicode.com"); - + assertThat(getResponseContent) + .isEqualTo("- proxy-config:\n" + " uuid: some-unique-name\n" + + " strategy: additive\n" + + " headers:\n" + + " x-original-stubby4j-custom-header: custom/value\n" + + " properties:\n" + + " endpoint: https://jsonplaceholder.typicode.com"); /////////////////////////////////////////////////////////////////////////////////////// // The actual test: updating by UUID @@ -208,14 +222,13 @@ public void should_UpdateStubbedProxyConfig_WithJsonRequest_ByValidUuid() throws getResponseContent = httpGetResponse.parseAsString().trim(); assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode()); - assertThat(getResponseContent).isEqualTo( - "- proxy-config:\n" + - " uuid: some-unique-name\n" + - " strategy: additive\n" + - " headers:\n" + - " x-custom-header: custom/value\n" + - " properties:\n" + - " endpoint: https://UPDATED.com"); + assertThat(getResponseContent) + .isEqualTo("- proxy-config:\n" + " uuid: some-unique-name\n" + + " strategy: additive\n" + + " headers:\n" + + " x-custom-header: custom/value\n" + + " properties:\n" + + " endpoint: https://UPDATED.com"); } @Test @@ -231,12 +244,11 @@ public void should_UpdateStubbedDefaultProxyConfig_WithYamlRequest_ByValidUuid() String getResponseContent = httpGetResponse.parseAsString().trim(); assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode()); - assertThat(getResponseContent).isEqualTo( - "- proxy-config:\n" + - " description: this is a catch-all proxy config\n" + - " strategy: as-is\n" + - " properties:\n" + - " endpoint: https://jsonplaceholder.typicode.com"); + assertThat(getResponseContent) + .isEqualTo("- proxy-config:\n" + " description: this is a catch-all proxy config\n" + + " strategy: as-is\n" + + " properties:\n" + + " endpoint: https://jsonplaceholder.typicode.com"); /////////////////////////////////////////////////////////////////////////////////////// // The actual test: updating the 'default' proxy config by UUID @@ -265,13 +277,12 @@ public void should_UpdateStubbedDefaultProxyConfig_WithYamlRequest_ByValidUuid() getResponseContent = httpGetResponse.parseAsString().trim(); assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode()); - assertThat(getResponseContent).isEqualTo( - "- proxy-config:\n" + - " description: this is a catch-all proxy config that was updated\n" + - " strategy: as-is\n" + - " properties:\n" + - " endpoint: https://google.com\n" + - " uniqueKey: arbitraryValue"); + assertThat(getResponseContent) + .isEqualTo("- proxy-config:\n" + " description: this is a catch-all proxy config that was updated\n" + + " strategy: as-is\n" + + " properties:\n" + + " endpoint: https://google.com\n" + + " uniqueKey: arbitraryValue"); } @Test @@ -322,18 +333,17 @@ public void should_CreateWholeYAMLConfig_WithJsonRequest() throws Exception { /////////////////////////////////////////////////////////////////////////////////////// // 1st sanity check: verifying the original endpoint URL /////////////////////////////////////////////////////////////////////////////////////// - HttpRequest httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl + "proxy-config/default"); + HttpRequest httpGetRequest = + HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl + "proxy-config/default"); HttpResponse httpGetResponse = httpGetRequest.execute(); String getResponseContent = httpGetResponse.parseAsString().trim(); assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode()); - assertThat(getResponseContent).isEqualTo( - "- proxy-config:\n" + - " description: this is a catch-all proxy config\n" + - " strategy: as-is\n" + - " properties:\n" + - " endpoint: https://jsonplaceholder.typicode.com"); - + assertThat(getResponseContent) + .isEqualTo("- proxy-config:\n" + " description: this is a catch-all proxy config\n" + + " strategy: as-is\n" + + " properties:\n" + + " endpoint: https://jsonplaceholder.typicode.com"); /////////////////////////////////////////////////////////////////////////////////////// // The actual test: Creating a new YAML config by POST request @@ -358,12 +368,11 @@ public void should_CreateWholeYAMLConfig_WithJsonRequest() throws Exception { getResponseContent = httpGetResponse.parseAsString().trim(); assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode()); - assertThat(getResponseContent).contains( - "- proxy-config:\n" + - " description: this would be the default proxy config\n" + - " strategy: as-is\n" + - " properties:\n" + - " endpoint: https://google.com"); + assertThat(getResponseContent) + .contains("- proxy-config:\n" + " description: this would be the default proxy config\n" + + " strategy: as-is\n" + + " properties:\n" + + " endpoint: https://google.com"); } @Test @@ -372,7 +381,8 @@ public void should_Return400_WhenCreatingWholeConfig_WithEmptyPayload() throws E final String requestUrl = String.format("%s/", ADMIN_URL); final String jsonToCreate = ""; - final HttpRequest httpDeleteRequest = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, jsonToCreate); + final HttpRequest httpDeleteRequest = + HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, jsonToCreate); final HttpResponse httpDeleteResponse = httpDeleteRequest.execute(); assertThat(httpDeleteResponse.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST_400); @@ -387,14 +397,16 @@ public void should_Return400_WhenCreatingWholeProxyConfig_WithDuplicateUUIDs() t final InputStream jsonInputStream = url.openStream(); final String jsonToCreate = StringUtils.inputStreamToString(jsonInputStream); - final HttpRequest httpDeleteRequest = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, jsonToCreate); + final HttpRequest httpDeleteRequest = + HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, jsonToCreate); final HttpResponse httpDeleteResponse = httpDeleteRequest.execute(); assertThat(httpDeleteResponse.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST_400); } @Test - public void should_DeleteStubbedProxyConfig_WhenSuccessfulDeleteMade_ToAdminPortalRootWithValidUuid() throws Exception { + public void should_DeleteStubbedProxyConfig_WhenSuccessfulDeleteMade_ToAdminPortalRootWithValidUuid() + throws Exception { final String requestUrl = String.format("%s%s", ADMIN_URL, "/proxy-config/some-unique-name-two"); final HttpRequest httpDeleteRequest = HttpUtils.constructHttpRequest(HttpMethods.DELETE, requestUrl); diff --git a/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsAdminPortalsTest.java b/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsAdminPortalsTest.java index 4b789973e..3bd5c0668 100644 --- a/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsAdminPortalsTest.java +++ b/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsAdminPortalsTest.java @@ -1,5 +1,24 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; + import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpMethods; import com.google.api.client.http.HttpRequest; @@ -11,20 +30,16 @@ import io.github.azagniotov.stubby4j.utils.NetworkPortUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; import io.github.azagniotov.stubby4j.yaml.YamlBuilder; +import java.io.InputStream; +import java.net.URL; +import java.util.LinkedList; +import java.util.List; import org.eclipse.jetty.http.HttpStatus; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import java.io.InputStream; -import java.net.URL; -import java.util.LinkedList; -import java.util.List; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; - public class StubsAdminPortalsTest { private static final int STUBS_PORT = NetworkPortUtils.findAvailableTcpPort(); @@ -62,7 +77,8 @@ public void beforeEach() throws Exception { } @Test - public void should_UpdateStubsDataAndGetNewResource_WhenSuccessfulValidPostMade_ToAdminPortalRoot() throws Exception { + public void should_UpdateStubsDataAndGetNewResource_WhenSuccessfulValidPostMade_ToAdminPortalRoot() + throws Exception { final String yamlToUpdate = new YamlBuilder() .newStubbedRequest() @@ -76,7 +92,8 @@ public void should_UpdateStubsDataAndGetNewResource_WhenSuccessfulValidPostMade_ .build(); final String adminRequestUrl = String.format("%s/", ADMIN_URL); - final HttpRequest httpPuttRequest = HttpUtils.constructHttpRequest(HttpMethods.POST, adminRequestUrl, yamlToUpdate); + final HttpRequest httpPuttRequest = + HttpUtils.constructHttpRequest(HttpMethods.POST, adminRequestUrl, yamlToUpdate); final HttpResponse httpResponse = httpPuttRequest.execute(); final String statusMessage = httpResponse.getStatusMessage().trim(); @@ -101,14 +118,18 @@ public void should_UpdateStubsDataAndGetNewResource_WhenSuccessfulValidPostMade_ @Test public void should_AdjustResourceIdHeaderAccordingly_WhenSuccessfulDeleteMade() throws Exception { - final String stubsRequestUrl = String.format("%s%s", STUBS_URL, "/this/stub/should/always/be/second/in/this/file"); + final String stubsRequestUrl = + String.format("%s%s", STUBS_URL, "/this/stub/should/always/be/second/in/this/file"); final HttpRequest stubsGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, stubsRequestUrl); final HttpResponse preDeletionStubGetResponse = stubsGetRequest.execute(); final HttpHeaders preDeletionResponseHeaders = preDeletionStubGetResponse.getHeaders(); - assertThat(preDeletionResponseHeaders.containsKey(Common.HEADER_X_STUBBY_RESOURCE_ID)).isTrue(); - assertThat(preDeletionResponseHeaders.getFirstHeaderStringValue(Common.HEADER_X_STUBBY_RESOURCE_ID)).isEqualTo("1"); + assertThat(preDeletionResponseHeaders.containsKey(Common.HEADER_X_STUBBY_RESOURCE_ID)) + .isTrue(); + assertThat(preDeletionResponseHeaders.getFirstHeaderStringValue(Common.HEADER_X_STUBBY_RESOURCE_ID)) + .isEqualTo("1"); - final HttpRequest httpDeleteRequest = HttpUtils.constructHttpRequest(HttpMethods.DELETE, String.format("%s%s", ADMIN_URL, "/0")); + final HttpRequest httpDeleteRequest = + HttpUtils.constructHttpRequest(HttpMethods.DELETE, String.format("%s%s", ADMIN_URL, "/0")); final HttpResponse httpDeleteResponse = httpDeleteRequest.execute(); final String deleteResponseContent = httpDeleteResponse.parseAsString().trim(); assertThat(HttpStatus.OK_200).isEqualTo(httpDeleteResponse.getStatusCode()); @@ -117,8 +138,10 @@ public void should_AdjustResourceIdHeaderAccordingly_WhenSuccessfulDeleteMade() final HttpRequest postDeletionStubGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, stubsRequestUrl); final HttpResponse postDeletionStubGetResponse = postDeletionStubGetRequest.execute(); final HttpHeaders postDeletionResponseHeaders = postDeletionStubGetResponse.getHeaders(); - assertThat(postDeletionResponseHeaders.containsKey(Common.HEADER_X_STUBBY_RESOURCE_ID)).isTrue(); - assertThat(postDeletionResponseHeaders.getFirstHeaderStringValue(Common.HEADER_X_STUBBY_RESOURCE_ID)).isEqualTo("0"); + assertThat(postDeletionResponseHeaders.containsKey(Common.HEADER_X_STUBBY_RESOURCE_ID)) + .isTrue(); + assertThat(postDeletionResponseHeaders.getFirstHeaderStringValue(Common.HEADER_X_STUBBY_RESOURCE_ID)) + .isEqualTo("0"); } @Test @@ -137,7 +160,8 @@ public void should_ReturnAjaxRequestContent_WhenSuccessfulRequestMade() throws E assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED_201); final String resourceID = response.getHeaders().getFirstHeaderStringValue(Common.HEADER_X_STUBBY_RESOURCE_ID); - final String ajaxRequestUrl = String.format("%s%s%s%s", ADMIN_URL, "/ajax/resource/", resourceID, "/request/post"); + final String ajaxRequestUrl = + String.format("%s%s%s%s", ADMIN_URL, "/ajax/resource/", resourceID, "/request/post"); final HttpRequest ajaxRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, ajaxRequestUrl); final HttpResponse ajaxResponse = ajaxRequest.execute(); @@ -162,7 +186,8 @@ public void should_ReturnAjaxResponseContent_WhenSuccessfulRequestMade() throws assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED_201); final String resourceID = response.getHeaders().getFirstHeaderStringValue(Common.HEADER_X_STUBBY_RESOURCE_ID); - final String ajaxRequestUrl = String.format("%s%s%s%s", ADMIN_URL, "/ajax/resource/", resourceID, "/response/body"); + final String ajaxRequestUrl = + String.format("%s%s%s%s", ADMIN_URL, "/ajax/resource/", resourceID, "/response/body"); final HttpRequest ajaxRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, ajaxRequestUrl); final HttpResponse ajaxResponse = ajaxRequest.execute(); @@ -180,7 +205,8 @@ public void should_ReturnAjaxSequencedResponseContent_WhenSuccessfulRequestMade( assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED_201); final String resourceID = response.getHeaders().getFirstHeaderStringValue(Common.HEADER_X_STUBBY_RESOURCE_ID); - final String ajaxRequestUrl = String.format("%s%s%s%s", ADMIN_URL, "/ajax/resource/", resourceID, "/response/1/file"); + final String ajaxRequestUrl = + String.format("%s%s%s%s", ADMIN_URL, "/ajax/resource/", resourceID, "/response/1/file"); final HttpRequest ajaxRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, ajaxRequestUrl); final HttpResponse ajaxResponse = ajaxRequest.execute(); @@ -204,26 +230,26 @@ public void should_ReturnAjaxHttpLifecycleYAMLResponse_WhenSuccessfulRequestMade assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED_201); final String resourceID = response.getHeaders().getFirstHeaderStringValue(Common.HEADER_X_STUBBY_RESOURCE_ID); - final String ajaxRequestUrl = String.format("%s%s%s%s", ADMIN_URL, "/ajax/resource/", resourceID, "/httplifecycle/completeYAML"); + final String ajaxRequestUrl = + String.format("%s%s%s%s", ADMIN_URL, "/ajax/resource/", resourceID, "/httplifecycle/completeYAML"); final HttpRequest ajaxRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, ajaxRequestUrl); final HttpResponse ajaxResponse = ajaxRequest.execute(); assertThat(ajaxResponse.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat(ajaxResponse.parseAsString().trim()).contains( - "- request:" + BR + - " method: POST" + BR + - " url: /invoice/new" + BR + - " headers:" + BR + - " content-type: " + Common.HEADER_APPLICATION_JSON + BR + - " post: |" + BR + - " {\"name\": \"chocolate\", \"description\": \"full\", \"department\": \"savoury\"}" + BR + - " response:" + BR + - " headers:" + BR + - " content-type: " + Common.HEADER_APPLICATION_JSON + BR + - " pragma: no-cache" + BR + - " status: 201" + BR + - " body: |" + BR + - " {\"id\": \"456\", \"status\": \"created\"}"); + assertThat(ajaxResponse.parseAsString().trim()) + .contains("- request:" + BR + " method: POST" + + BR + " url: /invoice/new" + + BR + " headers:" + + BR + " content-type: " + + Common.HEADER_APPLICATION_JSON + BR + " post: |" + + BR + " {\"name\": \"chocolate\", \"description\": \"full\", \"department\": \"savoury\"}" + + BR + " response:" + + BR + " headers:" + + BR + " content-type: " + + Common.HEADER_APPLICATION_JSON + BR + " pragma: no-cache" + + BR + " status: 201" + + BR + " body: |" + + BR + " {\"id\": \"456\", \"status\": \"created\"}"); } @Test @@ -242,19 +268,19 @@ public void should_ReturnAjaxStubRequestYAMLResponse_WhenSuccessfulRequestMade() assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED_201); final String resourceID = response.getHeaders().getFirstHeaderStringValue(Common.HEADER_X_STUBBY_RESOURCE_ID); - final String ajaxRequestUrl = String.format("%s%s%s%s", ADMIN_URL, "/ajax/resource/", resourceID, "/httplifecycle/requestAsYAML"); + final String ajaxRequestUrl = + String.format("%s%s%s%s", ADMIN_URL, "/ajax/resource/", resourceID, "/httplifecycle/requestAsYAML"); final HttpRequest ajaxRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, ajaxRequestUrl); final HttpResponse ajaxResponse = ajaxRequest.execute(); assertThat(ajaxResponse.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat(ajaxResponse.parseAsString().trim()).contains( - "request:" + BR + - " method: POST" + BR + - " url: /invoice/new" + BR + - " headers:" + BR + - " content-type: application/json" + BR + - " post: |" + BR + - " {\"name\": \"chocolate\", \"description\": \"full\", \"department\": \"savoury\"}"); + assertThat(ajaxResponse.parseAsString().trim()) + .contains("request:" + BR + " method: POST" + + BR + " url: /invoice/new" + + BR + " headers:" + + BR + " content-type: application/json" + + BR + " post: |" + + BR + " {\"name\": \"chocolate\", \"description\": \"full\", \"department\": \"savoury\"}"); } @Test @@ -273,19 +299,19 @@ public void should_ReturnAjaxStubResponseYAMLResponse_WhenSuccessfulRequestMade( assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED_201); final String resourceID = response.getHeaders().getFirstHeaderStringValue(Common.HEADER_X_STUBBY_RESOURCE_ID); - final String ajaxRequestUrl = String.format("%s%s%s%s", ADMIN_URL, "/ajax/resource/", resourceID, "/httplifecycle/responseAsYAML"); + final String ajaxRequestUrl = + String.format("%s%s%s%s", ADMIN_URL, "/ajax/resource/", resourceID, "/httplifecycle/responseAsYAML"); final HttpRequest ajaxRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, ajaxRequestUrl); final HttpResponse ajaxResponse = ajaxRequest.execute(); assertThat(ajaxResponse.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat(ajaxResponse.parseAsString().trim()).contains( - "response:" + BR + - " headers:" + BR + - " content-type: application/json" + BR + - " pragma: no-cache" + BR + - " status: 201" + BR + - " body: |" + BR + - " {\"id\": \"456\", \"status\": \"created\"}"); + assertThat(ajaxResponse.parseAsString().trim()) + .contains("response:" + BR + " headers:" + + BR + " content-type: application/json" + + BR + " pragma: no-cache" + + BR + " status: 201" + + BR + " body: |" + + BR + " {\"id\": \"456\", \"status\": \"created\"}"); } @Test @@ -298,7 +324,8 @@ public void should_UpdateStubbedResponseBody_WhenRequestUrlStringRemainsUnchange final HttpResponse firstHttpGetResponse = firstHttpGetRequest.execute(); final String firstResponseContent = firstHttpGetResponse.parseAsString().trim(); - // Sanity check 1st request to Stubs to verify what the original stubbed response body contains for the above URL + // Sanity check 1st request to Stubs to verify what the original stubbed response body contains for the above + // URL assertThat(HttpStatus.OK_200).isEqualTo(firstHttpGetResponse.getStatusCode()); assertThat(firstResponseContent).contains("OK"); @@ -332,8 +359,10 @@ public void should_UpdateStubbedResponseBody_WhenRequestUrlStringRemainsUnchange // Making a stub update request final HttpRequest httpPutRequest = HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl, yamlToUpdate); final HttpResponse adminHttpPutResponse = httpPutRequest.execute(); - final String adminPutResponseContent = adminHttpPutResponse.parseAsString().trim(); - final String adminPutResponseLocationHeader = adminHttpPutResponse.getHeaders().getLocation(); + final String adminPutResponseContent = + adminHttpPutResponse.parseAsString().trim(); + final String adminPutResponseLocationHeader = + adminHttpPutResponse.getHeaders().getLocation(); assertThat(HttpStatus.OK_200).isEqualTo(adminHttpGetResponse.getStatusCode()); assertThat(adminPutResponseLocationHeader).isEqualTo(originalStubbedUrl); @@ -342,7 +371,8 @@ public void should_UpdateStubbedResponseBody_WhenRequestUrlStringRemainsUnchange // Sanity check 2nd request to Stubs to verify the updated stubbed response body for the above URL final HttpRequest secondHttpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, stubsRequestUrl); final HttpResponse secondHttpGetResponse = secondHttpGetRequest.execute(); - final String secondResponseContent = secondHttpGetResponse.parseAsString().trim(); + final String secondResponseContent = + secondHttpGetResponse.parseAsString().trim(); assertThat(HttpStatus.OK_200).isEqualTo(secondHttpGetResponse.getStatusCode()); assertThat(secondResponseContent).contains("OK Updated!"); @@ -353,12 +383,14 @@ public void should_UpdateStubbedResponseBody_WhenRequestUrlRegexRemainsUnchanged // Warm up the cache in StubRepository by making a request to a stub with URL regex: '^/resources/asn/.*$' final String originalStubbedUrl = "^/resources/asn/.*$"; - final List assertingRequests = new LinkedList() {{ - add("/resources/asn/1"); - add("/resources/asn/2"); - add("/resources/asn/3"); - add("/resources/asn/eew97we9"); - }}; + final List assertingRequests = new LinkedList() { + { + add("/resources/asn/1"); + add("/resources/asn/2"); + add("/resources/asn/3"); + add("/resources/asn/eew97we9"); + } + }; // Sanity check 1st requests to Stubs to verify what the stubbed response body contains for the above URLs for (final String assertingRequest : assertingRequests) { @@ -400,10 +432,13 @@ public void should_UpdateStubbedResponseBody_WhenRequestUrlRegexRemainsUnchanged .build(); // Making a stub update request - final HttpRequest httpPutRequest = HttpUtils.constructHttpRequest(HttpMethods.PUT, stubAdminRequestUrl, yamlToUpdate); + final HttpRequest httpPutRequest = + HttpUtils.constructHttpRequest(HttpMethods.PUT, stubAdminRequestUrl, yamlToUpdate); final HttpResponse adminHttpPutResponse = httpPutRequest.execute(); - final String adminPutResponseContent = adminHttpPutResponse.parseAsString().trim(); - final String adminPutResponseLocationHeader = adminHttpPutResponse.getHeaders().getLocation(); + final String adminPutResponseContent = + adminHttpPutResponse.parseAsString().trim(); + final String adminPutResponseLocationHeader = + adminHttpPutResponse.getHeaders().getLocation(); assertThat(HttpStatus.OK_200).isEqualTo(adminHttpGetResponse.getStatusCode()); assertThat(adminPutResponseLocationHeader).isEqualTo(originalStubbedUrl); @@ -421,4 +456,4 @@ public void should_UpdateStubbedResponseBody_WhenRequestUrlRegexRemainsUnchanged assertThat("{\"status\": \"ASN found AND UPDATED!\"}").isEqualTo(secondResponseContent); } } -} \ No newline at end of file +} diff --git a/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp11OverTlsTests.java b/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp11OverTlsTests.java index 6abba7b26..f88615c4b 100644 --- a/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp11OverTlsTests.java +++ b/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp11OverTlsTests.java @@ -1,11 +1,41 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.HttpClientUtils.buildHttpClient; +import static io.github.azagniotov.stubby4j.common.Common.HEADER_APPLICATION_JSON; +import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.SSLv3; +import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.TLS_v1_0; +import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.TLS_v1_1; +import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.TLS_v1_2; +import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.TLS_v1_3; +import static java.util.Arrays.asList; + import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.client.StubbyClient; import io.github.azagniotov.stubby4j.client.StubbyResponse; import io.github.azagniotov.stubby4j.server.ssl.SslUtils; import io.github.azagniotov.stubby4j.utils.NetworkPortUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.HashSet; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -18,21 +48,6 @@ import org.junit.BeforeClass; import org.junit.Test; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.HashSet; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.HttpClientUtils.buildHttpClient; -import static io.github.azagniotov.stubby4j.common.Common.HEADER_APPLICATION_JSON; -import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.SSLv3; -import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.TLS_v1_0; -import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.TLS_v1_1; -import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.TLS_v1_2; -import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.TLS_v1_3; -import static java.util.Arrays.asList; - public class StubsPortalHttp11OverTlsTests { private static final StubbyClient STUBBY_CLIENT = new StubbyClient(); @@ -62,7 +77,8 @@ public static void beforeClass() throws Exception { STUBBY_CLIENT.startJetty(STUBS_PORT, STUBS_SSL_PORT, ADMIN_PORT, url.getFile()); - final URL jsonContentUrl = StubsPortalHttp11OverTlsTests.class.getResource("/json/response/json_response_1.json"); + final URL jsonContentUrl = + StubsPortalHttp11OverTlsTests.class.getResource("/json/response/json_response_1.json"); assertThat(jsonContentUrl).isNotNull(); expectedContent = StringUtils.inputStreamToString(jsonContentUrl.openStream()); } diff --git a/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp11WebSocketOverTlsTests.java b/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp11WebSocketOverTlsTests.java index 598aa74cc..19841d690 100644 --- a/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp11WebSocketOverTlsTests.java +++ b/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp11WebSocketOverTlsTests.java @@ -1,5 +1,27 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.HttpClientUtils.jettyHttpClientOnHttp11WithClientSsl; +import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.TLS_v1_2; +import static io.github.azagniotov.stubby4j.server.websocket.StubsServerWebSocket.EMPTY_BYTE_BUFFER; +import static org.junit.Assert.assertThrows; + import io.github.azagniotov.stubby4j.annotations.PotentiallyFlaky; import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.client.StubbyClient; @@ -8,6 +30,20 @@ import io.github.azagniotov.stubby4j.utils.FileUtils; import io.github.azagniotov.stubby4j.utils.NetworkPortUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.StatusCode; @@ -31,27 +67,6 @@ import org.junit.Test; import org.junit.runners.MethodSorters; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URL; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.HttpClientUtils.jettyHttpClientOnHttp11WithClientSsl; -import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.TLS_v1_2; -import static io.github.azagniotov.stubby4j.server.websocket.StubsServerWebSocket.EMPTY_BYTE_BUFFER; -import static org.junit.Assert.assertThrows; - // There are jetty specific tests that I want to run last, hence the MethodSorters.NAME_ASCENDING, // since one of the tests will close the server websocket and stubby4j will have to be restarted. // Normally, it is a bad practice to have some interdependency in tests and should be avoided. @@ -66,14 +81,22 @@ public class StubsPortalHttp11WebSocketOverTlsTests { private static final String ADMIN_URL = String.format("http://localhost:%s", ADMIN_PORT); private static final String WEBSOCKET_SSL_ROOT_PATH_URL = String.format("wss://localhost:%s/ws", STUBS_SSL_PORT); - private static final URI REQUEST_URL_HELLO_1 = URI.create(String.format("%s%s", WEBSOCKET_SSL_ROOT_PATH_URL, "/demo/hello/1")); - private static final URI REQUEST_URL_HELLO_2 = URI.create(String.format("%s%s", WEBSOCKET_SSL_ROOT_PATH_URL, "/demo/hello/2")); - private static final URI REQUEST_URL_HELLO_3 = URI.create(String.format("%s%s", WEBSOCKET_SSL_ROOT_PATH_URL, "/demo/hello/3")); - private static final URI REQUEST_URL_HELLO_4 = URI.create(String.format("%s%s", WEBSOCKET_SSL_ROOT_PATH_URL, "/demo/hello/4")); - private static final URI REQUEST_URL_HELLO_5 = URI.create(String.format("%s%s", WEBSOCKET_SSL_ROOT_PATH_URL, "/demo/hello/5")); - private static final URI REQUEST_URL_HELLO_6 = URI.create(String.format("%s%s", WEBSOCKET_SSL_ROOT_PATH_URL, "/demo/hello/6")); - private static final URI REQUEST_URL_HELLO_7 = URI.create(String.format("%s%s", WEBSOCKET_SSL_ROOT_PATH_URL, "/demo/hello/7")); - private static final URI NON_STUBBED_REQUEST_URL = URI.create(String.format("%s%s", WEBSOCKET_SSL_ROOT_PATH_URL, "/blah")); + private static final URI REQUEST_URL_HELLO_1 = + URI.create(String.format("%s%s", WEBSOCKET_SSL_ROOT_PATH_URL, "/demo/hello/1")); + private static final URI REQUEST_URL_HELLO_2 = + URI.create(String.format("%s%s", WEBSOCKET_SSL_ROOT_PATH_URL, "/demo/hello/2")); + private static final URI REQUEST_URL_HELLO_3 = + URI.create(String.format("%s%s", WEBSOCKET_SSL_ROOT_PATH_URL, "/demo/hello/3")); + private static final URI REQUEST_URL_HELLO_4 = + URI.create(String.format("%s%s", WEBSOCKET_SSL_ROOT_PATH_URL, "/demo/hello/4")); + private static final URI REQUEST_URL_HELLO_5 = + URI.create(String.format("%s%s", WEBSOCKET_SSL_ROOT_PATH_URL, "/demo/hello/5")); + private static final URI REQUEST_URL_HELLO_6 = + URI.create(String.format("%s%s", WEBSOCKET_SSL_ROOT_PATH_URL, "/demo/hello/6")); + private static final URI REQUEST_URL_HELLO_7 = + URI.create(String.format("%s%s", WEBSOCKET_SSL_ROOT_PATH_URL, "/demo/hello/7")); + private static final URI NON_STUBBED_REQUEST_URL = + URI.create(String.format("%s%s", WEBSOCKET_SSL_ROOT_PATH_URL, "/blah")); private static WebSocketClient client; @@ -84,7 +107,8 @@ public static void beforeClass() throws Exception { ANSITerminal.muteConsole(true); - final URL url = StubsPortalHttp11WebSocketOverTlsTests.class.getResource("/yaml/main-test-stubs-with-web-socket-config.yaml"); + final URL url = StubsPortalHttp11WebSocketOverTlsTests.class.getResource( + "/yaml/main-test-stubs-with-web-socket-config.yaml"); assert url != null; final InputStream stubsDataInputStream = url.openStream(); @@ -96,7 +120,8 @@ public static void beforeClass() throws Exception { // WebSocket Bootstrap from HTTP/2 (RFC8441) not supported in Jetty 9.x // https://github.com/eclipse/jetty.project/blob/f86a719bce89844337e4f2bde68e8e147095ed80/jetty-websocket/websocket-server/src/main/java/org/eclipse/jetty/websocket/server/WebSocketServerFactory.java#L585 // - // Also, they added WebSocket Bootstrap from HTTP/2 (RFC8441) only in Jetty 10.x.x: https://github.com/eclipse/jetty.project/pull/3740 + // Also, they added WebSocket Bootstrap from HTTP/2 (RFC8441) only in Jetty 10.x.x: + // https://github.com/eclipse/jetty.project/pull/3740 STUBBY_CLIENT.startJetty(STUBS_PORT, STUBS_SSL_PORT, ADMIN_PORT, JettyFactory.DEFAULT_HOST, url.getFile(), ""); client = new WebSocketClient(jettyHttpClientOnHttp11WithClientSsl(TLS_v1_2)); @@ -164,7 +189,8 @@ public void serverOnOpen_SendsExpected_TextMessage() throws Exception { // Wait for client to get all the messages from the server socket.awaitCountDownLatchWithAssertion(); assertThat(socket.receivedOnMessageText.size()).isEqualTo(1); - assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")).isTrue(); + assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")) + .isTrue(); } @Test @@ -239,7 +265,8 @@ public void serverOnOpen_RespondsWithExpected_ContinuousPing() throws Exception } @Test - public void serverOnMessage_ReactsToClient_RealBinaryMessage_AndRespondsWithExpected_BinaryMessage_OnceOnly() throws Exception { + public void serverOnMessage_ReactsToClient_RealBinaryMessage_AndRespondsWithExpected_BinaryMessage_OnceOnly() + throws Exception { final StubsClientWebSocket socket = new StubsClientWebSocket(1); final ClientUpgradeRequest clientUpgradeRequest = new ClientUpgradeRequest(); @@ -267,7 +294,8 @@ public void serverOnMessage_ReactsToClient_RealBinaryMessage_AndRespondsWithExpe } @Test - public void serverOnMessage_ReactsToClient_TextBinaryMessage_AndRespondsWithExpected_BinaryMessage_OnceOnly() throws Exception { + public void serverOnMessage_ReactsToClient_TextBinaryMessage_AndRespondsWithExpected_BinaryMessage_OnceOnly() + throws Exception { final StubsClientWebSocket socket = new StubsClientWebSocket(1); final ClientUpgradeRequest clientUpgradeRequest = new ClientUpgradeRequest(); @@ -278,7 +306,8 @@ public void serverOnMessage_ReactsToClient_TextBinaryMessage_AndRespondsWithExpe final Future sessionFuture = client.connect(socket, REQUEST_URL_HELLO_4, clientUpgradeRequest); final Session session = sessionFuture.get(500, TimeUnit.MILLISECONDS); - final URL resource = StubsPortalHttp11WebSocketOverTlsTests.class.getResource("/json/response/json_response_6.json"); + final URL resource = + StubsPortalHttp11WebSocketOverTlsTests.class.getResource("/json/response/json_response_6.json"); final Path path = Paths.get(resource.toURI()); final byte[] payloadBytes = FileUtils.fileToBytes(path.toFile()); @@ -311,7 +340,8 @@ public void serverOnMessage_RespondsWithExpected_TextMessage_OnceOnly() throws E // Wait for client to get all the messages from the server socket.awaitCountDownLatchWithAssertion(); assertThat(socket.receivedOnMessageText.size()).isEqualTo(2); - assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")).isTrue(); + assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")) + .isTrue(); assertThat(socket.receivedOnMessageText.contains("bye-bye")).isTrue(); } @@ -332,7 +362,8 @@ public void serverOnMessage_RespondsWithExpected_TextMessage_ContinuousPush() th // Wait for client to get all the messages from the server socket.awaitCountDownLatchWithAssertion(); assertThat(socket.receivedOnMessageText.size()).isEqualTo(5); - assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")).isTrue(); + assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")) + .isTrue(); socket.receivedOnMessageText.remove("You have been successfully connected"); assertThat(socket.receivedOnMessageText.get(0)).isEqualTo("pushing"); @@ -358,7 +389,8 @@ public void serverOnMessage_RespondsWithExpected_BinaryMessage_OnceOnly() throws // Wait for client to get all the messages from the server socket.awaitCountDownLatchWithAssertion(); assertThat(socket.receivedOnMessageText.size()).isEqualTo(1); - assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")).isTrue(); + assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")) + .isTrue(); assertThat(socket.receivedOnMessageBytes.size()).isEqualTo(1); @@ -387,7 +419,8 @@ public void serverOnMessage_RespondsWithExpected_BinaryMessage_ContinuousPush() // Wait for client to get all the messages from the server socket.awaitCountDownLatchWithAssertion(); assertThat(socket.receivedOnMessageText.size()).isEqualTo(1); - assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")).isTrue(); + assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")) + .isTrue(); assertThat(socket.receivedOnMessageBytes.size()).isEqualTo(4); final InputStream binaryDataInputStream = readResourceAsInputStream("/binary/hello-world.pdf"); @@ -416,7 +449,8 @@ public void serverOnMessage_RespondsWithExpected_TextMessage_OnceOnly_And_Discon // Wait for client to get all the messages from the server socket.awaitCountDownLatchWithAssertion(); assertThat(socket.receivedOnMessageText.size()).isEqualTo(2); - assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")).isTrue(); + assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")) + .isTrue(); assertThat(socket.receivedOnMessageText.contains("bon-voyage")).isTrue(); assertThat(socket.receivedOnCloseText.size()).isEqualTo(1); @@ -573,7 +607,8 @@ public void webSocketProtocol_jettySanityCheck_jettyRespondsWithExpected_PongWit } @Test - @PotentiallyFlaky("This test can potentially can affect other tests because it closes the socket, something weird is happening under the hood, investigate later...") + @PotentiallyFlaky( + "This test can potentially can affect other tests because it closes the socket, something weird is happening under the hood, investigate later...") public void webSocketProtocol_jettySanityCheck_jettyShouldDisconnect_WhenClientClosesSocket() throws Exception { // This test makes sure that stubby4j did not mess up default Jetty // behavior that conforms to the RFC of the Web Socket protocol: @@ -620,9 +655,7 @@ public StubsClientWebSocket(final int numberOfExpectedMessages) { } @OnWebSocketConnect - public void onWebSocketConnect(final Session session) { - - } + public void onWebSocketConnect(final Session session) {} @OnWebSocketFrame public void onOnWebSocketFrame(final Frame frame) throws IOException { @@ -670,9 +703,7 @@ public void onWebSocketClose(int statusCode, String reason) { } @OnWebSocketError - public void onWebSocketError(Throwable cause) { - - } + public void onWebSocketError(Throwable cause) {} public void awaitCountDownLatchWithAssertion() throws InterruptedException { assertThat(this.countDownLatch.await(3, TimeUnit.SECONDS)).isTrue(); diff --git a/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp11WebSocketTests.java b/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp11WebSocketTests.java index 01ccccfdd..5e39f2c78 100644 --- a/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp11WebSocketTests.java +++ b/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp11WebSocketTests.java @@ -1,5 +1,26 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.HttpClientUtils.jettyHttpClientOnHttp11; +import static io.github.azagniotov.stubby4j.server.websocket.StubsServerWebSocket.EMPTY_BYTE_BUFFER; +import static org.junit.Assert.assertThrows; + import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.client.StubbyClient; import io.github.azagniotov.stubby4j.client.StubbyResponse; @@ -7,6 +28,20 @@ import io.github.azagniotov.stubby4j.utils.FileUtils; import io.github.azagniotov.stubby4j.utils.NetworkPortUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.WebSocketBehavior; @@ -29,26 +64,6 @@ import org.junit.Test; import org.junit.runners.MethodSorters; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URL; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.HttpClientUtils.jettyHttpClientOnHttp11; -import static io.github.azagniotov.stubby4j.server.websocket.StubsServerWebSocket.EMPTY_BYTE_BUFFER; -import static org.junit.Assert.assertThrows; - // There are jetty specific tests that I want to run last, hence the MethodSorters.NAME_ASCENDING, // since one of the tests will close the server websocket and stubby4j will have to be restarted. // Normally, it is a bad practice to have some interdependency in tests and should be avoided. @@ -63,14 +78,22 @@ public class StubsPortalHttp11WebSocketTests { private static final String ADMIN_URL = String.format("http://localhost:%s", ADMIN_PORT); private static final String WEBSOCKET_ROOT_PATH_URL = String.format("ws://localhost:%s/ws", STUBS_PORT); - private static final URI REQUEST_URL_HELLO_1 = URI.create(String.format("%s%s", WEBSOCKET_ROOT_PATH_URL, "/demo/hello/1")); - private static final URI REQUEST_URL_HELLO_2 = URI.create(String.format("%s%s", WEBSOCKET_ROOT_PATH_URL, "/demo/hello/2")); - private static final URI REQUEST_URL_HELLO_3 = URI.create(String.format("%s%s", WEBSOCKET_ROOT_PATH_URL, "/demo/hello/3")); - private static final URI REQUEST_URL_HELLO_4 = URI.create(String.format("%s%s", WEBSOCKET_ROOT_PATH_URL, "/demo/hello/4")); - private static final URI REQUEST_URL_HELLO_5 = URI.create(String.format("%s%s", WEBSOCKET_ROOT_PATH_URL, "/demo/hello/5")); - private static final URI REQUEST_URL_HELLO_6 = URI.create(String.format("%s%s", WEBSOCKET_ROOT_PATH_URL, "/demo/hello/6")); - private static final URI REQUEST_URL_HELLO_7 = URI.create(String.format("%s%s", WEBSOCKET_ROOT_PATH_URL, "/demo/hello/7")); - private static final URI NON_STUBBED_REQUEST_URL = URI.create(String.format("%s%s", WEBSOCKET_ROOT_PATH_URL, "/blah")); + private static final URI REQUEST_URL_HELLO_1 = + URI.create(String.format("%s%s", WEBSOCKET_ROOT_PATH_URL, "/demo/hello/1")); + private static final URI REQUEST_URL_HELLO_2 = + URI.create(String.format("%s%s", WEBSOCKET_ROOT_PATH_URL, "/demo/hello/2")); + private static final URI REQUEST_URL_HELLO_3 = + URI.create(String.format("%s%s", WEBSOCKET_ROOT_PATH_URL, "/demo/hello/3")); + private static final URI REQUEST_URL_HELLO_4 = + URI.create(String.format("%s%s", WEBSOCKET_ROOT_PATH_URL, "/demo/hello/4")); + private static final URI REQUEST_URL_HELLO_5 = + URI.create(String.format("%s%s", WEBSOCKET_ROOT_PATH_URL, "/demo/hello/5")); + private static final URI REQUEST_URL_HELLO_6 = + URI.create(String.format("%s%s", WEBSOCKET_ROOT_PATH_URL, "/demo/hello/6")); + private static final URI REQUEST_URL_HELLO_7 = + URI.create(String.format("%s%s", WEBSOCKET_ROOT_PATH_URL, "/demo/hello/7")); + private static final URI NON_STUBBED_REQUEST_URL = + URI.create(String.format("%s%s", WEBSOCKET_ROOT_PATH_URL, "/blah")); private static WebSocketClient client; @@ -81,7 +104,8 @@ public static void beforeClass() throws Exception { ANSITerminal.muteConsole(true); - final URL url = StubsPortalHttp11WebSocketTests.class.getResource("/yaml/main-test-stubs-with-web-socket-config.yaml"); + final URL url = + StubsPortalHttp11WebSocketTests.class.getResource("/yaml/main-test-stubs-with-web-socket-config.yaml"); assert url != null; final InputStream stubsDataInputStream = url.openStream(); @@ -93,7 +117,8 @@ public static void beforeClass() throws Exception { // WebSocket Bootstrap from HTTP/2 (RFC8441) not supported in Jetty 9.x // https://github.com/eclipse/jetty.project/blob/f86a719bce89844337e4f2bde68e8e147095ed80/jetty-websocket/websocket-server/src/main/java/org/eclipse/jetty/websocket/server/WebSocketServerFactory.java#L585 // - // Also, they added WebSocket Bootstrap from HTTP/2 (RFC8441) only in Jetty 10.x.x: https://github.com/eclipse/jetty.project/pull/3740 + // Also, they added WebSocket Bootstrap from HTTP/2 (RFC8441) only in Jetty 10.x.x: + // https://github.com/eclipse/jetty.project/pull/3740 STUBBY_CLIENT.startJetty(STUBS_PORT, STUBS_SSL_PORT, ADMIN_PORT, JettyFactory.DEFAULT_HOST, url.getFile(), ""); client = new WebSocketClient(jettyHttpClientOnHttp11()); @@ -161,7 +186,8 @@ public void serverOnOpen_SendsExpected_TextMessage() throws Exception { // Wait for client to get all the messages from the server socket.awaitCountDownLatchWithAssertion(); assertThat(socket.receivedOnMessageText.size()).isEqualTo(1); - assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")).isTrue(); + assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")) + .isTrue(); } @Test @@ -236,7 +262,8 @@ public void serverOnOpen_RespondsWithExpected_ContinuousPing() throws Exception } @Test - public void serverOnMessage_ReactsToClient_RealBinaryMessage_AndRespondsWithExpected_BinaryMessage_OnceOnly() throws Exception { + public void serverOnMessage_ReactsToClient_RealBinaryMessage_AndRespondsWithExpected_BinaryMessage_OnceOnly() + throws Exception { final StubsClientWebSocket socket = new StubsClientWebSocket(1); final ClientUpgradeRequest clientUpgradeRequest = new ClientUpgradeRequest(); @@ -264,7 +291,8 @@ public void serverOnMessage_ReactsToClient_RealBinaryMessage_AndRespondsWithExpe } @Test - public void serverOnMessage_ReactsToClient_TextBinaryMessage_AndRespondsWithExpected_BinaryMessage_OnceOnly() throws Exception { + public void serverOnMessage_ReactsToClient_TextBinaryMessage_AndRespondsWithExpected_BinaryMessage_OnceOnly() + throws Exception { final StubsClientWebSocket socket = new StubsClientWebSocket(1); final ClientUpgradeRequest clientUpgradeRequest = new ClientUpgradeRequest(); @@ -308,7 +336,8 @@ public void serverOnMessage_RespondsWithExpected_TextMessage_OnceOnly() throws E // Wait for client to get all the messages from the server socket.awaitCountDownLatchWithAssertion(); assertThat(socket.receivedOnMessageText.size()).isEqualTo(2); - assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")).isTrue(); + assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")) + .isTrue(); assertThat(socket.receivedOnMessageText.contains("bye-bye")).isTrue(); } @@ -329,7 +358,8 @@ public void serverOnMessage_RespondsWithExpected_TextMessage_ContinuousPush() th // Wait for client to get all the messages from the server socket.awaitCountDownLatchWithAssertion(); assertThat(socket.receivedOnMessageText.size()).isEqualTo(5); - assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")).isTrue(); + assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")) + .isTrue(); socket.receivedOnMessageText.remove("You have been successfully connected"); assertThat(socket.receivedOnMessageText.get(0)).isEqualTo("pushing"); @@ -355,7 +385,8 @@ public void serverOnMessage_RespondsWithExpected_BinaryMessage_OnceOnly() throws // Wait for client to get all the messages from the server socket.awaitCountDownLatchWithAssertion(); assertThat(socket.receivedOnMessageText.size()).isEqualTo(1); - assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")).isTrue(); + assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")) + .isTrue(); assertThat(socket.receivedOnMessageBytes.size()).isEqualTo(1); @@ -384,7 +415,8 @@ public void serverOnMessage_RespondsWithExpected_BinaryMessage_ContinuousPush() // Wait for client to get all the messages from the server socket.awaitCountDownLatchWithAssertion(); assertThat(socket.receivedOnMessageText.size()).isEqualTo(1); - assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")).isTrue(); + assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")) + .isTrue(); assertThat(socket.receivedOnMessageBytes.size()).isEqualTo(4); final InputStream binaryDataInputStream = readResourceAsInputStream("/binary/hello-world.pdf"); @@ -397,31 +429,31 @@ public void serverOnMessage_RespondsWithExpected_BinaryMessage_ContinuousPush() assertThat(socket.receivedOnMessageBytes.get(3)).isEqualTo(expectedBytes); } -// @Test -// public void serverOnMessage_RespondsWithExpected_TextMessage_OnceOnly_And_Disconnects() throws Exception { -// final StubsClientWebSocket socket = new StubsClientWebSocket(3); -// final ClientUpgradeRequest clientUpgradeRequest = new ClientUpgradeRequest(); -// clientUpgradeRequest.setRequestURI(REQUEST_URL_HELLO_1); -// clientUpgradeRequest.setLocalEndpoint(socket); -// clientUpgradeRequest.setSubProtocols("echo", "mamba"); -// -// final Future sessionFuture = client.connect(socket, REQUEST_URL_HELLO_1, clientUpgradeRequest); -// final Session session = sessionFuture.get(500, TimeUnit.MILLISECONDS); -// -// session.getRemote().sendString("disconnect with a message"); -// -// // Wait for client to get all the messages from the server -// socket.awaitCountDownLatchWithAssertion(); -// assertThat(socket.receivedOnMessageText.size()).isEqualTo(2); -// assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")).isTrue(); -// assertThat(socket.receivedOnMessageText.contains("bon-voyage")).isTrue(); -// -// assertThat(socket.receivedOnCloseText.size()).isEqualTo(1); -// assertThat(socket.receivedOnCloseText.contains("bye")).isTrue(); -// -// assertThat(socket.receivedOnCloseStatus.size()).isEqualTo(1); -// assertThat(socket.receivedOnCloseStatus.contains(StatusCode.NORMAL)).isTrue(); -// } + // @Test + // public void serverOnMessage_RespondsWithExpected_TextMessage_OnceOnly_And_Disconnects() throws Exception { + // final StubsClientWebSocket socket = new StubsClientWebSocket(3); + // final ClientUpgradeRequest clientUpgradeRequest = new ClientUpgradeRequest(); + // clientUpgradeRequest.setRequestURI(REQUEST_URL_HELLO_1); + // clientUpgradeRequest.setLocalEndpoint(socket); + // clientUpgradeRequest.setSubProtocols("echo", "mamba"); + // + // final Future sessionFuture = client.connect(socket, REQUEST_URL_HELLO_1, clientUpgradeRequest); + // final Session session = sessionFuture.get(500, TimeUnit.MILLISECONDS); + // + // session.getRemote().sendString("disconnect with a message"); + // + // // Wait for client to get all the messages from the server + // socket.awaitCountDownLatchWithAssertion(); + // assertThat(socket.receivedOnMessageText.size()).isEqualTo(2); + // assertThat(socket.receivedOnMessageText.contains("You have been successfully connected")).isTrue(); + // assertThat(socket.receivedOnMessageText.contains("bon-voyage")).isTrue(); + // + // assertThat(socket.receivedOnCloseText.size()).isEqualTo(1); + // assertThat(socket.receivedOnCloseText.contains("bye")).isTrue(); + // + // assertThat(socket.receivedOnCloseStatus.size()).isEqualTo(1); + // assertThat(socket.receivedOnCloseStatus.contains(StatusCode.NORMAL)).isTrue(); + // } @Test public void serverOnMessage_RespondsWithExpected_BinaryMessage_FragmentedFrames() throws Exception { @@ -589,9 +621,7 @@ public StubsClientWebSocket(final int numberOfExpectedMessages) { } @OnWebSocketConnect - public void onWebSocketConnect(final Session session) { - - } + public void onWebSocketConnect(final Session session) {} @OnWebSocketFrame public void onOnWebSocketFrame(final Frame frame) throws IOException { @@ -639,9 +669,7 @@ public void onWebSocketClose(int statusCode, String reason) { } @OnWebSocketError - public void onWebSocketError(Throwable cause) { - - } + public void onWebSocketError(Throwable cause) {} public void awaitCountDownLatchWithAssertion() throws InterruptedException { assertThat(this.countDownLatch.await(3, TimeUnit.SECONDS)).isTrue(); diff --git a/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp20ClearTextTests.java b/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp20ClearTextTests.java index 777e45517..3228fb212 100644 --- a/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp20ClearTextTests.java +++ b/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp20ClearTextTests.java @@ -1,11 +1,39 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.HttpClientUtils.jettyHttpClientOnHttp20; + import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.client.StubbyClient; import io.github.azagniotov.stubby4j.client.StubbyResponse; import io.github.azagniotov.stubby4j.server.JettyFactory; import io.github.azagniotov.stubby4j.utils.NetworkPortUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Phaser; +import java.util.concurrent.TimeUnit; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.http.HttpFields; @@ -32,19 +60,6 @@ import org.junit.BeforeClass; import org.junit.Test; -import java.io.InputStream; -import java.net.InetSocketAddress; -import java.net.URL; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.StandardCharsets; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Phaser; -import java.util.concurrent.TimeUnit; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.HttpClientUtils.jettyHttpClientOnHttp20; - public class StubsPortalHttp20ClearTextTests { private static final StubbyClient STUBBY_CLIENT = new StubbyClient(); @@ -69,9 +84,16 @@ public static void beforeClass() throws Exception { stubsData = StringUtils.inputStreamToString(stubsDataInputStream); stubsDataInputStream.close(); - STUBBY_CLIENT.startJetty(STUBS_PORT, STUBS_SSL_PORT, ADMIN_PORT, JettyFactory.DEFAULT_HOST, url.getFile(), "--enable_tls_with_alpn_and_http_2"); + STUBBY_CLIENT.startJetty( + STUBS_PORT, + STUBS_SSL_PORT, + ADMIN_PORT, + JettyFactory.DEFAULT_HOST, + url.getFile(), + "--enable_tls_with_alpn_and_http_2"); - final URL jsonContentUrl = StubsPortalHttp20ClearTextTests.class.getResource("/json/response/json_response_1.json"); + final URL jsonContentUrl = + StubsPortalHttp20ClearTextTests.class.getResource("/json/response/json_response_1.json"); assertThat(jsonContentUrl).isNotNull(); expectedContent = StringUtils.inputStreamToString(jsonContentUrl.openStream()); } @@ -107,13 +129,15 @@ public void shouldReturnExpectedResponseWhenGetRequestMadeUsingLowLevelApiOver_H final HttpURI httpURI = new HttpURI("http://" + host + ":" + STUBS_PORT + "/invoice?status=active&type=full"); final FuturePromise sessionPromise = new FuturePromise<>(); - http2Client.connect(new InetSocketAddress(host, STUBS_PORT), new ServerSessionListener.Adapter(), sessionPromise); + http2Client.connect( + new InetSocketAddress(host, STUBS_PORT), new ServerSessionListener.Adapter(), sessionPromise); final Session session = sessionPromise.get(5, TimeUnit.SECONDS); final HttpFields requestFields = new HttpFields(); requestFields.put("User-Agent", http2Client.getClass().getName() + "/" + Jetty.VERSION); - final MetaData.Request metaData = new MetaData.Request(HttpMethod.GET.asString(), httpURI, HttpVersion.HTTP_2, requestFields); + final MetaData.Request metaData = + new MetaData.Request(HttpMethod.GET.asString(), httpURI, HttpVersion.HTTP_2, requestFields); final HeadersFrame headersFrame = new HeadersFrame(metaData, null, true); // A Phaser may be used instead of a CountDownLatch to control a one-shot action serving a @@ -144,7 +168,8 @@ public void onData(final Stream stream, final DataFrame frame, final Callback ca if (!frame.isEndStream()) { // Get the content buffer. final ByteBuffer dataBuffer = frame.getData(); - assertThat(ByteBuffer.wrap(expectedContent.getBytes(StandardCharsets.UTF_8))).isEqualTo(dataBuffer); + assertThat(ByteBuffer.wrap(expectedContent.getBytes(StandardCharsets.UTF_8))) + .isEqualTo(dataBuffer); // Consume the buffer, here - as an example - just log it. final CharBuffer decodedData = StandardCharsets.UTF_8.decode(dataBuffer); @@ -178,11 +203,12 @@ private void makeRequestAndAssert() throws Exception { final HttpClient httpClient = jettyHttpClientOnHttp20(); httpClient.start(); - ContentResponse response = httpClient.newRequest("localhost", STUBS_PORT) + ContentResponse response = httpClient + .newRequest("localhost", STUBS_PORT) .path("/invoice?status=active&type=full") .method(HttpMethod.GET) .scheme(HttpScheme.HTTP.asString()) - //.timeout(5, TimeUnit.SECONDS) + // .timeout(5, TimeUnit.SECONDS) .send(); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK_200); diff --git a/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp20OverTlsWithAlpnProtocolTests.java b/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp20OverTlsWithAlpnProtocolTests.java index 38b775052..b791a7775 100644 --- a/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp20OverTlsWithAlpnProtocolTests.java +++ b/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalHttp20OverTlsWithAlpnProtocolTests.java @@ -1,5 +1,28 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.HttpClientUtils.jettyClientSslContextFactory; +import static io.github.azagniotov.stubby4j.HttpClientUtils.jettyHttpClientOnHttp20WithClientSsl; +import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.TLS_v1_2; +import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.TLS_v1_3; +import static java.util.Arrays.asList; + import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.client.StubbyClient; import io.github.azagniotov.stubby4j.client.StubbyResponse; @@ -7,6 +30,16 @@ import io.github.azagniotov.stubby4j.server.ssl.SslUtils; import io.github.azagniotov.stubby4j.utils.NetworkPortUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.StandardCharsets; +import java.util.HashSet; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Phaser; +import java.util.concurrent.TimeUnit; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.http.HttpFields; @@ -34,24 +67,6 @@ import org.junit.BeforeClass; import org.junit.Test; -import java.io.InputStream; -import java.net.InetSocketAddress; -import java.net.URL; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.StandardCharsets; -import java.util.HashSet; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Phaser; -import java.util.concurrent.TimeUnit; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.HttpClientUtils.jettyClientSslContextFactory; -import static io.github.azagniotov.stubby4j.HttpClientUtils.jettyHttpClientOnHttp20WithClientSsl; -import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.TLS_v1_2; -import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.TLS_v1_3; -import static java.util.Arrays.asList; - public class StubsPortalHttp20OverTlsWithAlpnProtocolTests { private static final StubbyClient STUBBY_CLIENT = new StubbyClient(); @@ -76,9 +91,16 @@ public static void beforeClass() throws Exception { stubsData = StringUtils.inputStreamToString(stubsDataInputStream); stubsDataInputStream.close(); - STUBBY_CLIENT.startJetty(STUBS_PORT, STUBS_SSL_PORT, ADMIN_PORT, JettyFactory.DEFAULT_HOST, url.getFile(), "--enable_tls_with_alpn_and_http_2"); + STUBBY_CLIENT.startJetty( + STUBS_PORT, + STUBS_SSL_PORT, + ADMIN_PORT, + JettyFactory.DEFAULT_HOST, + url.getFile(), + "--enable_tls_with_alpn_and_http_2"); - final URL jsonContentUrl = StubsPortalHttp20OverTlsWithAlpnProtocolTests.class.getResource("/json/response/json_response_1.json"); + final URL jsonContentUrl = + StubsPortalHttp20OverTlsWithAlpnProtocolTests.class.getResource("/json/response/json_response_1.json"); assertThat(jsonContentUrl).isNotNull(); expectedContent = StringUtils.inputStreamToString(jsonContentUrl.openStream()); } @@ -116,7 +138,8 @@ public void shouldReturnExpectedResponseWhenHttp2GetRequestMadeOnOverTlsWithAlpn } @Test - public void shouldReturnExpectedResponseUsingLowLevelHttp2ClientApiOverTlsWithAlpn_TlsVersion_1_3() throws Exception { + public void shouldReturnExpectedResponseUsingLowLevelHttp2ClientApiOverTlsWithAlpn_TlsVersion_1_3() + throws Exception { final SslContextFactory sslContextFactory = jettyClientSslContextFactory(TLS_v1_3); final HTTP2Client http2Client = new HTTP2Client(); @@ -124,16 +147,22 @@ public void shouldReturnExpectedResponseUsingLowLevelHttp2ClientApiOverTlsWithAl http2Client.start(); final String host = "localhost"; - final HttpURI httpURI = new HttpURI("https://" + host + ":" + STUBS_SSL_PORT + "/invoice?status=active&type=full"); + final HttpURI httpURI = + new HttpURI("https://" + host + ":" + STUBS_SSL_PORT + "/invoice?status=active&type=full"); final FuturePromise sessionPromise = new FuturePromise<>(); - http2Client.connect(sslContextFactory, new InetSocketAddress(host, STUBS_SSL_PORT), new ServerSessionListener.Adapter(), sessionPromise); + http2Client.connect( + sslContextFactory, + new InetSocketAddress(host, STUBS_SSL_PORT), + new ServerSessionListener.Adapter(), + sessionPromise); final Session session = sessionPromise.get(5, TimeUnit.SECONDS); final HttpFields requestFields = new HttpFields(); requestFields.put("User-Agent", http2Client.getClass().getName() + "/" + Jetty.VERSION); - final MetaData.Request metaData = new MetaData.Request(HttpMethod.GET.asString(), httpURI, HttpVersion.HTTP_2, requestFields); + final MetaData.Request metaData = + new MetaData.Request(HttpMethod.GET.asString(), httpURI, HttpVersion.HTTP_2, requestFields); final HeadersFrame headersFrame = new HeadersFrame(metaData, null, true); // A Phaser may be used instead of a CountDownLatch to control a one-shot action serving a @@ -164,7 +193,8 @@ public void onData(final Stream stream, final DataFrame frame, final Callback ca if (!frame.isEndStream()) { // Get the content buffer. final ByteBuffer dataBuffer = frame.getData(); - assertThat(ByteBuffer.wrap(expectedContent.getBytes(StandardCharsets.UTF_8))).isEqualTo(dataBuffer); + assertThat(ByteBuffer.wrap(expectedContent.getBytes(StandardCharsets.UTF_8))) + .isEqualTo(dataBuffer); // Consume the buffer, here - as an example - just log it. final CharBuffer decodedData = StandardCharsets.UTF_8.decode(dataBuffer); @@ -198,11 +228,12 @@ private void makeRequestAndAssert(final String tlsProtocol) throws Exception { final HttpClient httpClient = jettyHttpClientOnHttp20WithClientSsl(tlsProtocol); httpClient.start(); - ContentResponse response = httpClient.newRequest("localhost", STUBS_SSL_PORT) + ContentResponse response = httpClient + .newRequest("localhost", STUBS_SSL_PORT) .path("/invoice?status=active&type=full") .method(HttpMethod.GET) .scheme(HttpScheme.HTTPS.asString()) - //.timeout(5, TimeUnit.SECONDS) + // .timeout(5, TimeUnit.SECONDS) .send(); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK_200); diff --git a/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalRaisedIssueTests.java b/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalRaisedIssueTests.java index 2b821536b..d42a6fb93 100644 --- a/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalRaisedIssueTests.java +++ b/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalRaisedIssueTests.java @@ -1,5 +1,25 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.common.Common.HEADER_APPLICATION_JSON; +import static io.github.azagniotov.stubby4j.common.Common.HEADER_APPLICATION_XML; + import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpMethods; import com.google.api.client.http.HttpRequest; @@ -10,6 +30,8 @@ import io.github.azagniotov.stubby4j.http.HttpMethodExtended; import io.github.azagniotov.stubby4j.utils.NetworkPortUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; +import java.io.InputStream; +import java.net.URL; import org.eclipse.jetty.http.HttpStatus; import org.junit.After; import org.junit.AfterClass; @@ -19,13 +41,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import java.io.InputStream; -import java.net.URL; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.common.Common.HEADER_APPLICATION_JSON; -import static io.github.azagniotov.stubby4j.common.Common.HEADER_APPLICATION_XML; - public class StubsPortalRaisedIssueTests { private static final int STUBS_PORT = NetworkPortUtils.findAvailableTcpPort(); @@ -79,7 +94,8 @@ public void stubby4jIssue29() throws Exception { //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Making request#1 which matches rule_2 ONLY, this will cache stub for rule_2 by the above requestUrl //////////////////////////////////////////////////////////////////////////////////////////////////////////// - final String contentOne = "ALEX-1ALEX-2ALEX-3"; + final String contentOne = + "ALEX-1ALEX-2ALEX-3"; final HttpRequest requestOne = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, contentOne); requestOne.setHeaders(httpHeaders); @@ -92,9 +108,11 @@ public void stubby4jIssue29() throws Exception { final String responseContentOne = responseOne.parseAsString().trim(); - final URL xmlActualContentResourceOne = StubsPortalRaisedIssueTests.class.getResource("/xml/response/xml_response_2.xml"); + final URL xmlActualContentResourceOne = + StubsPortalRaisedIssueTests.class.getResource("/xml/response/xml_response_2.xml"); assertThat(xmlActualContentResourceOne).isNotNull(); - final String expectedResponseContentOne = StringUtils.inputStreamToString(xmlActualContentResourceOne.openStream()); + final String expectedResponseContentOne = + StringUtils.inputStreamToString(xmlActualContentResourceOne.openStream()); assertThat(responseContentOne).isEqualTo(expectedResponseContentOne); @@ -102,7 +120,8 @@ public void stubby4jIssue29() throws Exception { // Making request#2 which matches rule_1 AND rule_2. But, in this case, // we are expecting rule_1 as a response, because the rule_1 is defined earlier than rule_2 //////////////////////////////////////////////////////////////////////////////////////////////////////////// - final URL xmlContentResourceTwo = StubsPortalRaisedIssueTests.class.getResource("/xml/request/xml_payload_3.xml"); + final URL xmlContentResourceTwo = + StubsPortalRaisedIssueTests.class.getResource("/xml/request/xml_payload_3.xml"); assertThat(xmlContentResourceTwo).isNotNull(); final String contentTwo = StringUtils.inputStreamToString(xmlContentResourceTwo.openStream()); @@ -117,9 +136,11 @@ public void stubby4jIssue29() throws Exception { final String responseContentTwo = responseTwo.parseAsString().trim(); - final URL xmlActualContentResourceTwo = StubsPortalRaisedIssueTests.class.getResource("/xml/response/xml_response_1.xml"); + final URL xmlActualContentResourceTwo = + StubsPortalRaisedIssueTests.class.getResource("/xml/response/xml_response_1.xml"); assertThat(xmlActualContentResourceTwo).isNotNull(); - final String expectedResponseContentTwo = StringUtils.inputStreamToString(xmlActualContentResourceTwo.openStream()); + final String expectedResponseContentTwo = + StringUtils.inputStreamToString(xmlActualContentResourceTwo.openStream()); assertThat(responseContentTwo).isEqualTo(expectedResponseContentTwo); } @@ -132,7 +153,8 @@ public void stubby4jIssue29_VanillaRegex() throws Exception { httpHeaders.setContentType(HEADER_APPLICATION_XML); // The '?' in ALEX-1ALEX-2ALEX-3"; + final String contentOne = + "ALEX-1ALEX-2ALEX-3"; final HttpRequest requestOne = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, contentOne); requestOne.setHeaders(httpHeaders); @@ -145,9 +167,11 @@ public void stubby4jIssue29_VanillaRegex() throws Exception { final String responseContentOne = responseOne.parseAsString().trim(); - final URL xmlActualContentResourceOne = StubsPortalRaisedIssueTests.class.getResource("/xml/response/xml_response_2.xml"); + final URL xmlActualContentResourceOne = + StubsPortalRaisedIssueTests.class.getResource("/xml/response/xml_response_2.xml"); assertThat(xmlActualContentResourceOne).isNotNull(); - final String expectedResponseContentOne = StringUtils.inputStreamToString(xmlActualContentResourceOne.openStream()); + final String expectedResponseContentOne = + StringUtils.inputStreamToString(xmlActualContentResourceOne.openStream()); assertThat(responseContentOne).isEqualTo(expectedResponseContentOne); } @@ -162,7 +186,8 @@ public void stubby4jIssue29_VanillaComplexRegex() throws Exception { // Note: // 1. the '?' in are escaped as these are regex characters - final URL xmlContentUrl = StubsPortalRaisedIssueTests.class.getResource("/xml/request/xml_request_issue_29_payload.xml"); + final URL xmlContentUrl = + StubsPortalRaisedIssueTests.class.getResource("/xml/request/xml_request_issue_29_payload.xml"); assertThat(xmlContentUrl).isNotNull(); final String payloadContent = StringUtils.inputStreamToString(xmlContentUrl.openStream()); @@ -173,13 +198,16 @@ public void stubby4jIssue29_VanillaComplexRegex() throws Exception { final HttpHeaders httpResponseHeaders = httpResponse.getHeaders(); assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.CREATED_201); - assertThat(httpResponseHeaders.getContentType().contains(HEADER_APPLICATION_XML)).isTrue(); + assertThat(httpResponseHeaders.getContentType().contains(HEADER_APPLICATION_XML)) + .isTrue(); final String responseContentOne = httpResponse.parseAsString().trim(); - final URL xmlActualContentResourceOne = StubsPortalRaisedIssueTests.class.getResource("/xml/response/xml_response_issue_29_body.xml"); + final URL xmlActualContentResourceOne = + StubsPortalRaisedIssueTests.class.getResource("/xml/response/xml_response_issue_29_body.xml"); assertThat(xmlActualContentResourceOne).isNotNull(); - final String expectedResponseContentOne = StringUtils.inputStreamToString(xmlActualContentResourceOne.openStream()); + final String expectedResponseContentOne = + StringUtils.inputStreamToString(xmlActualContentResourceOne.openStream()); assertThat(responseContentOne).isEqualTo(expectedResponseContentOne); } @@ -194,7 +222,8 @@ public void stubby4jIssue93_WithRequestFilePayloadWithoutResponseBody() throws E assertThat(jsonContentUrl).isNotNull(); final String content = StringUtils.inputStreamToString(jsonContentUrl.openStream()); - final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethodExtended.PATCH.asString(), requestUrl, content); + final HttpRequest request = + HttpUtils.constructHttpRequest(HttpMethodExtended.PATCH.asString(), requestUrl, content); final HttpResponse response = request.execute(); final HttpHeaders headers = response.getHeaders(); @@ -211,7 +240,8 @@ public void stubby4jIssue93_WithRequestBodyPayloadWithoutResponseBody() throws E final String requestUrl = String.format("%s%s", STUBS_URL, "/azagniotov/stubby4j/issues/93"); final String content = "This is a PATCH update"; - final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethodExtended.PATCH.asString(), requestUrl, content); + final HttpRequest request = + HttpUtils.constructHttpRequest(HttpMethodExtended.PATCH.asString(), requestUrl, content); final HttpResponse response = request.execute(); final HttpHeaders headers = response.getHeaders(); @@ -257,8 +287,8 @@ public void stubby4jIssue93_ExtraTest() throws Exception { final HttpResponse responseOne = requestOne.execute(); assertThat(responseOne.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST_400); - assertThat("{\"type\": \"BAD_REQUEST\"}").isEqualTo(responseOne.parseAsString().trim()); - + assertThat("{\"type\": \"BAD_REQUEST\"}") + .isEqualTo(responseOne.parseAsString().trim()); final String contentTwo = "{\"type\": \"HOME\"}"; final HttpRequest requestTwo = HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl, contentTwo); @@ -274,7 +304,8 @@ public void stubby4jIssue171() throws Exception { final String requestUrl = String.format("%s%s", STUBS_URL, "/azagniotov/stubby4j/issues/171"); - final String content = "[{\"application\":{\"Address\":[{\"addressId\":8,\"customerId\":1,\"orderItemId\":3,\"addressType\":\"STMT\",\"city\":\"DOCKLANDS\",\"country\":\"AU\",\"postcode\":\"3008\",\"state\":\"VIC\",\"streetName\":\"Collins\",\"streetNumber\":\"691\",\"streetType\":\"ST\"},{\"addressId\":7,\"customerId\":1,\"addressType\":\"CMAL\",\"city\":\"DOCKLANDS\",\"country\":\"AU\",\"postcode\":\"3008\",\"state\":\"VIC\",\"streetName\":\"Collins\",\"streetNumber\":\"691\",\"streetType\":\"ST\"},{\"addressId\":6,\"customerId\":1,\"addressType\":\"CRES\",\"city\":\"DOCKLANDS\",\"country\":\"AU\",\"postcode\":\"3008\",\"state\":\"VIC\",\"streetName\":\"Collins\",\"streetNumber\":\"691\",\"streetType\":\"ST\"}],\"AppCustRelationship\":[{\"customerId\":1,\"applicationId\":2,\"relationshipType\":\"POW\"}],\"Application\":[{\"applicationId\":2,\"applicationSigned\":false,\"applicationSource\":\"sola\",\"applicationSourceCode\":\"QMV\",\"applicationSourceCountry\":\"AU\",\"applicationVersion\":1,\"basketId\":1,\"bsb\":\"\",\"channel\":\"I\",\"createdDate\":\"2021-01-21T09:57:03+11:00\",\"currencyCode\":\"AUD\",\"modifiedBy\":\"Apply User\",\"orderId\":1000000003}],\"CRNRequest\":[{\"regId\":5,\"customerId\":1,\"orderItemId\":3,\"accessLevel\":\"Full\",\"createNewCRN\":true,\"customerClass\":\"CNE\"}],\"Contact\":[{\"contactId\":4,\"customerId\":1,\"contactType\":\"E\",\"email\":\"test@anz.com\"}],\"CustOrderItemRelationship\":[{\"customerId\":1,\"orderItemId\":3,\"custAcctRelationship\":\"SOL\",\"orderItemFlag\":\"N\"}],\"Customer\":[{\"customerId\":1,\"acceptMarketing\":true,\"AUTaxResidentOnly\":false,\"customerType\":\"IND\",\"depositCustomerType\":\"STD\",\"existingCustomer\":false,\"fullName\":\"Failure Test\",\"ipAddress\":\"\",\"privacyConsent\":true,\"verificationStatus\":\"Verified\"}],\"Deposit\":[{\"orderItemId\":3,\"ATOType\":\"I\",\"numberOfSignatories\":1,\"transactionAccountType\":\"IND\"}],\"Individual\":[{\"customerId\":1,\"dateOfBirth\":\"1981-01-01T00:00:00Z\",\"firstName\":\"Failure\",\"gender\":\"M\",\"lastName\":\"Test\",\"middleName\":\"\",\"title\":\"mr\"}],\"OrderItem\":[{\"orderItemId\":3,\"capProductCode\":\"DDA\",\"capSubProductCode\":\"ED\",\"eStatementEmail\":\"test@anz.com\",\"natureOfProduct\":\"primary\"}]}}]"; + final String content = + "[{\"application\":{\"Address\":[{\"addressId\":8,\"customerId\":1,\"orderItemId\":3,\"addressType\":\"STMT\",\"city\":\"DOCKLANDS\",\"country\":\"AU\",\"postcode\":\"3008\",\"state\":\"VIC\",\"streetName\":\"Collins\",\"streetNumber\":\"691\",\"streetType\":\"ST\"},{\"addressId\":7,\"customerId\":1,\"addressType\":\"CMAL\",\"city\":\"DOCKLANDS\",\"country\":\"AU\",\"postcode\":\"3008\",\"state\":\"VIC\",\"streetName\":\"Collins\",\"streetNumber\":\"691\",\"streetType\":\"ST\"},{\"addressId\":6,\"customerId\":1,\"addressType\":\"CRES\",\"city\":\"DOCKLANDS\",\"country\":\"AU\",\"postcode\":\"3008\",\"state\":\"VIC\",\"streetName\":\"Collins\",\"streetNumber\":\"691\",\"streetType\":\"ST\"}],\"AppCustRelationship\":[{\"customerId\":1,\"applicationId\":2,\"relationshipType\":\"POW\"}],\"Application\":[{\"applicationId\":2,\"applicationSigned\":false,\"applicationSource\":\"sola\",\"applicationSourceCode\":\"QMV\",\"applicationSourceCountry\":\"AU\",\"applicationVersion\":1,\"basketId\":1,\"bsb\":\"\",\"channel\":\"I\",\"createdDate\":\"2021-01-21T09:57:03+11:00\",\"currencyCode\":\"AUD\",\"modifiedBy\":\"Apply User\",\"orderId\":1000000003}],\"CRNRequest\":[{\"regId\":5,\"customerId\":1,\"orderItemId\":3,\"accessLevel\":\"Full\",\"createNewCRN\":true,\"customerClass\":\"CNE\"}],\"Contact\":[{\"contactId\":4,\"customerId\":1,\"contactType\":\"E\",\"email\":\"test@anz.com\"}],\"CustOrderItemRelationship\":[{\"customerId\":1,\"orderItemId\":3,\"custAcctRelationship\":\"SOL\",\"orderItemFlag\":\"N\"}],\"Customer\":[{\"customerId\":1,\"acceptMarketing\":true,\"AUTaxResidentOnly\":false,\"customerType\":\"IND\",\"depositCustomerType\":\"STD\",\"existingCustomer\":false,\"fullName\":\"Failure Test\",\"ipAddress\":\"\",\"privacyConsent\":true,\"verificationStatus\":\"Verified\"}],\"Deposit\":[{\"orderItemId\":3,\"ATOType\":\"I\",\"numberOfSignatories\":1,\"transactionAccountType\":\"IND\"}],\"Individual\":[{\"customerId\":1,\"dateOfBirth\":\"1981-01-01T00:00:00Z\",\"firstName\":\"Failure\",\"gender\":\"M\",\"lastName\":\"Test\",\"middleName\":\"\",\"title\":\"mr\"}],\"OrderItem\":[{\"orderItemId\":3,\"capProductCode\":\"DDA\",\"capSubProductCode\":\"ED\",\"eStatementEmail\":\"test@anz.com\",\"natureOfProduct\":\"primary\"}]}}]"; final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, content); final HttpHeaders httpHeaders = new HttpHeaders(); @@ -297,7 +328,8 @@ public void stubby4jIssue171_WithWrongPayload() throws Exception { final String requestUrl = String.format("%s%s", STUBS_URL, "/azagniotov/stubby4j/issues/171"); // Stubbed RegEx expects JSON key "natureOfProduct" to be present, but it is missing from the POSTed payload - final String content = "[{\"application\":{\"Address\":[{\"addressId\":8,\"customerId\":1,\"orderItemId\":3,\"addressType\":\"STMT\",\"city\":\"DOCKLANDS\",\"country\":\"AU\",\"postcode\":\"3008\",\"state\":\"VIC\",\"streetName\":\"Collins\",\"streetNumber\":\"691\",\"streetType\":\"ST\"},{\"addressId\":7,\"customerId\":1,\"addressType\":\"CMAL\",\"city\":\"DOCKLANDS\",\"country\":\"AU\",\"postcode\":\"3008\",\"state\":\"VIC\",\"streetName\":\"Collins\",\"streetNumber\":\"691\",\"streetType\":\"ST\"},{\"addressId\":6,\"customerId\":1,\"addressType\":\"CRES\",\"city\":\"DOCKLANDS\",\"country\":\"AU\",\"postcode\":\"3008\",\"state\":\"VIC\",\"streetName\":\"Collins\",\"streetNumber\":\"691\",\"streetType\":\"ST\"}],\"AppCustRelationship\":[{\"customerId\":1,\"applicationId\":2,\"relationshipType\":\"POW\"}],\"Application\":[{\"applicationId\":2,\"applicationSigned\":false,\"applicationSource\":\"sola\",\"applicationSourceCode\":\"QMV\",\"applicationSourceCountry\":\"AU\",\"applicationVersion\":1,\"basketId\":1,\"bsb\":\"\",\"channel\":\"I\",\"createdDate\":\"2021-01-21T09:57:03+11:00\",\"currencyCode\":\"AUD\",\"modifiedBy\":\"Apply User\",\"orderId\":1000000003}],\"CRNRequest\":[{\"regId\":5,\"customerId\":1,\"orderItemId\":3,\"accessLevel\":\"Full\",\"createNewCRN\":true,\"customerClass\":\"CNE\"}],\"Contact\":[{\"contactId\":4,\"customerId\":1,\"contactType\":\"E\",\"email\":\"test@anz.com\"}],\"CustOrderItemRelationship\":[{\"customerId\":1,\"orderItemId\":3,\"custAcctRelationship\":\"SOL\",\"orderItemFlag\":\"N\"}],\"Customer\":[{\"customerId\":1,\"acceptMarketing\":true,\"AUTaxResidentOnly\":false,\"customerType\":\"IND\",\"depositCustomerType\":\"STD\",\"existingCustomer\":false,\"fullName\":\"Failure Test\",\"ipAddress\":\"\",\"privacyConsent\":true,\"verificationStatus\":\"Verified\"}],\"Deposit\":[{\"orderItemId\":3,\"ATOType\":\"I\",\"numberOfSignatories\":1,\"transactionAccountType\":\"IND\"}],\"Individual\":[{\"customerId\":1,\"dateOfBirth\":\"1981-01-01T00:00:00Z\",\"firstName\":\"Failure\",\"gender\":\"M\",\"lastName\":\"Test\",\"middleName\":\"\",\"title\":\"mr\"}],\"OrderItem\":[{\"orderItemId\":3,\"capProductCode\":\"DDA\",\"capSubProductCode\":\"ED\",\"eStatementEmail\":\"test@anz.com\"}]}}]"; + final String content = + "[{\"application\":{\"Address\":[{\"addressId\":8,\"customerId\":1,\"orderItemId\":3,\"addressType\":\"STMT\",\"city\":\"DOCKLANDS\",\"country\":\"AU\",\"postcode\":\"3008\",\"state\":\"VIC\",\"streetName\":\"Collins\",\"streetNumber\":\"691\",\"streetType\":\"ST\"},{\"addressId\":7,\"customerId\":1,\"addressType\":\"CMAL\",\"city\":\"DOCKLANDS\",\"country\":\"AU\",\"postcode\":\"3008\",\"state\":\"VIC\",\"streetName\":\"Collins\",\"streetNumber\":\"691\",\"streetType\":\"ST\"},{\"addressId\":6,\"customerId\":1,\"addressType\":\"CRES\",\"city\":\"DOCKLANDS\",\"country\":\"AU\",\"postcode\":\"3008\",\"state\":\"VIC\",\"streetName\":\"Collins\",\"streetNumber\":\"691\",\"streetType\":\"ST\"}],\"AppCustRelationship\":[{\"customerId\":1,\"applicationId\":2,\"relationshipType\":\"POW\"}],\"Application\":[{\"applicationId\":2,\"applicationSigned\":false,\"applicationSource\":\"sola\",\"applicationSourceCode\":\"QMV\",\"applicationSourceCountry\":\"AU\",\"applicationVersion\":1,\"basketId\":1,\"bsb\":\"\",\"channel\":\"I\",\"createdDate\":\"2021-01-21T09:57:03+11:00\",\"currencyCode\":\"AUD\",\"modifiedBy\":\"Apply User\",\"orderId\":1000000003}],\"CRNRequest\":[{\"regId\":5,\"customerId\":1,\"orderItemId\":3,\"accessLevel\":\"Full\",\"createNewCRN\":true,\"customerClass\":\"CNE\"}],\"Contact\":[{\"contactId\":4,\"customerId\":1,\"contactType\":\"E\",\"email\":\"test@anz.com\"}],\"CustOrderItemRelationship\":[{\"customerId\":1,\"orderItemId\":3,\"custAcctRelationship\":\"SOL\",\"orderItemFlag\":\"N\"}],\"Customer\":[{\"customerId\":1,\"acceptMarketing\":true,\"AUTaxResidentOnly\":false,\"customerType\":\"IND\",\"depositCustomerType\":\"STD\",\"existingCustomer\":false,\"fullName\":\"Failure Test\",\"ipAddress\":\"\",\"privacyConsent\":true,\"verificationStatus\":\"Verified\"}],\"Deposit\":[{\"orderItemId\":3,\"ATOType\":\"I\",\"numberOfSignatories\":1,\"transactionAccountType\":\"IND\"}],\"Individual\":[{\"customerId\":1,\"dateOfBirth\":\"1981-01-01T00:00:00Z\",\"firstName\":\"Failure\",\"gender\":\"M\",\"lastName\":\"Test\",\"middleName\":\"\",\"title\":\"mr\"}],\"OrderItem\":[{\"orderItemId\":3,\"capProductCode\":\"DDA\",\"capSubProductCode\":\"ED\",\"eStatementEmail\":\"test@anz.com\"}]}}]"; final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, content); final HttpHeaders httpHeaders = new HttpHeaders(); @@ -387,7 +419,8 @@ public void stubby4jIssue399_VanillaRegex() throws Exception { final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(HEADER_APPLICATION_XML); - final URL jsonContentUrl = StubsPortalRaisedIssueTests.class.getResource("/xml/request/xml_request_issue_399_payload.xml"); + final URL jsonContentUrl = + StubsPortalRaisedIssueTests.class.getResource("/xml/request/xml_request_issue_399_payload.xml"); assertThat(jsonContentUrl).isNotNull(); final String content = StringUtils.inputStreamToString(jsonContentUrl.openStream()); @@ -398,13 +431,16 @@ public void stubby4jIssue399_VanillaRegex() throws Exception { final HttpHeaders httpResponseHeaders = httpResponse.getHeaders(); assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat(httpResponseHeaders.getContentType().contains(HEADER_APPLICATION_XML)).isTrue(); + assertThat(httpResponseHeaders.getContentType().contains(HEADER_APPLICATION_XML)) + .isTrue(); final String httpResponseContent = httpResponse.parseAsString().trim(); - final URL xmlActualContentResourceOne = StubsPortalRaisedIssueTests.class.getResource("/xml/response/xml_response_issue_399_body.xml"); + final URL xmlActualContentResourceOne = + StubsPortalRaisedIssueTests.class.getResource("/xml/response/xml_response_issue_399_body.xml"); assertThat(xmlActualContentResourceOne).isNotNull(); - final String expectedResponseContent = StringUtils.inputStreamToString(xmlActualContentResourceOne.openStream()); + final String expectedResponseContent = + StringUtils.inputStreamToString(xmlActualContentResourceOne.openStream()); assertThat(httpResponseContent).isEqualTo(expectedResponseContent); } @@ -416,7 +452,8 @@ public void stubby4jIssue399_XmlUnit_Matcher() throws Exception { final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(HEADER_APPLICATION_XML); - final URL jsonContentUrl = StubsPortalRaisedIssueTests.class.getResource("/xml/request/xml_request_issue_399_payload.xml"); + final URL jsonContentUrl = + StubsPortalRaisedIssueTests.class.getResource("/xml/request/xml_request_issue_399_payload.xml"); assertThat(jsonContentUrl).isNotNull(); final String content = StringUtils.inputStreamToString(jsonContentUrl.openStream()); @@ -427,11 +464,13 @@ public void stubby4jIssue399_XmlUnit_Matcher() throws Exception { final HttpHeaders httpResponseHeaders = httpResponse.getHeaders(); assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat(httpResponseHeaders.getContentType().contains(HEADER_APPLICATION_XML)).isTrue(); + assertThat(httpResponseHeaders.getContentType().contains(HEADER_APPLICATION_XML)) + .isTrue(); final String httpResponseContent = httpResponse.parseAsString().trim(); - final URL xmlActualContentResource = StubsPortalRaisedIssueTests.class.getResource("/xml/response/xml_response_issue_399_body.xml"); + final URL xmlActualContentResource = + StubsPortalRaisedIssueTests.class.getResource("/xml/response/xml_response_issue_399_body.xml"); assertThat(xmlActualContentResource).isNotNull(); final String expectedResponseContent = StringUtils.inputStreamToString(xmlActualContentResource.openStream()); @@ -445,7 +484,8 @@ public void stubby4jIssue399_XmlUnit_Matcher_WithInlinedPost() throws Exception final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(HEADER_APPLICATION_XML); - final URL jsonContentUrl = StubsPortalRaisedIssueTests.class.getResource("/xml/request/xml_request_issue_399_payload_2.xml"); + final URL jsonContentUrl = + StubsPortalRaisedIssueTests.class.getResource("/xml/request/xml_request_issue_399_payload_2.xml"); assertThat(jsonContentUrl).isNotNull(); final String content = StringUtils.inputStreamToString(jsonContentUrl.openStream()); @@ -456,10 +496,12 @@ public void stubby4jIssue399_XmlUnit_Matcher_WithInlinedPost() throws Exception final HttpHeaders httpResponseHeaders = httpResponse.getHeaders(); assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat(httpResponseHeaders.getContentType().contains(HEADER_APPLICATION_XML)).isTrue(); + assertThat(httpResponseHeaders.getContentType().contains(HEADER_APPLICATION_XML)) + .isTrue(); final String httpResponseContent = httpResponse.parseAsString().trim(); - final String expectedResponseContent = "Captured values are, authority: PIPS with name pid that starts with pid://"; + final String expectedResponseContent = + "Captured values are, authority: PIPS with name pid that starts with pid://"; assertThat(httpResponseContent).isEqualTo(expectedResponseContent); } @@ -468,7 +510,8 @@ public void stubby4jIssue399_XmlUnit_Matcher_WithInlinedPost() throws Exception @Test public void stubby4jStackOverFlowQuestion70417269() throws Exception { - final String requestOneUrl = String.format("%s%s", STUBS_URL, "/stackoverflow/70417269/one-two-five/test?pathid=1,2,5"); + final String requestOneUrl = + String.format("%s%s", STUBS_URL, "/stackoverflow/70417269/one-two-five/test?pathid=1,2,5"); final HttpRequest requestOne = HttpUtils.constructHttpRequest(HttpMethods.GET, requestOneUrl); final HttpResponse responseOne = requestOne.execute(); @@ -479,7 +522,8 @@ public void stubby4jStackOverFlowQuestion70417269() throws Exception { //////////////////////////////////////////////////////////////////////////////////////////////////////////// - final String requestTwoUrl = String.format("%s%s", STUBS_URL, "/stackoverflow/70417269/one-two/test?pathid=1,2"); + final String requestTwoUrl = + String.format("%s%s", STUBS_URL, "/stackoverflow/70417269/one-two/test?pathid=1,2"); final HttpRequest requestTwo = HttpUtils.constructHttpRequest(HttpMethods.GET, requestTwoUrl); final HttpResponse responseTwo = requestTwo.execute(); diff --git a/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalTest.java b/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalTest.java index 53ee72008..b13da0b44 100644 --- a/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalTest.java +++ b/src/functionalTest/java/io/github/azagniotov/stubby4j/StubsPortalTest.java @@ -1,5 +1,26 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.generics.TypeSafeConverter.asCheckedArrayList; +import static io.github.azagniotov.stubby4j.common.Common.HEADER_APPLICATION_JSON; +import static io.github.azagniotov.stubby4j.common.Common.HEADER_APPLICATION_XML; + import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpMethods; import com.google.api.client.http.HttpRequest; @@ -11,6 +32,13 @@ import io.github.azagniotov.stubby4j.utils.FileUtils; import io.github.azagniotov.stubby4j.utils.NetworkPortUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.PrintStream; +import java.net.URL; +import java.net.UnknownHostException; +import java.util.LinkedList; +import java.util.List; import org.eclipse.jetty.http.HttpStatus; import org.junit.After; import org.junit.AfterClass; @@ -20,19 +48,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.PrintStream; -import java.net.URL; -import java.net.UnknownHostException; -import java.util.LinkedList; -import java.util.List; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.generics.TypeSafeConverter.asCheckedArrayList; -import static io.github.azagniotov.stubby4j.common.Common.HEADER_APPLICATION_JSON; -import static io.github.azagniotov.stubby4j.common.Common.HEADER_APPLICATION_XML; - public class StubsPortalTest { // This port needs to be hardcoded due to tests for the: @@ -83,13 +98,15 @@ public void afterEach() throws Exception { @Test public void shouldMatchRequest_WhenStubbedUrlRegexBeginsWith_ButGoodAssertionSent() throws Exception { - //^/resources/asn/.*$ + // ^/resources/asn/.*$ - final List assertingRequests = new LinkedList() {{ - add("/resources/asn/"); - add("/resources/asn/123"); - add("/resources/asn/eew97we9"); - }}; + final List assertingRequests = new LinkedList() { + { + add("/resources/asn/"); + add("/resources/asn/123"); + add("/resources/asn/eew97we9"); + } + }; for (final String assertingRequest : assertingRequests) { @@ -106,13 +123,15 @@ public void shouldMatchRequest_WhenStubbedUrlRegexBeginsWith_ButGoodAssertionSen @Test public void shouldMatchRequest_WhenStubbedUrlRegexified_ButGoodAssertionSent() throws Exception { - //^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+$ + // ^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+$ - final List assertingRequests = new LinkedList() {{ - add("/abc-efg/12/KM/jhgjkhg234234l2"); - add("/abc-efg/12/KM/23423"); - add("/aaa-aaa/00/AA/qwerty"); - }}; + final List assertingRequests = new LinkedList() { + { + add("/abc-efg/12/KM/jhgjkhg234234l2"); + add("/abc-efg/12/KM/23423"); + add("/aaa-aaa/00/AA/qwerty"); + } + }; for (final String assertingRequest : assertingRequests) { @@ -131,11 +150,13 @@ public void shouldMatchRequest_WhenStubbedUrlRegexifiedAndNoStubbedQueryParams() // ^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+\?paramOne=[a-zA-Z]{3,8}¶mTwo=[a-zA-Z]{3,8} - final List assertingRequests = new LinkedList() {{ - add("/abc-efg/12/KM/jhgjkhg234234l2?paramOne=valueOne¶mTwo=valueTwo"); - add("/abc-efg/12/KM/23423?paramOne=aaaBLaH¶mTwo=QWERTYUI"); - add("/aaa-aaa/00/AA/qwerty?paramOne=BLAH¶mTwo=Two"); - }}; + final List assertingRequests = new LinkedList() { + { + add("/abc-efg/12/KM/jhgjkhg234234l2?paramOne=valueOne¶mTwo=valueTwo"); + add("/abc-efg/12/KM/23423?paramOne=aaaBLaH¶mTwo=QWERTYUI"); + add("/aaa-aaa/00/AA/qwerty?paramOne=BLAH¶mTwo=Two"); + } + }; for (final String assertingRequest : assertingRequests) { @@ -152,16 +173,18 @@ public void shouldMatchRequest_WhenStubbedUrlRegexifiedAndNoStubbedQueryParams() @Test public void shouldNotMatchRequest_WhenStubbedUrlRegexified_ButBadAssertionSent() throws Exception { - //^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+$ + // ^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+$ - final List assertingRequests = new LinkedList() {{ - add("/abca-efg/12/KM/jhgjkhg234234l2"); - add("/abcefg/12/KM/23423"); - add("/aaa-aaa/00/Af/qwerty"); - add("/aaa-aaa/00/AA/qwerTy"); - add("/aaa-aaa/009/AA/qwerty"); - add("/AAA-AAA/00/AA/qwerty"); - }}; + final List assertingRequests = new LinkedList() { + { + add("/abca-efg/12/KM/jhgjkhg234234l2"); + add("/abcefg/12/KM/23423"); + add("/aaa-aaa/00/Af/qwerty"); + add("/aaa-aaa/00/AA/qwerTy"); + add("/aaa-aaa/009/AA/qwerty"); + add("/AAA-AAA/00/AA/qwerty"); + } + }; for (final String assertingRequest : assertingRequests) { @@ -174,8 +197,12 @@ public void shouldNotMatchRequest_WhenStubbedUrlRegexified_ButBadAssertionSent() } @Test - public void should_MakeSuccessfulRequest_WhenQueryParamsAreAnArrayWithEscapedSingleQuoteElements() throws Exception { - final String requestUrl = String.format("%s%s", STUBS_URL, "/entity.find.single.quote?type_name=user&client_id=id&client_secret=secret&attributes=[%27id%27,%27uuid%27,%27created%27,%27lastUpdated%27,%27displayName%27,%27email%27,%27givenName%27,%27familyName%27]"); + public void should_MakeSuccessfulRequest_WhenQueryParamsAreAnArrayWithEscapedSingleQuoteElements() + throws Exception { + final String requestUrl = String.format( + "%s%s", + STUBS_URL, + "/entity.find.single.quote?type_name=user&client_id=id&client_secret=secret&attributes=[%27id%27,%27uuid%27,%27created%27,%27lastUpdated%27,%27displayName%27,%27email%27,%27givenName%27,%27familyName%27]"); final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); final HttpResponse response = request.execute(); @@ -187,7 +214,10 @@ public void should_MakeSuccessfulRequest_WhenQueryParamsAreAnArrayWithEscapedSin @Test public void should_MakeSuccessfulRequest_WhenQueryParamValueWithEscapedPlus() throws Exception { - final String requestUrl = String.format("%s%s", STUBS_URL, "/entity.find.spaces.within?key=stalin%2B%2B%2Band%2B%2Btruman%2Bare%2B%2B%2Bbest%2B%2B%2Bbuddies"); + final String requestUrl = String.format( + "%s%s", + STUBS_URL, + "/entity.find.spaces.within?key=stalin%2B%2B%2Band%2B%2Btruman%2Bare%2B%2B%2Bbest%2B%2B%2Bbuddies"); final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); final HttpResponse response = request.execute(); @@ -198,51 +228,71 @@ public void should_MakeSuccessfulRequest_WhenQueryParamValueWithEscapedPlus() th } @Test - public void should_MakeSuccessfulRequest_WhenQueryParamValueWithEscapedPlusWithEscapedSingleQuoteElements() throws Exception { - final String requestUrl = String.format("%s%s", STUBS_URL, "/entity.find.single.quote.spaces.within?key=%5B%27stalin%2B%2B%2Band%2B%2B%2Btruman%27,%27are%2B%2B%2Bbest%2B%2B%2Bfriends%27%5D"); + public void should_MakeSuccessfulRequest_WhenQueryParamValueWithEscapedPlusWithEscapedSingleQuoteElements() + throws Exception { + final String requestUrl = String.format( + "%s%s", + STUBS_URL, + "/entity.find.single.quote.spaces.within?key=%5B%27stalin%2B%2B%2Band%2B%2B%2Btruman%27,%27are%2B%2B%2Bbest%2B%2B%2Bfriends%27%5D"); final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); final HttpResponse response = request.execute(); final String responseContent = response.parseAsString().trim(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"status\": \"hello world with single quote and spaces within\"}").isEqualTo(responseContent); + assertThat("{\"status\": \"hello world with single quote and spaces within\"}") + .isEqualTo(responseContent); } @Test - public void should_MakeSuccessfulRequest_WhenQueryParamValueWithRawPlusWithEscapedSingleQuoteElements() throws Exception { - final String requestUrl = String.format("%s%s", STUBS_URL, "/entity.find.single.quote.spaces.within?key=%5B%27stalin+and+++truman%27,%27are+best++friends%27%5D"); + public void should_MakeSuccessfulRequest_WhenQueryParamValueWithRawPlusWithEscapedSingleQuoteElements() + throws Exception { + final String requestUrl = String.format( + "%s%s", + STUBS_URL, + "/entity.find.single.quote.spaces.within?key=%5B%27stalin+and+++truman%27,%27are+best++friends%27%5D"); final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); final HttpResponse response = request.execute(); final String responseContent = response.parseAsString().trim(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"status\": \"hello world with single quote and spaces within\"}").isEqualTo(responseContent); + assertThat("{\"status\": \"hello world with single quote and spaces within\"}") + .isEqualTo(responseContent); } @Test - public void should_MakeSuccessfulRequest_WhenQueryParamValueWithEmptySpacesWithEscapedSingleQuoteElements() throws Exception { - final String requestUrl = String.format("%s%s", STUBS_URL, "/entity.find.single.quote.spaces.within?key=%5B%27stalin and truman%27,%27are best friends%27%5D"); + public void should_MakeSuccessfulRequest_WhenQueryParamValueWithEmptySpacesWithEscapedSingleQuoteElements() + throws Exception { + final String requestUrl = String.format( + "%s%s", + STUBS_URL, + "/entity.find.single.quote.spaces.within?key=%5B%27stalin and truman%27,%27are best friends%27%5D"); final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); final HttpResponse response = request.execute(); final String responseContent = response.parseAsString().trim(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"status\": \"hello world with single quote and spaces within\"}").isEqualTo(responseContent); + assertThat("{\"status\": \"hello world with single quote and spaces within\"}") + .isEqualTo(responseContent); } @Test - public void should_MakeSuccessfulRequest_WhenQueryParamValueWithEscapedSpacesWithEscapedSingleQuoteElements() throws Exception { - final String requestUrl = String.format("%s%s", STUBS_URL, "/entity.find.single.quote.spaces.within?key=%5B%27stalin%20and%20%20truman%27,%27are%20best%20%20friends%27%5D"); + public void should_MakeSuccessfulRequest_WhenQueryParamValueWithEscapedSpacesWithEscapedSingleQuoteElements() + throws Exception { + final String requestUrl = String.format( + "%s%s", + STUBS_URL, + "/entity.find.single.quote.spaces.within?key=%5B%27stalin%20and%20%20truman%27,%27are%20best%20%20friends%27%5D"); final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); final HttpResponse response = request.execute(); final String responseContent = response.parseAsString().trim(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"status\": \"hello world with single quote and spaces within\"}").isEqualTo(responseContent); + assertThat("{\"status\": \"hello world with single quote and spaces within\"}") + .isEqualTo(responseContent); } @Test @@ -291,7 +341,10 @@ public void should_FailRequest_WhenUrlMatchingButFilePathDoesNotExist() throws E @Test public void should_MakeSuccessfulRequest_WhenQueryParamsAreAnArrayWithEscapedQuotedElements() throws Exception { - final String requestUrl = String.format("%s%s", STUBS_URL, "/entity.find?type_name=user&client_id=id&client_secret=secret&attributes=[%22id%22,%22uuid%22,%22created%22,%22lastUpdated%22,%22displayName%22,%22email%22,%22givenName%22,%22familyName%22]"); + final String requestUrl = String.format( + "%s%s", + STUBS_URL, + "/entity.find?type_name=user&client_id=id&client_secret=secret&attributes=[%22id%22,%22uuid%22,%22created%22,%22lastUpdated%22,%22displayName%22,%22email%22,%22givenName%22,%22familyName%22]"); final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); final HttpResponse response = request.execute(); @@ -303,7 +356,10 @@ public void should_MakeSuccessfulRequest_WhenQueryParamsAreAnArrayWithEscapedQuo @Test public void should_MakeSuccessfulRequest_WhenQueryParamsAreAnArray() throws Exception { - final String requestUrl = String.format("%s%s", STUBS_URL, "/entity.find.again?type_name=user&client_id=id&client_secret=secret&attributes=[id,uuid,created,lastUpdated,displayName,email,givenName,familyName]"); + final String requestUrl = String.format( + "%s%s", + STUBS_URL, + "/entity.find.again?type_name=user&client_id=id&client_secret=secret&attributes=[id,uuid,created,lastUpdated,displayName,email,givenName,familyName]"); final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); final HttpResponse response = request.execute(); @@ -389,7 +445,8 @@ public void should_FindPostContentsEqual_WhenXmlContentOrderIrrelevant() throws public void should_ReturnPDF_WhenGetRequestMade() throws Exception { final String requestUrl = String.format("%s%s", STUBS_URL, "/pdf/hello-world"); - final HttpResponse response = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute(); + final HttpResponse response = + HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); assertThat(response.getHeaders()).containsKey("content-type"); @@ -405,7 +462,8 @@ public void should_ReturnAllProducts_WhenGetRequestMade() throws Exception { final String expectedContent = StringUtils.inputStreamToString(jsonContentUrl.openStream()); final String requestUrl = String.format("%s%s", STUBS_URL, "/invoice?status=active&type=full"); - final HttpResponse response = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute(); + final HttpResponse response = + HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute(); final String contentTypeHeader = response.getContentType(); final String responseContent = response.parseAsString().trim(); @@ -419,7 +477,8 @@ public void should_ReturnAllProducts_WhenGetRequestMade() throws Exception { public void should_FailToReturnAllProducts_WhenGetRequestMadeWithoutRequiredQueryString() throws Exception { final String requestUrl = String.format("%s%s", STUBS_URL, "/invoice?status=active"); - final HttpResponse response = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute(); + final HttpResponse response = + HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND_404); } @@ -432,7 +491,8 @@ public void should_ReturnAllProducts_WhenGetRequestMadeOverSsl() throws Exceptio final String expectedContent = StringUtils.inputStreamToString(jsonContentUrl.openStream()); final String requestUrl = String.format("%s%s", STUBS_SSL_URL, "/invoice?status=active&type=full"); - final HttpResponse response = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute(); + final HttpResponse response = + HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute(); final String contentTypeHeader = response.getContentType(); @@ -445,7 +505,8 @@ public void should_ReturnAllProducts_WhenGetRequestMadeOverSsl() throws Exceptio public void should_FailToReturnAllProducts_WhenGetRequestMadeWithoutRequiredQueryStringOverSsl() throws Exception { final String requestUrl = String.format("%s%s", STUBS_SSL_URL, "/invoice?status=active"); - final HttpResponse response = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute(); + final HttpResponse response = + HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND_404); } @@ -466,7 +527,8 @@ public void should_UpdateProduct_WhenPutRequestMade() throws Exception { final String contentTypeHeader = response.getContentType(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"id\": \"123\", \"status\": \"updated\"}").isEqualTo(response.parseAsString().trim()); + assertThat("{\"id\": \"123\", \"status\": \"updated\"}") + .isEqualTo(response.parseAsString().trim()); assertThat(contentTypeHeader).contains(HEADER_APPLICATION_JSON); } @@ -486,7 +548,8 @@ public void should_UpdateProduct_WhenPutRequestMadeOverSsl() throws Exception { final String contentTypeHeader = response.getContentType(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"id\": \"123\", \"status\": \"updated\"}").isEqualTo(response.parseAsString().trim()); + assertThat("{\"id\": \"123\", \"status\": \"updated\"}") + .isEqualTo(response.parseAsString().trim()); assertThat(contentTypeHeader).contains(HEADER_APPLICATION_JSON); } @@ -628,13 +691,15 @@ public void should_MakeSuccessfulRequest_AndReturnMultipleSequencedResponses() t assertThat(firstResponseContent).isEqualTo("OK"); final HttpResponse secondSequenceResponse = request.execute(); - final String secondResponseContent = secondSequenceResponse.parseAsString().trim(); + final String secondResponseContent = + secondSequenceResponse.parseAsString().trim(); assertThat(HttpStatus.CREATED_201).isEqualTo(secondSequenceResponse.getStatusCode()); assertThat(secondResponseContent).isEqualTo("Still going strong!"); final HttpResponse thridSequenceResponse = request.execute(); - final String thirdResponseContent = thridSequenceResponse.parseAsString().trim(); + final String thirdResponseContent = + thridSequenceResponse.parseAsString().trim(); assertThat(HttpStatus.INTERNAL_SERVER_ERROR_500).isEqualTo(thridSequenceResponse.getStatusCode()); assertThat(thirdResponseContent).isEqualTo("OMFG!!!"); @@ -659,13 +724,15 @@ public void should_MakeSuccessfulRequest_AndReturnMultipleSequencedResponses_Fro assertThat(firstResponseContent).isEqualTo("OK"); final HttpResponse secondSequenceResponse = request.execute(); - final String secondResponseContent = secondSequenceResponse.parseAsString().trim(); + final String secondResponseContent = + secondSequenceResponse.parseAsString().trim(); assertThat(HttpStatus.CREATED_201).isEqualTo(secondSequenceResponse.getStatusCode()); assertThat(secondResponseContent).isEqualTo("Still going strong!"); final HttpResponse thirdSequenceResponse = request.execute(); - final String thirdResponseContent = thirdSequenceResponse.parseAsString().trim(); + final String thirdResponseContent = + thirdSequenceResponse.parseAsString().trim(); assertThat(HttpStatus.INTERNAL_SERVER_ERROR_500).isEqualTo(thirdSequenceResponse.getStatusCode()); assertThat(thirdResponseContent).isEqualTo("OMFG!!!"); @@ -678,7 +745,8 @@ public void should_MakeSuccessfulRequest_AndReturnMultipleSequencedResponses_Fro } @Test - public void should_MakeSuccessfulRequest_AndReturnMultipleSequencedResponses_FromFile_WithBadUrls() throws Exception { + public void should_MakeSuccessfulRequest_AndReturnMultipleSequencedResponses_FromFile_WithBadUrls() + throws Exception { final String requestUrl = String.format("%s%s", STUBS_URL, "/uri/with/sequenced/responses/infile/withbadurls"); final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); @@ -690,13 +758,15 @@ public void should_MakeSuccessfulRequest_AndReturnMultipleSequencedResponses_Fro assertThat(firstResponseContent).isEmpty(); final HttpResponse secondSequenceResponse = request.execute(); - final String secondResponseContent = secondSequenceResponse.parseAsString().trim(); + final String secondResponseContent = + secondSequenceResponse.parseAsString().trim(); assertThat(HttpStatus.CREATED_201).isEqualTo(secondSequenceResponse.getStatusCode()); assertThat(secondResponseContent).isEqualTo("Still going strong!"); final HttpResponse thirdSequenceResponse = request.execute(); - final String thirdResponseContent = thirdSequenceResponse.parseAsString().trim(); + final String thirdResponseContent = + thirdSequenceResponse.parseAsString().trim(); assertThat(HttpStatus.INTERNAL_SERVER_ERROR_500).isEqualTo(thirdSequenceResponse.getStatusCode()); assertThat(thirdResponseContent).isEmpty(); @@ -713,14 +783,13 @@ public void should_MakeSuccessfulRequest_WhenPostRegexMatchingPostWithLineChars( final String requestUrl = String.format("%s%s", STUBS_URL, "/uri/with/post/regex"); final String content = - "Here's the story of a lovely lady," + FileUtils.BR + - "Who was bringing up three very lovely girls." + FileUtils.BR + - "All of them had hair of gold, like their mother," + FileUtils.BR + - "The youngest one in curls." + FileUtils.BR + - "Here's the story, of a man named Brady," + FileUtils.BR + - "Who was busy with three boys of his own." + FileUtils.BR + - "They were four men, living all together," + FileUtils.BR + - "Yet they were all alone."; + "Here's the story of a lovely lady," + FileUtils.BR + "Who was bringing up three very lovely girls." + + FileUtils.BR + "All of them had hair of gold, like their mother," + + FileUtils.BR + "The youngest one in curls." + + FileUtils.BR + "Here's the story, of a man named Brady," + + FileUtils.BR + "Who was busy with three boys of his own." + + FileUtils.BR + "They were four men, living all together," + + FileUtils.BR + "Yet they were all alone."; final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, content); final HttpResponse response = request.execute(); @@ -733,7 +802,8 @@ public void should_MakeSuccessfulRequest_WhenPostRegexMatchingPostWithLineChars( public void should_MakeSuccessfulRequest_WhenJsonRegexMatchesPostJson() throws Exception { final String requestUrl = String.format("%s%s", STUBS_URL, "/post-body-as-json"); - final String content = "{\"userId\":\"19\",\"requestId\":\"12345\",\"transactionDate\":\"98765\",\"transactionTime\":\"11111\"}"; + final String content = + "{\"userId\":\"19\",\"requestId\":\"12345\",\"transactionDate\":\"98765\",\"transactionTime\":\"11111\"}"; final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, content); final HttpHeaders requestHeaders = new HttpHeaders(); @@ -743,14 +813,17 @@ public void should_MakeSuccessfulRequest_WhenJsonRegexMatchesPostJson() throws E final HttpResponse response = request.execute(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat(response.parseAsString().trim()).isEqualTo("{\"requestId\": \"12345\", \"transactionDate\": \"98765\", \"transactionTime\": \"11111\"}"); + assertThat(response.parseAsString().trim()) + .isEqualTo( + "{\"requestId\": \"12345\", \"transactionDate\": \"98765\", \"transactionTime\": \"11111\"}"); } @Test public void should_MakeSuccessfulRequest_WhenJsonRegexMatchesComplexJsonPost() throws Exception { final String requestUrl = String.format("%s%s", STUBS_URL, "/post-body-as-json-2"); - final String content = "{\"objects\": [{\"key\": \"value\"}, {\"key\": \"value\"}, {\"key\": {\"key\": \"12345\"}}]}"; + final String content = + "{\"objects\": [{\"key\": \"value\"}, {\"key\": \"value\"}, {\"key\": {\"key\": \"12345\"}}]}"; final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, content); final HttpHeaders requestHeaders = new HttpHeaders(); @@ -813,7 +886,8 @@ public void should_ReturnExpectedResourceIdHeader_WhenSuccessfulRequestMade() th assertThat(headers.getContentType().contains(HEADER_APPLICATION_JSON)).isTrue(); assertThat(headers.containsKey(Common.HEADER_X_STUBBY_RESOURCE_ID)).isTrue(); - final List headerValues = asCheckedArrayList(headers.get(Common.HEADER_X_STUBBY_RESOURCE_ID), String.class); + final List headerValues = + asCheckedArrayList(headers.get(Common.HEADER_X_STUBBY_RESOURCE_ID), String.class); assertThat(headerValues.get(0)).isEqualTo("1"); } @@ -828,7 +902,6 @@ public void should_ReturnReplacedTokenizedResponse_WhenCapturingGroupsEqualToNum assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); assertThat(responseContent).isEqualTo("Returned invoice number# 12345 in category 'milk'"); - requestUrl = String.format("%s%s", STUBS_URL, "/resources/invoices/88888/category/army"); request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); response = request.execute(); @@ -846,8 +919,8 @@ public void should_ReturnReplacedTokenizedResponse_WhenUsingExternalFile() throw String responseContent = response.parseAsString().trim(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat(responseContent).isEqualTo("Returned invoice number# 12345 in category 'milk' on the date 'Saturday'"); - + assertThat(responseContent) + .isEqualTo("Returned invoice number# 12345 in category 'milk' on the date 'Saturday'"); requestUrl = String.format("%s%s", STUBS_URL, "/account/88888/category/army?date=NOW"); request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); @@ -883,7 +956,9 @@ public void should_ReturnReplacedTokenizedResponse_WhenFullMatchCapturingGroupsA String responseContent = response.parseAsString().trim(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat(responseContent).isEqualTo("Returned content with URL /no/explicit/groups/22222, query param ABC and custom-header XYZ"); + assertThat(responseContent) + .isEqualTo( + "Returned content with URL /no/explicit/groups/22222, query param ABC and custom-header XYZ"); } @Test @@ -894,7 +969,9 @@ public void should_ReturnReplacedTokenizedResponse_WhenCapturingGroupHasSubgroup String responseContent = response.parseAsString().trim(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat(responseContent).isEqualTo("Returned content with URL /groups/with/sub/groups/abc-123, parent group abc-123 and two sub-groups abc & 123"); + assertThat(responseContent) + .isEqualTo( + "Returned content with URL /groups/with/sub/groups/abc-123, parent group abc-123 and two sub-groups abc & 123"); } @Test @@ -903,7 +980,8 @@ public void shouldReturnReplacedValueInLocationHeaderWhenQueryParamHasDynamicTok expectedException.expect(UnknownHostException.class); expectedException.expectMessage("hostDoesNotExist123.com"); - final String requestUrl = String.format("%s%s", STUBS_URL, "/v8/identity/authorize?redirect_uri=https://hostDoesNotExist123.com/app/very/cool"); + final String requestUrl = String.format( + "%s%s", STUBS_URL, "/v8/identity/authorize?redirect_uri=https://hostDoesNotExist123.com/app/very/cool"); final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl); request.execute(); @@ -922,7 +1000,8 @@ public void should_MakeSuccessfulRedirectRequest_WhenLocationHeaderAndStatusSet( final HttpResponse response = request.execute(); final HttpHeaders headers = response.getHeaders(); - assertThat(headers.getContentType().contains(Common.HEADER_APPLICATION_JSON)).isTrue(); + assertThat(headers.getContentType().contains(Common.HEADER_APPLICATION_JSON)) + .isTrue(); String responseContent = response.parseAsString().trim(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); @@ -962,7 +1041,8 @@ public void should_MakeSuccessfulRequest_When404NotFoundResponseStubbedWithBody( public void should_MakeSuccessfulRequest_WhenGetRequestMadeWithNoEqualSignInQueryStringParam() throws Exception { final String requestUrl = String.format("%s%s", STUBS_URL, "/empty.param?type_name&client_secret=secret"); - final HttpResponse response = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute(); + final HttpResponse response = + HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute(); final String responseContentAsString = response.parseAsString().trim(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); @@ -970,10 +1050,12 @@ public void should_MakeSuccessfulRequest_WhenGetRequestMadeWithNoEqualSignInQuer } @Test - public void should_MakeSuccessfulRequest_WhenGetRequestMadeWithNoEqualSignInSingleQueryStringParam() throws Exception { + public void should_MakeSuccessfulRequest_WhenGetRequestMadeWithNoEqualSignInSingleQueryStringParam() + throws Exception { final String requestUrl = String.format("%s%s", STUBS_URL, "/empty.single.param?type_name"); - final HttpResponse response = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute(); + final HttpResponse response = + HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute(); final String responseContentAsString = response.parseAsString().trim(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); @@ -984,7 +1066,8 @@ public void should_MakeSuccessfulRequest_WhenGetRequestMadeWithNoEqualSignInSing public void should_MakeSuccessfulRequest_WhenGetRequestMadeWithNoQueryStringParamValue() throws Exception { final String requestUrl = String.format("%s%s", STUBS_URL, "/empty.param?type_name=&client_secret=secret"); - final HttpResponse response = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute(); + final HttpResponse response = + HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute(); final String responseContentAsString = response.parseAsString().trim(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); @@ -1007,7 +1090,8 @@ public void should_ReturnExpectedRecordedResponse_FromAnotherValidUrl() throws E String responseContent = response.parseAsString().trim(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); - assertThat(responseContent).contains("STANDARD"); + assertThat(responseContent) + .contains("STANDARD"); } @Test @@ -1022,7 +1106,8 @@ public void should_ReturnExpectedRecordedResponseUsingActualQuery_FromAnotherVal final HttpResponse response = request.execute(); final HttpHeaders headers = response.getHeaders(); - assertThat(headers.getContentType().contains(Common.HEADER_APPLICATION_JSON)).isTrue(); + assertThat(headers.getContentType().contains(Common.HEADER_APPLICATION_JSON)) + .isTrue(); String responseContent = response.parseAsString().trim(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200); @@ -1070,10 +1155,12 @@ public void should_ReturnExpectedRecordedResponse_OnSubsequentCallToValidUrl() t final int LIMIT = 5; for (int idx = 1; idx <= LIMIT; idx++) { final HttpResponse actualResponse = request.execute(); - final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + final String actualConsoleOutput = + consoleCaptor.toString(StringUtils.UTF_8).trim(); String firstCallResponseContent = actualResponse.parseAsString().trim(); - assertThat(firstCallResponseContent).contains("STANDARD"); + assertThat(firstCallResponseContent) + .contains("STANDARD"); // Make sure we only hitting recordable source once assertThat(actualConsoleOutput).contains("HTTP request from stub metadata to"); diff --git a/src/functionalTest/java/io/github/azagniotov/stubby4j/client/StubbyClientTest.java b/src/functionalTest/java/io/github/azagniotov/stubby4j/client/StubbyClientTest.java index 8a8d7d4ef..d6e3dc910 100644 --- a/src/functionalTest/java/io/github/azagniotov/stubby4j/client/StubbyClientTest.java +++ b/src/functionalTest/java/io/github/azagniotov/stubby4j/client/StubbyClientTest.java @@ -1,8 +1,28 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.client; +import static com.google.common.truth.Truth.assertThat; + import io.github.azagniotov.stubby4j.handlers.AdminPortalHandler; import io.github.azagniotov.stubby4j.server.JettyFactory; import io.github.azagniotov.stubby4j.utils.StringUtils; +import java.io.InputStream; +import java.net.URL; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpScheme; import org.eclipse.jetty.http.HttpStatus; @@ -12,12 +32,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import java.io.InputStream; -import java.net.URL; - -import static com.google.common.truth.Truth.assertThat; - - public class StubbyClientTest { private static final String MAIN_TEST_STUBS_YAML = "/yaml/main-test-stubs.yaml"; @@ -26,7 +40,8 @@ public class StubbyClientTest { private static final int SSL_PORT = 4443; private static final String ENCODED_STRING = "Ym9iOndyb25nLXNlY3JldA=="; - private static final String AUTHORIZATION_HEADER_CUSTOM = String.format("CustomAuthorizationName %s", ENCODED_STRING); + private static final String AUTHORIZATION_HEADER_CUSTOM = + String.format("CustomAuthorizationName %s", ENCODED_STRING); private static final String BOB_SECRET = "bob:secret"; @Rule @@ -36,7 +51,8 @@ public class StubbyClientTest { public static void beforeClass() throws Exception { final URL url = StubbyClientTest.class.getResource(MAIN_TEST_STUBS_YAML); assert url != null; - STUBBY_CLIENT.startJetty(JettyFactory.DEFAULT_STUBS_PORT, SSL_PORT, JettyFactory.DEFAULT_ADMIN_PORT, url.getFile()); + STUBBY_CLIENT.startJetty( + JettyFactory.DEFAULT_STUBS_PORT, SSL_PORT, JettyFactory.DEFAULT_ADMIN_PORT, url.getFile()); } @AfterClass @@ -62,12 +78,7 @@ public void makeRequest_ShouldMakeSuccessfulGetOverSsl() throws Exception { final String uri = "/item/1"; final StubbyResponse stubbyResponse = STUBBY_CLIENT.makeRequest( - HttpScheme.HTTPS.asString(), - HttpMethod.GET.asString(), - JettyFactory.DEFAULT_HOST, - uri, - SSL_PORT, - null); + HttpScheme.HTTPS.asString(), HttpMethod.GET.asString(), JettyFactory.DEFAULT_HOST, uri, SSL_PORT, null); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.OK_200); assertThat("{\"id\" : \"1\", \"description\" : \"milk\"}").isEqualTo(stubbyResponse.body()); @@ -78,8 +89,13 @@ public void makeRequest_ShouldFailToMakeRequest_WhenUnsupportedMethodGiven() thr expectedException.expect(UnsupportedOperationException.class); - STUBBY_CLIENT.makeRequest(HttpScheme.HTTPS.asString(), HttpMethod.MOVE.asString(), JettyFactory.DEFAULT_HOST, - "/item/1", SSL_PORT, null); + STUBBY_CLIENT.makeRequest( + HttpScheme.HTTPS.asString(), + HttpMethod.MOVE.asString(), + JettyFactory.DEFAULT_HOST, + "/item/1", + SSL_PORT, + null); } @Test @@ -112,10 +128,15 @@ public void doGet_ShouldMakeSuccessfulGetWithBasicAuth_WhenAuthCredentialsIsProv final String uri = "/item/auth"; final int port = JettyFactory.DEFAULT_STUBS_PORT; - final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGet(host, uri, port, new Authorization(Authorization.AuthorizationType.BASIC, StringUtils.encodeBase64(BOB_SECRET))); + final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGet( + host, + uri, + port, + new Authorization(Authorization.AuthorizationType.BASIC, StringUtils.encodeBase64(BOB_SECRET))); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"id\" : \"8\", \"description\" : \"authorized using basic\"}").isEqualTo(stubbyResponse.body()); + assertThat("{\"id\" : \"8\", \"description\" : \"authorized using basic\"}") + .isEqualTo(stubbyResponse.body()); } @Test @@ -124,10 +145,12 @@ public void doGet_ShouldMakeSuccessfulGetWithBearerAuth_WhenAuthCredentialsIsPro final String uri = "/item/auth/bearer"; final int port = JettyFactory.DEFAULT_STUBS_PORT; - final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGet(host, uri, port, new Authorization(Authorization.AuthorizationType.BEARER, ENCODED_STRING)); + final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGet( + host, uri, port, new Authorization(Authorization.AuthorizationType.BEARER, ENCODED_STRING)); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"id\" : \"12\", \"description\" : \"authorized using bearer\"}").isEqualTo(stubbyResponse.body()); + assertThat("{\"id\" : \"12\", \"description\" : \"authorized using bearer\"}") + .isEqualTo(stubbyResponse.body()); } @Test @@ -136,10 +159,15 @@ public void doGet_ShouldMakeSuccessfulGetWithCustomAuth_WhenAuthCredentialsIsPro final String uri = "/item/auth/custom"; final int port = JettyFactory.DEFAULT_STUBS_PORT; - final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGet(host, uri, port, new Authorization(Authorization.AuthorizationType.CUSTOM, AUTHORIZATION_HEADER_CUSTOM)); + final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGet( + host, + uri, + port, + new Authorization(Authorization.AuthorizationType.CUSTOM, AUTHORIZATION_HEADER_CUSTOM)); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"id\" : \"12\", \"description\" : \"authorized using custom\"}").isEqualTo(stubbyResponse.body()); + assertThat("{\"id\" : \"12\", \"description\" : \"authorized using custom\"}") + .isEqualTo(stubbyResponse.body()); } @Test @@ -147,10 +175,15 @@ public void doGetOverSsl_ShouldMakeSuccessfulGetWithBasicAuth_WhenAuthCredential final String host = "localhost"; final String uri = "/item/auth"; - final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGetOverSsl(host, uri, SSL_PORT, new Authorization(Authorization.AuthorizationType.BASIC, StringUtils.encodeBase64(BOB_SECRET))); + final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGetOverSsl( + host, + uri, + SSL_PORT, + new Authorization(Authorization.AuthorizationType.BASIC, StringUtils.encodeBase64(BOB_SECRET))); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"id\" : \"8\", \"description\" : \"authorized using basic\"}").isEqualTo(stubbyResponse.body()); + assertThat("{\"id\" : \"8\", \"description\" : \"authorized using basic\"}") + .isEqualTo(stubbyResponse.body()); } @Test @@ -158,10 +191,12 @@ public void doGetOverSsl_ShouldMakeSuccessfulGetWithBearerAuth_WhenAuthCredentia final String host = "localhost"; final String uri = "/item/auth/bearer"; - final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGetOverSsl(host, uri, SSL_PORT, new Authorization(Authorization.AuthorizationType.BEARER, ENCODED_STRING)); + final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGetOverSsl( + host, uri, SSL_PORT, new Authorization(Authorization.AuthorizationType.BEARER, ENCODED_STRING)); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"id\" : \"12\", \"description\" : \"authorized using bearer\"}").isEqualTo(stubbyResponse.body()); + assertThat("{\"id\" : \"12\", \"description\" : \"authorized using bearer\"}") + .isEqualTo(stubbyResponse.body()); } @Test @@ -169,40 +204,54 @@ public void doGetOverSsl_ShouldMakeSuccessfulGetWithCustomAuth_WhenAuthCredentia final String host = "localhost"; final String uri = "/item/auth/custom"; - final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGetOverSsl(host, uri, SSL_PORT, new Authorization(Authorization.AuthorizationType.CUSTOM, AUTHORIZATION_HEADER_CUSTOM)); + final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGetOverSsl( + host, + uri, + SSL_PORT, + new Authorization(Authorization.AuthorizationType.CUSTOM, AUTHORIZATION_HEADER_CUSTOM)); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"id\" : \"12\", \"description\" : \"authorized using custom\"}").isEqualTo(stubbyResponse.body()); + assertThat("{\"id\" : \"12\", \"description\" : \"authorized using custom\"}") + .isEqualTo(stubbyResponse.body()); } @Test - public void doGetUsingDefaultStubbyPortAndHost_ShouldMakeSuccessfulGetWithBasicAuth_WhenAuthCredentialsIsProvided() throws Exception { + public void doGetUsingDefaultStubbyPortAndHost_ShouldMakeSuccessfulGetWithBasicAuth_WhenAuthCredentialsIsProvided() + throws Exception { final String uri = "/item/auth"; - final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGetUsingDefaults(uri, new Authorization(Authorization.AuthorizationType.BASIC, StringUtils.encodeBase64(BOB_SECRET))); + final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGetUsingDefaults( + uri, new Authorization(Authorization.AuthorizationType.BASIC, StringUtils.encodeBase64(BOB_SECRET))); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"id\" : \"8\", \"description\" : \"authorized using basic\"}").isEqualTo(stubbyResponse.body()); + assertThat("{\"id\" : \"8\", \"description\" : \"authorized using basic\"}") + .isEqualTo(stubbyResponse.body()); } @Test - public void doGetUsingDefaultStubbyPortAndHost_ShouldMakeSuccessfulGetWithBearerAuth_WhenAuthCredentialsIsProvided() throws Exception { + public void doGetUsingDefaultStubbyPortAndHost_ShouldMakeSuccessfulGetWithBearerAuth_WhenAuthCredentialsIsProvided() + throws Exception { final String uri = "/item/auth/bearer"; - final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGetUsingDefaults(uri, new Authorization(Authorization.AuthorizationType.BEARER, ENCODED_STRING)); + final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGetUsingDefaults( + uri, new Authorization(Authorization.AuthorizationType.BEARER, ENCODED_STRING)); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"id\" : \"12\", \"description\" : \"authorized using bearer\"}").isEqualTo(stubbyResponse.body()); + assertThat("{\"id\" : \"12\", \"description\" : \"authorized using bearer\"}") + .isEqualTo(stubbyResponse.body()); } @Test - public void doGetUsingDefaultStubbyPortAndHost_ShouldMakeSuccessfulGetWithCustomAuth_WhenAuthCredentialsIsProvided() throws Exception { + public void doGetUsingDefaultStubbyPortAndHost_ShouldMakeSuccessfulGetWithCustomAuth_WhenAuthCredentialsIsProvided() + throws Exception { final String uri = "/item/auth/custom"; - final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGetUsingDefaults(uri, new Authorization(Authorization.AuthorizationType.CUSTOM, AUTHORIZATION_HEADER_CUSTOM)); + final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGetUsingDefaults( + uri, new Authorization(Authorization.AuthorizationType.CUSTOM, AUTHORIZATION_HEADER_CUSTOM)); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"id\" : \"12\", \"description\" : \"authorized using custom\"}").isEqualTo(stubbyResponse.body()); + assertThat("{\"id\" : \"12\", \"description\" : \"authorized using custom\"}") + .isEqualTo(stubbyResponse.body()); } @Test @@ -211,7 +260,11 @@ public void doGet_ShouldMakeSuccessfulGetWithBasicAuth_WhenWrongAuthCredentialsI final String uri = "/item/auth"; final int port = JettyFactory.DEFAULT_STUBS_PORT; - final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGet(host, uri, port, new Authorization(Authorization.AuthorizationType.BASIC, StringUtils.encodeBase64("bob:wrong-secret"))); + final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGet( + host, + uri, + port, + new Authorization(Authorization.AuthorizationType.BASIC, StringUtils.encodeBase64("bob:wrong-secret"))); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.UNAUTHORIZED_401); } @@ -222,7 +275,8 @@ public void doGet_ShouldMakeSuccessfulGetWithBearerAuth_WhenWrongAuthCredentials final String uri = "/item/auth/bearer"; final int port = JettyFactory.DEFAULT_STUBS_PORT; - final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGet(host, uri, port, new Authorization(Authorization.AuthorizationType.BEARER, "blahblahblah==")); + final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGet( + host, uri, port, new Authorization(Authorization.AuthorizationType.BEARER, "blahblahblah==")); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.UNAUTHORIZED_401); } @@ -233,7 +287,11 @@ public void doGet_ShouldMakeSuccessfulGetWithCustomAuth_WhenWrongAuthCredentials final String uri = "/item/auth/custom"; final int port = JettyFactory.DEFAULT_STUBS_PORT; - final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGet(host, uri, port, new Authorization(Authorization.AuthorizationType.CUSTOM, "CustomAuthorizationName blahblahblah==")); + final StubbyResponse stubbyResponse = STUBBY_CLIENT.doGet( + host, + uri, + port, + new Authorization(Authorization.AuthorizationType.CUSTOM, "CustomAuthorizationName blahblahblah==")); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.UNAUTHORIZED_401); } @@ -301,18 +359,27 @@ public void doPost_ShouldMakeSuccessfulPostWithBasicAuth_WhenAuthCredentialsIsPr final int port = JettyFactory.DEFAULT_STUBS_PORT; final String post = "{\"action\" : \"submit\"}"; - final StubbyResponse stubbyResponse = STUBBY_CLIENT.doPost(host, uri, port, new Authorization(Authorization.AuthorizationType.BASIC, StringUtils.encodeBase64(BOB_SECRET)), post); + final StubbyResponse stubbyResponse = STUBBY_CLIENT.doPost( + host, + uri, + port, + new Authorization(Authorization.AuthorizationType.BASIC, StringUtils.encodeBase64(BOB_SECRET)), + post); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.OK_200); assertThat("OK").isEqualTo(stubbyResponse.body()); } @Test - public void doPostUsingDefaults_ShouldMakeSuccessfulPostWithBasicAuth_WhenAuthCredentialsIsProvided() throws Exception { + public void doPostUsingDefaults_ShouldMakeSuccessfulPostWithBasicAuth_WhenAuthCredentialsIsProvided() + throws Exception { final String uri = "/item/submit"; final String post = "{\"action\" : \"submit\"}"; - final StubbyResponse stubbyResponse = STUBBY_CLIENT.doPostUsingDefaults(uri, post, new Authorization(Authorization.AuthorizationType.BASIC, StringUtils.encodeBase64(BOB_SECRET))); + final StubbyResponse stubbyResponse = STUBBY_CLIENT.doPostUsingDefaults( + uri, + post, + new Authorization(Authorization.AuthorizationType.BASIC, StringUtils.encodeBase64(BOB_SECRET))); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.OK_200); assertThat("OK").isEqualTo(stubbyResponse.body()); @@ -328,7 +395,6 @@ public void doPostUsingDefaults_ShouldMakeSuccessfulPost() throws Exception { assertThat("Got post response").isEqualTo(stubbyResponse.body()); } - @Test public void doPost_ShouldMakeSuccessfulPost_WhenGivenEmptyUri() throws Exception { final String host = "localhost"; @@ -385,7 +451,6 @@ public void doPost_ShouldMakeSuccessfulPost_WhenNullPostGiven() throws Exception assertThat("OK").isEqualTo(stubbyResponse.body()); } - @Test public void doPost_ShouldMakeSuccessfulPost_WhenEmptyPostGiven() throws Exception { final String host = "localhost"; @@ -427,7 +492,8 @@ public void doPost_ShouldMakeSuccessfulPostToCreateStubData() throws Exception { @Test public void updateStubbedData_ShouldMakeSuccessfulPostToCreateStubData() throws Exception { - final String adminUrl = String.format("http://localhost:%s%s", JettyFactory.DEFAULT_ADMIN_PORT, AdminPortalHandler.ADMIN_ROOT); + final String adminUrl = + String.format("http://localhost:%s%s", JettyFactory.DEFAULT_ADMIN_PORT, AdminPortalHandler.ADMIN_ROOT); final URL url = StubbyClientTest.class.getResource(MAIN_TEST_STUBS_YAML); final InputStream stubsDatanputStream = url.openStream(); @@ -523,10 +589,12 @@ public void doDelete_ShouldMakeSuccessfulGetWithBearerAuth_WhenAuthCredentialsIs final String uri = "/item/auth/bearer/1"; final int port = JettyFactory.DEFAULT_STUBS_PORT; - final StubbyResponse stubbyResponse = STUBBY_CLIENT.doDelete(host, uri, port, new Authorization(Authorization.AuthorizationType.BEARER, ENCODED_STRING)); + final StubbyResponse stubbyResponse = STUBBY_CLIENT.doDelete( + host, uri, port, new Authorization(Authorization.AuthorizationType.BEARER, ENCODED_STRING)); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"id\" : \"12\", \"description\" : \"deleted authorized using bearer\"}").isEqualTo(stubbyResponse.body()); + assertThat("{\"id\" : \"12\", \"description\" : \"deleted authorized using bearer\"}") + .isEqualTo(stubbyResponse.body()); } @Test @@ -534,9 +602,11 @@ public void doDeleteOverSsl_ShouldMakeSuccessfulGetWithBearerAuth_WhenAuthCreden final String host = "localhost"; final String uri = "/item/auth/bearer/1"; - final StubbyResponse stubbyResponse = STUBBY_CLIENT.doDeleteOverSsl(host, uri, SSL_PORT, new Authorization(Authorization.AuthorizationType.BEARER, ENCODED_STRING)); + final StubbyResponse stubbyResponse = STUBBY_CLIENT.doDeleteOverSsl( + host, uri, SSL_PORT, new Authorization(Authorization.AuthorizationType.BEARER, ENCODED_STRING)); assertThat(stubbyResponse.statusCode()).isEqualTo(HttpStatus.OK_200); - assertThat("{\"id\" : \"12\", \"description\" : \"deleted authorized using bearer\"}").isEqualTo(stubbyResponse.body()); + assertThat("{\"id\" : \"12\", \"description\" : \"deleted authorized using bearer\"}") + .isEqualTo(stubbyResponse.body()); } } diff --git a/src/functionalTest/java/io/github/azagniotov/stubby4j/client/StubbyClientYamlessTest.java b/src/functionalTest/java/io/github/azagniotov/stubby4j/client/StubbyClientYamlessTest.java index 21235e395..ed1b83bfe 100644 --- a/src/functionalTest/java/io/github/azagniotov/stubby4j/client/StubbyClientYamlessTest.java +++ b/src/functionalTest/java/io/github/azagniotov/stubby4j/client/StubbyClientYamlessTest.java @@ -1,17 +1,31 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.client; +import static com.google.common.truth.Truth.assertThat; + import io.github.azagniotov.stubby4j.utils.NetworkPortUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; +import java.io.InputStream; import org.eclipse.jetty.http.HttpStatus; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import java.io.InputStream; - -import static com.google.common.truth.Truth.assertThat; - - public class StubbyClientYamlessTest { private static final String ADDRESS_TO_BIND = "127.0.0.1"; @@ -25,17 +39,14 @@ public class StubbyClientYamlessTest { public static void beforeClass() throws Exception { // For example, passing additional command line args. But, they are not needed for this specific test - final String[] additionalFlags = new String[]{"--debug"}; + final String[] additionalFlags = new String[] {"--debug"}; - final InputStream resourceAsStream = StubbyClientYamlessTest.class.getResourceAsStream("/yaml/standalone-stub.yaml"); + final InputStream resourceAsStream = + StubbyClientYamlessTest.class.getResourceAsStream("/yaml/standalone-stub.yaml"); final String stubsYamlConfigurationData = StringUtils.inputStreamToString(resourceAsStream); - STUBBY_CLIENT.startJettyYamless(stubsYamlConfigurationData, - STUBS_PORT, - STUBS_TLS_PORT, - ADMIN_PORT, - ADDRESS_TO_BIND, - additionalFlags); + STUBBY_CLIENT.startJettyYamless( + stubsYamlConfigurationData, STUBS_PORT, STUBS_TLS_PORT, ADMIN_PORT, ADDRESS_TO_BIND, additionalFlags); } @AfterClass diff --git a/src/integrationTest/java/io/github/azagniotov/stubby4j/cli/CommandLineInterpreterTest.java b/src/integrationTest/java/io/github/azagniotov/stubby4j/cli/CommandLineInterpreterTest.java index a2f6f23b8..1c3db71ec 100644 --- a/src/integrationTest/java/io/github/azagniotov/stubby4j/cli/CommandLineInterpreterTest.java +++ b/src/integrationTest/java/io/github/azagniotov/stubby4j/cli/CommandLineInterpreterTest.java @@ -1,18 +1,31 @@ -package io.github.azagniotov.stubby4j.cli; - -import io.github.azagniotov.stubby4j.utils.StringUtils; -import org.junit.Test; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; +package io.github.azagniotov.stubby4j.cli; import static com.google.common.truth.Truth.assertThat; import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; +import io.github.azagniotov.stubby4j.utils.StringUtils; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.Test; public class CommandLineInterpreterTest { - @Test public void consolePrintedHelpMessageShouldBeAsExpected() throws Exception { @@ -26,65 +39,66 @@ public void consolePrintedHelpMessageShouldBeAsExpected() throws Exception { System.setOut(oldPrintStream); - final String expectedConsoleOutput = "usage:" + BR + - "java -jar stubby4j-x.x.xx.jar [-a ] [-d ] [-da] [-dc] [-ds] [-h]" + BR + - " [-k ] [-l ] [-m] [-o] [-p ] [-s ] [-t ]" + BR + - " [-ta] [-v] [-w ]" + BR + - " -a,--admin Port for admin portal. Defaults" + BR + - " to 8889." + BR + - " -d,--data Data file to pre-load endpoints." + BR + - " Data file to pre-load endpoints." + BR + - " Optional valid YAML 1.1 is" + BR + - " expected. If YAML is not" + BR + - " provided, you will be expected to" + BR + - " configure stubs via the stubby4j" + BR + - " HTTP POST API." + BR + - " -da,--disable_admin_portal Does not start Admin portal" + BR + - " -dc,--disable_stub_caching Since v7.2.0. Disables stubs" + BR + - " in-memory caching when stubs are" + BR + - " successfully matched to the" + BR + - " incoming HTTP requests" + BR + - " -ds,--disable_ssl Disables TLS support (enabled by" + BR + - " default) and disables the" + BR + - " '--enable_tls_with_alpn_and_http_" + BR + - " 2' flag, if the latter was" + BR + - " provided" + BR + - " -h,--help This help text." + BR + - " -k,--keystore Keystore file for custom TLS. By" + BR + - " default TLS is enabled using" + BR + - " internal self-signed certificate." + BR + - " -l,--location Hostname at which to bind stubby." + BR + - " -m,--mute Mute console output." + BR + - " -o,--debug Dumps raw HTTP request to the" + BR + - " console (if console is not" + BR + - " muted!)." + BR + - " -p,--password Password for the provided" + BR + - " keystore file." + BR + - " -s,--stubs Port for stub portal. Defaults to" + BR + - " 8882." + BR + - " -t,--tls Port for TLS connection. Defaults" + BR + - " to 7443." + BR + - " -ta,--enable_tls_with_alpn_and_http_2 Since v7.4.0. Enables HTTP/2 over" + BR + - " TCP (h2c) and HTTP/2 over TLS" + BR + - " (h2) on TLS v1.2 or newer using" + BR + - " ALPN extension" + BR + - " -v,--version Prints out to console stubby" + BR + - " version." + BR + - " -w,--watch Since v2.0.11. Periodically scans" + BR + - " for changes in last modification" + BR + - " date of the main YAML and" + BR + - " referenced external files (if" + BR + - " any). The flag can accept an" + BR + - " optional arg value which is the" + BR + - " watch scan time in milliseconds." + BR + - " If milliseconds is not provided," + BR + - " the watch scans every 100ms. If" + BR + - " last modification date changed" + BR + - " since the last scan period, the" + BR + - " stub configuration is reloaded"; + final String expectedConsoleOutput = + "usage:" + BR + "java -jar stubby4j-x.x.xx.jar [-a ] [-d ] [-da] [-dc] [-ds] [-h]" + + BR + " [-k ] [-l ] [-m] [-o] [-p ] [-s ] [-t ]" + + BR + " [-ta] [-v] [-w ]" + + BR + " -a,--admin Port for admin portal. Defaults" + + BR + " to 8889." + + BR + " -d,--data Data file to pre-load endpoints." + + BR + " Data file to pre-load endpoints." + + BR + " Optional valid YAML 1.1 is" + + BR + " expected. If YAML is not" + + BR + " provided, you will be expected to" + + BR + " configure stubs via the stubby4j" + + BR + " HTTP POST API." + + BR + " -da,--disable_admin_portal Does not start Admin portal" + + BR + " -dc,--disable_stub_caching Since v7.2.0. Disables stubs" + + BR + " in-memory caching when stubs are" + + BR + " successfully matched to the" + + BR + " incoming HTTP requests" + + BR + " -ds,--disable_ssl Disables TLS support (enabled by" + + BR + " default) and disables the" + + BR + " '--enable_tls_with_alpn_and_http_" + + BR + " 2' flag, if the latter was" + + BR + " provided" + + BR + " -h,--help This help text." + + BR + " -k,--keystore Keystore file for custom TLS. By" + + BR + " default TLS is enabled using" + + BR + " internal self-signed certificate." + + BR + " -l,--location Hostname at which to bind stubby." + + BR + " -m,--mute Mute console output." + + BR + " -o,--debug Dumps raw HTTP request to the" + + BR + " console (if console is not" + + BR + " muted!)." + + BR + " -p,--password Password for the provided" + + BR + " keystore file." + + BR + " -s,--stubs Port for stub portal. Defaults to" + + BR + " 8882." + + BR + " -t,--tls Port for TLS connection. Defaults" + + BR + " to 7443." + + BR + " -ta,--enable_tls_with_alpn_and_http_2 Since v7.4.0. Enables HTTP/2 over" + + BR + " TCP (h2c) and HTTP/2 over TLS" + + BR + " (h2) on TLS v1.2 or newer using" + + BR + " ALPN extension" + + BR + " -v,--version Prints out to console stubby" + + BR + " version." + + BR + " -w,--watch Since v2.0.11. Periodically scans" + + BR + " for changes in last modification" + + BR + " date of the main YAML and" + + BR + " referenced external files (if" + + BR + " any). The flag can accept an" + + BR + " optional arg value which is the" + + BR + " watch scan time in milliseconds." + + BR + " If milliseconds is not provided," + + BR + " the watch scans every 100ms. If" + + BR + " last modification date changed" + + BR + " since the last scan period, the" + + BR + " stub configuration is reloaded"; - final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + final String actualConsoleOutput = + consoleCaptor.toString(StringUtils.UTF_8).trim(); assertThat(actualConsoleOutput).isEqualTo(expectedConsoleOutput); } -} \ No newline at end of file +} diff --git a/src/integrationTest/java/io/github/azagniotov/stubby4j/parser/json/JSONAssertTest.java b/src/integrationTest/java/io/github/azagniotov/stubby4j/parser/json/JSONAssertTest.java index dd8508dbb..6a608de0c 100644 --- a/src/integrationTest/java/io/github/azagniotov/stubby4j/parser/json/JSONAssertTest.java +++ b/src/integrationTest/java/io/github/azagniotov/stubby4j/parser/json/JSONAssertTest.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.parser.json; import io.github.azagniotov.stubby4j.utils.StringUtils; diff --git a/src/integrationTest/java/io/github/azagniotov/stubby4j/server/ssl/CustomHostnameVerifierTest.java b/src/integrationTest/java/io/github/azagniotov/stubby4j/server/ssl/CustomHostnameVerifierTest.java index ca57e769e..c83d5c77e 100644 --- a/src/integrationTest/java/io/github/azagniotov/stubby4j/server/ssl/CustomHostnameVerifierTest.java +++ b/src/integrationTest/java/io/github/azagniotov/stubby4j/server/ssl/CustomHostnameVerifierTest.java @@ -1,13 +1,28 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.server.ssl; -import org.junit.BeforeClass; -import org.junit.Test; +import static com.google.common.truth.Truth.assertThat; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Set; - -import static com.google.common.truth.Truth.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; public class CustomHostnameVerifierTest { @@ -47,8 +62,10 @@ public void nonSubjectAltNames() throws Exception { assertThat(customHostnameVerifier.isSubjectAltNamesContain(null)).isFalse(); assertThat(customHostnameVerifier.isSubjectAltNamesContain("")).isFalse(); assertThat(customHostnameVerifier.isSubjectAltNamesContain("null")).isFalse(); - assertThat(customHostnameVerifier.isSubjectAltNamesContain("203.0.113.42")).isFalse(); - assertThat(customHostnameVerifier.isSubjectAltNamesContain("2001:0002:14:5:1:2:bf35:2610")).isFalse(); + assertThat(customHostnameVerifier.isSubjectAltNamesContain("203.0.113.42")) + .isFalse(); + assertThat(customHostnameVerifier.isSubjectAltNamesContain("2001:0002:14:5:1:2:bf35:2610")) + .isFalse(); } @Test diff --git a/src/integrationTest/java/io/github/azagniotov/stubby4j/server/ssl/SslUtilsTest.java b/src/integrationTest/java/io/github/azagniotov/stubby4j/server/ssl/SslUtilsTest.java index ee72d3b83..227a196e3 100644 --- a/src/integrationTest/java/io/github/azagniotov/stubby4j/server/ssl/SslUtilsTest.java +++ b/src/integrationTest/java/io/github/azagniotov/stubby4j/server/ssl/SslUtilsTest.java @@ -1,13 +1,28 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.server.ssl; -import org.junit.BeforeClass; -import org.junit.Test; +import static com.google.common.truth.Truth.assertThat; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Set; - -import static com.google.common.truth.Truth.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; public class SslUtilsTest { diff --git a/src/integrationTest/java/io/github/azagniotov/stubby4j/stubs/StubRepositoryTest.java b/src/integrationTest/java/io/github/azagniotov/stubby4j/stubs/StubRepositoryTest.java index 4bcb12440..a67f2772c 100644 --- a/src/integrationTest/java/io/github/azagniotov/stubby4j/stubs/StubRepositoryTest.java +++ b/src/integrationTest/java/io/github/azagniotov/stubby4j/stubs/StubRepositoryTest.java @@ -1,5 +1,38 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_CONFIG; +import static io.github.azagniotov.stubby4j.stubs.StubbableAuthorizationType.BASIC; +import static io.github.azagniotov.stubby4j.stubs.StubbableAuthorizationType.BEARER; +import static io.github.azagniotov.stubby4j.stubs.StubbableAuthorizationType.CUSTOM; +import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; +import static io.github.azagniotov.stubby4j.utils.ReflectionUtils.injectObjectFields; +import static io.github.azagniotov.stubby4j.utils.StringUtils.inputStreamToString; +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.google.api.client.http.HttpMethods; import io.github.azagniotov.stubby4j.annotations.PotentiallyFlaky; import io.github.azagniotov.stubby4j.caching.Cache; @@ -9,15 +42,6 @@ import io.github.azagniotov.stubby4j.yaml.YamlBuilder; import io.github.azagniotov.stubby4j.yaml.YamlParseResultSet; import io.github.azagniotov.stubby4j.yaml.YamlParser; -import org.eclipse.jetty.http.HttpStatus.Code; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; - -import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -31,24 +55,14 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_CONFIG; -import static io.github.azagniotov.stubby4j.stubs.StubbableAuthorizationType.BASIC; -import static io.github.azagniotov.stubby4j.stubs.StubbableAuthorizationType.BEARER; -import static io.github.azagniotov.stubby4j.stubs.StubbableAuthorizationType.CUSTOM; -import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; -import static io.github.azagniotov.stubby4j.utils.ReflectionUtils.injectObjectFields; -import static io.github.azagniotov.stubby4j.utils.StringUtils.inputStreamToString; -import static org.junit.Assert.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - +import javax.servlet.http.HttpServletRequest; +import org.eclipse.jetty.http.HttpStatus.Code; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; @SuppressWarnings("serial") @RunWith(MockitoJUnitRunner.class) @@ -70,10 +84,8 @@ public class StubRepositoryTest { private Cache spyNoOpCache = Cache.stubHttpLifecycleCache(true); @Spy - private StubRepository spyStubRepository = new StubRepository(CONFIG_FILE, - Cache.stubHttpLifecycleCache(false), - YAML_PARSE_RESULT_SET_FUTURE, - new StubbyHttpTransport()); + private StubRepository spyStubRepository = new StubRepository( + CONFIG_FILE, Cache.stubHttpLifecycleCache(false), YAML_PARSE_RESULT_SET_FUTURE, new StubbyHttpTransport()); private StubRequest.Builder requestBuilder; @@ -84,18 +96,21 @@ public void beforeEach() throws Exception { @Test public void shouldCacheStubOnlyOnFirstRequestWhenUsingDefaultCache() throws Exception { - final StubRepository stubRepository = new StubRepository(CONFIG_FILE, spyDefaultCache, YAML_PARSE_RESULT_SET_FUTURE, new StubbyHttpTransport()); + final StubRepository stubRepository = new StubRepository( + CONFIG_FILE, spyDefaultCache, YAML_PARSE_RESULT_SET_FUTURE, new StubbyHttpTransport()); final String url = "/invoice/123"; final String expectedStatus = "200"; final String expectedBody = "This is a response for 123"; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl(url) .newStubbedResponse() .withStatus(expectedStatus) - .withLiteralBody(expectedBody).build(); + .withLiteralBody(expectedBody) + .build(); stubRepository.resetStubsCache(new YamlParser().parse(".", yaml)); @@ -122,18 +137,21 @@ public void shouldCacheStubOnlyOnFirstRequestWhenUsingDefaultCache() throws Exce @Test public void shouldNoOpCacheEveryRequestWhenUsingNoOpCache() throws Exception { - final StubRepository stubRepository = new StubRepository(CONFIG_FILE, spyNoOpCache, YAML_PARSE_RESULT_SET_FUTURE, new StubbyHttpTransport()); + final StubRepository stubRepository = + new StubRepository(CONFIG_FILE, spyNoOpCache, YAML_PARSE_RESULT_SET_FUTURE, new StubbyHttpTransport()); final String url = "/invoice/123"; final String expectedStatus = "200"; final String expectedBody = "This is a response for 123"; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl(url) .newStubbedResponse() .withStatus(expectedStatus) - .withLiteralBody(expectedBody).build(); + .withLiteralBody(expectedBody) + .build(); stubRepository.resetStubsCache(new YamlParser().parse(".", yaml)); @@ -180,15 +198,14 @@ public void shouldReturnMatchingStubbedSequenceResponse_WhenSequenceHasOneRespon loadYamlToDataStore(yaml); final StubRequest assertingRequest = - requestBuilder - .withUrl(url) - .withMethodGet().build(); + requestBuilder.withUrl(url).withMethodGet().build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); assertThat(Code.OK).isEqualTo(foundStubResponse.getHttpStatusCode()); assertThat(foundStubResponse.getBody()).isEqualTo(sequenceResponseBody); - assertThat(foundStubResponse.getHeaders()).containsEntry(sequenceResponseHeaderKey, sequenceResponseHeaderValue); + assertThat(foundStubResponse.getHeaders()) + .containsEntry(sequenceResponseHeaderKey, sequenceResponseHeaderValue); } @Test @@ -218,17 +235,15 @@ public void shouldReturnMatchingStubbedSequenceResponse_WhenSequenceHasManyRespo loadYamlToDataStore(yaml); final StubRequest assertingRequest = - requestBuilder - .withUrl(url) - .withMethodGet().build(); - + requestBuilder.withUrl(url).withMethodGet().build(); final StubResponse irrelevantFirstSequenceResponse = setUpStubSearchBehavior(assertingRequest); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); assertThat(Code.INTERNAL_SERVER_ERROR).isEqualTo(foundStubResponse.getHttpStatusCode()); assertThat(foundStubResponse.getBody()).isEqualTo(sequenceResponseBody); - assertThat(foundStubResponse.getHeaders()).containsEntry(sequenceResponseHeaderKey, sequenceResponseHeaderValue); + assertThat(foundStubResponse.getHeaders()) + .containsEntry(sequenceResponseHeaderKey, sequenceResponseHeaderValue); } @Test @@ -258,9 +273,7 @@ public void shouldReturnFirstSequenceResponse_WhenAllSequenceResponsesHaveBeenCo loadYamlToDataStore(yaml); final StubRequest assertingRequest = - requestBuilder - .withUrl(url) - .withMethodGet().build(); + requestBuilder.withUrl(url).withMethodGet().build(); final StubResponse irrelevantFirstSequenceResponse = setUpStubSearchBehavior(assertingRequest); final StubResponse irrelevantLastSequenceResponse = setUpStubSearchBehavior(assertingRequest); @@ -268,7 +281,8 @@ public void shouldReturnFirstSequenceResponse_WhenAllSequenceResponsesHaveBeenCo assertThat(Code.OK).isEqualTo(firstSequenceResponseRestarted.getHttpStatusCode()); assertThat(firstSequenceResponseRestarted.getBody()).isEqualTo(sequenceResponseBody); - assertThat(firstSequenceResponseRestarted.getHeaders()).containsEntry(sequenceResponseHeaderKey, sequenceResponseHeaderValue); + assertThat(firstSequenceResponseRestarted.getHeaders()) + .containsEntry(sequenceResponseHeaderKey, sequenceResponseHeaderValue); } @Test @@ -280,20 +294,20 @@ public void shouldReturnMatchingRedirectResponse_WhenLocationHeaderSet() throws final String expectedHeaderKey = "location"; final String expectedHeaderValue = "/invoice/123"; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl(url) .newStubbedResponse() .withStatus(expectedStatus) .withHeaders(expectedHeaderKey, expectedHeaderValue) - .withLiteralBody(expectedBody).build(); + .withLiteralBody(expectedBody) + .build(); loadYamlToDataStore(yaml); final StubRequest assertingRequest = - requestBuilder - .withUrl(url) - .withMethodGet().build(); + requestBuilder.withUrl(url).withMethodGet().build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); @@ -302,7 +316,6 @@ public void shouldReturnMatchingRedirectResponse_WhenLocationHeaderSet() throws assertThat(foundStubResponse.getHeaders()).containsEntry(expectedHeaderKey, expectedHeaderValue); } - @Test public void shouldReturnMatchingStubbedResponse_WhenValidGetRequestMade() throws Exception { @@ -310,19 +323,19 @@ public void shouldReturnMatchingStubbedResponse_WhenValidGetRequestMade() throws final String expectedStatus = "200"; final String expectedBody = "This is a response for 123"; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl(url) .newStubbedResponse() .withStatus(expectedStatus) - .withLiteralBody(expectedBody).build(); + .withLiteralBody(expectedBody) + .build(); loadYamlToDataStore(yaml); final StubRequest assertingRequest = - requestBuilder - .withUrl(url) - .withMethodGet().build(); + requestBuilder.withUrl(url).withMethodGet().build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); @@ -330,7 +343,6 @@ public void shouldReturnMatchingStubbedResponse_WhenValidGetRequestMade() throws assertThat(foundStubResponse.getBody()).isEqualTo(expectedBody); } - @Test public void shouldReturnMatchingStubbedResponse_WhenValidAuthorizationBasicHeaderSubmitted() throws Exception { @@ -339,21 +351,23 @@ public void shouldReturnMatchingStubbedResponse_WhenValidAuthorizationBasicHeade final String expectedStatus = "200"; final String expectedBody = "This is a response for 555"; final String expectedHeaderValue = "'bob:secret'"; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl(url) .withHeaders(BASIC.asYAMLProp(), expectedHeaderValue) .newStubbedResponse() .withStatus(expectedStatus) - .withLiteralBody(expectedBody).build(); + .withLiteralBody(expectedBody) + .build(); loadYamlToDataStore(yaml); - final StubRequest assertingRequest = - requestBuilder - .withUrl(url) - .withMethodGet() - .withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, "Basic Ym9iOnNlY3JldA==").build(); //bob:secret + final StubRequest assertingRequest = requestBuilder + .withUrl(url) + .withMethodGet() + .withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, "Basic Ym9iOnNlY3JldA==") + .build(); // bob:secret final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); @@ -369,21 +383,23 @@ public void shouldReturnMatchingStubbedResponse_WhenValidAuthorizationBearerHead final String expectedStatus = "200"; final String expectedBody = "This is a response for 555"; final String expectedHeaderValue = "Ym9iOnNlY3JldA=="; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl(url) .withHeaders(BEARER.asYAMLProp(), expectedHeaderValue) .newStubbedResponse() .withStatus(expectedStatus) - .withLiteralBody(expectedBody).build(); + .withLiteralBody(expectedBody) + .build(); loadYamlToDataStore(yaml); - final StubRequest assertingRequest = - requestBuilder - .withUrl(url) - .withMethodGet() - .withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, "Bearer Ym9iOnNlY3JldA==").build(); + final StubRequest assertingRequest = requestBuilder + .withUrl(url) + .withMethodGet() + .withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, "Bearer Ym9iOnNlY3JldA==") + .build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); @@ -399,21 +415,23 @@ public void shouldReturnMatchingStubbedResponse_WhenValidAuthorizationCustomHead final String expectedStatus = "200"; final String expectedBody = "This is a response for 555"; final String expectedHeaderValue = "CustomAuthorizationName Ym9iOnNlY3JldA=="; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl(url) .withHeaders(CUSTOM.asYAMLProp(), expectedHeaderValue) .newStubbedResponse() .withStatus(expectedStatus) - .withLiteralBody(expectedBody).build(); + .withLiteralBody(expectedBody) + .build(); loadYamlToDataStore(yaml); - final StubRequest assertingRequest = - requestBuilder - .withUrl(url) - .withMethodGet() - .withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, "CustomAuthorizationName Ym9iOnNlY3JldA==").build(); + final StubRequest assertingRequest = requestBuilder + .withUrl(url) + .withMethodGet() + .withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, "CustomAuthorizationName Ym9iOnNlY3JldA==") + .build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); @@ -429,20 +447,20 @@ public void shouldReturnMatchingUnauthorizedStubResponse_WhenAuthorizationHeader final String expectedBody = "This is a response for 555"; final String expectedHeaderValue = "'bob:secret'"; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl(url) .withHeaders(BASIC.asYAMLProp(), expectedHeaderValue) .newStubbedResponse() .withStatus(expectedStatus) - .withLiteralBody(expectedBody).build(); + .withLiteralBody(expectedBody) + .build(); loadYamlToDataStore(yaml); final StubRequest assertingRequest = - requestBuilder - .withUrl(url) - .withMethodGet().build(); + requestBuilder.withUrl(url).withMethodGet().build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); @@ -450,27 +468,29 @@ public void shouldReturnMatchingUnauthorizedStubResponse_WhenAuthorizationHeader assertThat(foundStubResponse.getBody()).isEqualTo(""); } - @Test - public void shouldReturnMatchingUnauthorizedStubResponse_WhenAuthorizationHeaderSubmittedWithBadCredentials() throws Exception { + public void shouldReturnMatchingUnauthorizedStubResponse_WhenAuthorizationHeaderSubmittedWithBadCredentials() + throws Exception { final String url = "/invoice/555"; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl(url) .withHeaders(BASIC.asYAMLProp(), "'bob:secret'") .newStubbedResponse() .withStatus("200") - .withLiteralBody("This is a response for 555").build(); + .withLiteralBody("This is a response for 555") + .build(); loadYamlToDataStore(yaml); - final StubRequest assertingRequest = - requestBuilder - .withUrl(url) - .withMethodGet() - .withHeader(BASIC.asYAMLProp(), "Basic BadCredentials").build(); + final StubRequest assertingRequest = requestBuilder + .withUrl(url) + .withMethodGet() + .withHeader(BASIC.asYAMLProp(), "Basic BadCredentials") + .build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); @@ -479,25 +499,28 @@ public void shouldReturnMatchingUnauthorizedStubResponse_WhenAuthorizationHeader } @Test - public void shouldReturnMatchingUnauthorizedStubResponse_WhenAuthorizationHeaderSubmittedWithNull() throws Exception { + public void shouldReturnMatchingUnauthorizedStubResponse_WhenAuthorizationHeaderSubmittedWithNull() + throws Exception { final String url = "/invoice/555"; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl(url) .withHeaders(BASIC.asYAMLProp(), "'bob:secret'") .newStubbedResponse() .withStatus("200") - .withLiteralBody("This is a response for 555").build(); + .withLiteralBody("This is a response for 555") + .build(); loadYamlToDataStore(yaml); - final StubRequest assertingRequest = - requestBuilder - .withUrl(url) - .withMethodGet() - .withHeader(BASIC.asYAMLProp(), null).build(); + final StubRequest assertingRequest = requestBuilder + .withUrl(url) + .withMethodGet() + .withHeader(BASIC.asYAMLProp(), null) + .build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); @@ -508,19 +531,19 @@ public void shouldReturnMatchingUnauthorizedStubResponse_WhenAuthorizationHeader @Test public void shouldReturnNotFoundStubResponse_WhenAssertingRequestWasNotMatched() throws Exception { - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl("/invoice/125") .newStubbedResponse() .withStatus("200") - .withLiteralBody("This is a response for 125").build(); + .withLiteralBody("This is a response for 125") + .build(); loadYamlToDataStore(yaml); final StubRequest assertingRequest = - requestBuilder - .withUrl("/invoice/300") - .withMethodGet().build(); + requestBuilder.withUrl("/invoice/300").withMethodGet().build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); @@ -536,21 +559,20 @@ public void shouldReturnMatchingStubbedResponse_WhenValidPostRequestMade() throw final String expectedStatus = "503"; final String expectedBody = "This is a response for 567"; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodPost() .withLiteralPost("This is a post data") .withUrl(url) .newStubbedResponse() .withStatus(expectedStatus) - .withLiteralBody(expectedBody).build(); + .withLiteralBody(expectedBody) + .build(); loadYamlToDataStore(yaml); final StubRequest assertingRequest = - requestBuilder - .withUrl(url) - .withMethodPost() - .withPost(postData).build(); + requestBuilder.withUrl(url).withMethodPost().withPost(postData).build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); @@ -563,20 +585,20 @@ public void shouldReturnNotFoundStubResponse_WhenPostBodyMissing() throws Except final String url = "/invoice/567"; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodPost() .withLiteralPost("This is a post data") .withUrl(url) .newStubbedResponse() .withStatus("503") - .withLiteralBody("This is a response for 567").build(); + .withLiteralBody("This is a response for 567") + .build(); loadYamlToDataStore(yaml); final StubRequest assertingRequest = - requestBuilder - .withUrl(url) - .withMethodPost().build(); + requestBuilder.withUrl(url).withMethodPost().build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); @@ -589,19 +611,19 @@ public void shouldReturnNotFoundStubResponse_WhenHittingCorrectUrlButWrongMethod final String url = "/invoice/567"; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl(url) .newStubbedResponse() .withStatus("503") - .withLiteralBody("This is a response for 567").build(); + .withLiteralBody("This is a response for 567") + .build(); loadYamlToDataStore(yaml); final StubRequest assertingRequest = - requestBuilder - .withUrl(url) - .withMethodPost().build(); + requestBuilder.withUrl(url).withMethodPost().build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); @@ -615,21 +637,20 @@ public void shouldReturnNotFoundStubResponse_WhenPostRequestMadeToIncorrectUrl() final String url = "/invoice/non-existent-url"; final String postData = "This is a post data"; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodPost() .withLiteralPost("This is a post data") .withUrl("/invoice/567") .newStubbedResponse() .withStatus("503") - .withLiteralBody("This is a response for 567").build(); + .withLiteralBody("This is a response for 567") + .build(); loadYamlToDataStore(yaml); final StubRequest assertingRequest = - requestBuilder - .withUrl(url) - .withMethodPost() - .withPost(postData).build(); + requestBuilder.withUrl(url).withMethodPost().withPost(postData).build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); @@ -644,29 +665,34 @@ public void shouldReturnMatchingStubbedResponse_WhenQueryParamIsArray() throws E final String expectedStatus = "200"; final String expectedBody = "{\"status\": \"hello world\"}"; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl(url) .withQuery("type_name", "user") .withQuery("client_id", "id") .withQuery("client_secret", "secret") - .withQuery("attributes", "'[\"id\",\"uuid\",\"created\",\"lastUpdated\",\"displayName\",\"email\",\"givenName\",\"familyName\"]'") + .withQuery( + "attributes", + "'[\"id\",\"uuid\",\"created\",\"lastUpdated\",\"displayName\",\"email\",\"givenName\",\"familyName\"]'") .newStubbedResponse() .withStatus(expectedStatus) .withFoldedBody(expectedBody) - .withHeaders("content-type", Common.HEADER_APPLICATION_JSON).build(); + .withHeaders("content-type", Common.HEADER_APPLICATION_JSON) + .build(); loadYamlToDataStore(yaml); - final StubRequest assertingRequest = - requestBuilder - .withUrl(url) - .withMethodGet() - .withQuery("type_name", "user") - .withQuery("client_id", "id") - .withQuery("client_secret", "secret") - .withQuery("attributes", "[\"id\",\"uuid\",\"created\",\"lastUpdated\",\"displayName\",\"email\",\"givenName\",\"familyName\"]") - .build(); + final StubRequest assertingRequest = requestBuilder + .withUrl(url) + .withMethodGet() + .withQuery("type_name", "user") + .withQuery("client_id", "id") + .withQuery("client_secret", "secret") + .withQuery( + "attributes", + "[\"id\",\"uuid\",\"created\",\"lastUpdated\",\"displayName\",\"email\",\"givenName\",\"familyName\"]") + .build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); @@ -675,23 +701,28 @@ public void shouldReturnMatchingStubbedResponse_WhenQueryParamIsArray() throws E } @Test - public void shouldReturnMatchingStubbedResponse_WhenQueryParamArrayHasElementsWithinUrlEncodedQuotes() throws Exception { + public void shouldReturnMatchingStubbedResponse_WhenQueryParamArrayHasElementsWithinUrlEncodedQuotes() + throws Exception { final String url = "/entity.find"; final String expectedStatus = "200"; final String expectedBody = "{\"status\": \"hello world\"}"; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl(url) .withQuery("type_name", "user") .withQuery("client_id", "id") .withQuery("client_secret", "secret") - .withQuery("attributes", "'[\"id\",\"uuid\",\"created\",\"lastUpdated\",\"displayName\",\"email\",\"givenName\",\"familyName\"]'") + .withQuery( + "attributes", + "'[\"id\",\"uuid\",\"created\",\"lastUpdated\",\"displayName\",\"email\",\"givenName\",\"familyName\"]'") .newStubbedResponse() .withStatus(expectedStatus) .withFoldedBody(expectedBody) - .withHeaders("content-type", Common.HEADER_APPLICATION_JSON).build(); + .withHeaders("content-type", Common.HEADER_APPLICATION_JSON) + .build(); loadYamlToDataStore(yaml); @@ -699,8 +730,7 @@ public void shouldReturnMatchingStubbedResponse_WhenQueryParamArrayHasElementsWi when(mockHttpServletRequest.getMethod()).thenReturn(HttpMethods.GET); when(mockHttpServletRequest.getQueryString()) .thenReturn( - "type_name=user&client_id=id&client_secret=secret&attributes=[%22id%22,%22uuid%22,%22created%22,%22lastUpdated%22,%22displayName%22,%22email%22,%22givenName%22,%22familyName%22]" - ); + "type_name=user&client_id=id&client_secret=secret&attributes=[%22id%22,%22uuid%22,%22created%22,%22lastUpdated%22,%22displayName%22,%22email%22,%22givenName%22,%22familyName%22]"); final StubRequest assertingRequest = spyStubRepository.toStubRequest(mockHttpServletRequest); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); @@ -710,20 +740,25 @@ public void shouldReturnMatchingStubbedResponse_WhenQueryParamArrayHasElementsWi } @Test - public void shouldReturnNotFoundStubResponse_WhenQueryParamArrayHasNonMatchedElementsWithinUrlEncodedQuotes() throws Exception { + public void shouldReturnNotFoundStubResponse_WhenQueryParamArrayHasNonMatchedElementsWithinUrlEncodedQuotes() + throws Exception { final String url = "/entity.find"; - final String yaml = YAML_BUILDER.newStubbedRequest() + final String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl(url) .withQuery("type_name", "user") .withQuery("client_id", "id") .withQuery("client_secret", "secret") - .withQuery("attributes", "'[\"id\",\"uuid\",\"created\",\"lastUpdated\",\"displayName\",\"email\",\"givenName\",\"familyName\"]'") + .withQuery( + "attributes", + "'[\"id\",\"uuid\",\"created\",\"lastUpdated\",\"displayName\",\"email\",\"givenName\",\"familyName\"]'") .newStubbedResponse() .withStatus("200") .withFoldedBody("{\"status\": \"hello world\"}") - .withHeaders("content-type", Common.HEADER_APPLICATION_JSON).build(); + .withHeaders("content-type", Common.HEADER_APPLICATION_JSON) + .build(); loadYamlToDataStore(yaml); @@ -731,8 +766,7 @@ public void shouldReturnNotFoundStubResponse_WhenQueryParamArrayHasNonMatchedEle when(mockHttpServletRequest.getMethod()).thenReturn(HttpMethods.GET); when(mockHttpServletRequest.getQueryString()) .thenReturn( - "type_name=user&client_id=id&client_secret=secret&attributes=[%22NOMATCH%22,%22uuid%22,%22created%22,%22lastUpdated%22,%22displayName%22,%22email%22,%22givenName%22,%22familyName%22]" - ); + "type_name=user&client_id=id&client_secret=secret&attributes=[%22NOMATCH%22,%22uuid%22,%22created%22,%22lastUpdated%22,%22displayName%22,%22email%22,%22givenName%22,%22familyName%22]"); final StubRequest assertingRequest = spyStubRepository.toStubRequest(mockHttpServletRequest); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); @@ -743,15 +777,21 @@ public void shouldReturnNotFoundStubResponse_WhenQueryParamArrayHasNonMatchedEle @Test public void shouldReturnRequestAndResponseExternalFiles() throws Exception { - final File expectedRequestFile = FileUtils.uriToFile(StubRepositoryTest.class.getResource("/json/request.external.file.json").getFile()); - final File expectedResponseFile = FileUtils.uriToFile(StubRepositoryTest.class.getResource("/json/response.1.external.file.json").getFile()); + final File expectedRequestFile = FileUtils.uriToFile(StubRepositoryTest.class + .getResource("/json/request.external.file.json") + .getFile()); + final File expectedResponseFile = FileUtils.uriToFile(StubRepositoryTest.class + .getResource("/json/response.1.external.file.json") + .getFile()); resetStubHttpLifeCyclesFromYamlResource("/yaml/two.external.files.yaml"); final Map externalFiles = spyStubRepository.getExternalFiles(); assertThat(externalFiles.size()).isEqualTo(2); - assertThat(externalFiles.containsValue(expectedRequestFile.lastModified())).isTrue(); - assertThat(externalFiles.containsValue(expectedResponseFile.lastModified())).isTrue(); + assertThat(externalFiles.containsValue(expectedRequestFile.lastModified())) + .isTrue(); + assertThat(externalFiles.containsValue(expectedResponseFile.lastModified())) + .isTrue(); final Set filenames = new HashSet<>(); for (final Map.Entry entry : externalFiles.entrySet()) { @@ -765,14 +805,19 @@ public void shouldReturnRequestAndResponseExternalFiles() throws Exception { @Test public void shouldReturnOnlyResponseExternalFile() throws Exception { - final File expectedRequestFile = FileUtils.uriToFile(StubRepositoryTest.class.getResource("/json/request.external.file.json").getFile()); - final File expectedResponseFile = FileUtils.uriToFile(StubRepositoryTest.class.getResource("/json/response.1.external.file.json").getFile()); + final File expectedRequestFile = FileUtils.uriToFile(StubRepositoryTest.class + .getResource("/json/request.external.file.json") + .getFile()); + final File expectedResponseFile = FileUtils.uriToFile(StubRepositoryTest.class + .getResource("/json/response.1.external.file.json") + .getFile()); resetStubHttpLifeCyclesFromYamlResource("/yaml/one.external.files.yaml"); final Map externalFiles = spyStubRepository.getExternalFiles(); assertThat(externalFiles.size()).isEqualTo(1); - assertThat(externalFiles.containsValue(expectedResponseFile.lastModified())).isTrue(); + assertThat(externalFiles.containsValue(expectedResponseFile.lastModified())) + .isTrue(); final Set filenames = new HashSet<>(); for (final Map.Entry entry : externalFiles.entrySet()) { @@ -786,14 +831,19 @@ public void shouldReturnOnlyResponseExternalFile() throws Exception { @Test public void shouldReturnDedupedExternalFile() throws Exception { - final File expectedRequestFile = FileUtils.uriToFile(StubRepositoryTest.class.getResource("/json/request.external.file.json").getFile()); - final File expectedResponseFile = FileUtils.uriToFile(StubRepositoryTest.class.getResource("/json/response.1.external.file.json").getFile()); + final File expectedRequestFile = FileUtils.uriToFile(StubRepositoryTest.class + .getResource("/json/request.external.file.json") + .getFile()); + final File expectedResponseFile = FileUtils.uriToFile(StubRepositoryTest.class + .getResource("/json/response.1.external.file.json") + .getFile()); resetStubHttpLifeCyclesFromYamlResource("/yaml/same.external.files.yaml"); final Map externalFiles = spyStubRepository.getExternalFiles(); assertThat(externalFiles.size()).isEqualTo(1); - assertThat(externalFiles.containsValue(expectedRequestFile.lastModified())).isTrue(); + assertThat(externalFiles.containsValue(expectedRequestFile.lastModified())) + .isTrue(); final Set filenames = new HashSet<>(); for (final Map.Entry entry : externalFiles.entrySet()) { @@ -807,14 +857,19 @@ public void shouldReturnDedupedExternalFile() throws Exception { @Test public void shouldReturnOnlyResponseExternalFileWhenRequestFileFailedToLoad() throws Exception { - final File expectedRequestFile = FileUtils.uriToFile(StubRepositoryTest.class.getResource("/json/request.external.file.json").getFile()); - final File expectedResponseFile = FileUtils.uriToFile(StubRepositoryTest.class.getResource("/json/response.1.external.file.json").getFile()); + final File expectedRequestFile = FileUtils.uriToFile(StubRepositoryTest.class + .getResource("/json/request.external.file.json") + .getFile()); + final File expectedResponseFile = FileUtils.uriToFile(StubRepositoryTest.class + .getResource("/json/response.1.external.file.json") + .getFile()); resetStubHttpLifeCyclesFromYamlResource("/yaml/request.null.external.files.yaml"); final Map externalFiles = spyStubRepository.getExternalFiles(); assertThat(externalFiles.size()).isEqualTo(1); - assertThat(externalFiles.containsValue(expectedResponseFile.lastModified())).isTrue(); + assertThat(externalFiles.containsValue(expectedResponseFile.lastModified())) + .isTrue(); final Set filenames = new HashSet<>(); for (final Map.Entry entry : externalFiles.entrySet()) { @@ -828,14 +883,19 @@ public void shouldReturnOnlyResponseExternalFileWhenRequestFileFailedToLoad() th @Test public void shouldReturnOnlyRequestExternalFileWhenResponseFileFailedToLoad() throws Exception { - final File expectedRequestFile = FileUtils.uriToFile(StubRepositoryTest.class.getResource("/json/request.external.file.json").getFile()); - final File expectedResponseFile = FileUtils.uriToFile(StubRepositoryTest.class.getResource("/json/response.1.external.file.json").getFile()); + final File expectedRequestFile = FileUtils.uriToFile(StubRepositoryTest.class + .getResource("/json/request.external.file.json") + .getFile()); + final File expectedResponseFile = FileUtils.uriToFile(StubRepositoryTest.class + .getResource("/json/response.1.external.file.json") + .getFile()); resetStubHttpLifeCyclesFromYamlResource("/yaml/response.null.external.files.yaml"); final Map externalFiles = spyStubRepository.getExternalFiles(); assertThat(externalFiles.size()).isEqualTo(1); - assertThat(externalFiles.containsValue(expectedRequestFile.lastModified())).isTrue(); + assertThat(externalFiles.containsValue(expectedRequestFile.lastModified())) + .isTrue(); final Set filenames = new HashSet<>(); for (final Map.Entry entry : externalFiles.entrySet()) { @@ -852,7 +912,9 @@ public void shouldVerifyGetAllResponsesInvokation_WhenInvokingGetExternalFiles() final URL yamlUrl = StubRepositoryTest.class.getResource("/yaml/two.cycles.with.multiple.responses.yaml"); final InputStream stubsDatanputStream = yamlUrl.openStream(); final String parentDirectory = new File(yamlUrl.getPath()).getParent(); - final List stubHttpLifecycles = new YamlParser().parse(parentDirectory, inputStreamToString(stubsDatanputStream)).getStubs(); + final List stubHttpLifecycles = new YamlParser() + .parse(parentDirectory, inputStreamToString(stubsDatanputStream)) + .getStubs(); assertThat(stubHttpLifecycles.size()).isEqualTo(2); assertThat(stubHttpLifecycles.get(0).getResponses().size()).isEqualTo(2); assertThat(stubHttpLifecycles.get(1).getResponses().size()).isEqualTo(2); @@ -863,8 +925,9 @@ public void shouldVerifyGetAllResponsesInvokation_WhenInvokingGetExternalFiles() spyStubHttpLifecycles.add(spyCycleOne); spyStubHttpLifecycles.add(spyCycleTwo); - spyStubRepository.resetStubsCache(new YamlParseResultSet(spyStubHttpLifecycles, new HashMap<>())); // 1st time call to getResponses - spyStubRepository.getExternalFiles(); // 2nd time call to getResponses + spyStubRepository.resetStubsCache( + new YamlParseResultSet(spyStubHttpLifecycles, new HashMap<>())); // 1st time call to getResponses + spyStubRepository.getExternalFiles(); // 2nd time call to getResponses verify(spyCycleOne, times(2)).getResponses(); verify(spyCycleTwo, times(2)).getResponses(); @@ -875,23 +938,29 @@ public void shouldVerifyGetRawFileInvocation_WhenInvokingGetExternalFiles() thro final URL yamlUrl = StubRepositoryTest.class.getResource("/yaml/two.cycles.with.multiple.responses.yaml"); final InputStream stubsConfigStream = yamlUrl.openStream(); final String parentDirectory = new File(yamlUrl.getPath()).getParent(); - final List stubHttpLifecycles = new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)).getStubs(); + final List stubHttpLifecycles = new YamlParser() + .parse(parentDirectory, inputStreamToString(stubsConfigStream)) + .getStubs(); assertThat(stubHttpLifecycles.size()).isEqualTo(2); assertThat(stubHttpLifecycles.get(0).getResponses().size()).isEqualTo(2); assertThat(stubHttpLifecycles.get(1).getResponses().size()).isEqualTo(2); // Turn existing StubResponse objects into Mockito.spy - final LinkedList stubResponsesOne = new LinkedList() {{ - add(spy(stubHttpLifecycles.get(0).getResponses().get(0))); - add(spy(stubHttpLifecycles.get(0).getResponses().get(1))); - }}; + final LinkedList stubResponsesOne = new LinkedList() { + { + add(spy(stubHttpLifecycles.get(0).getResponses().get(0))); + add(spy(stubHttpLifecycles.get(0).getResponses().get(1))); + } + }; injectObjectFields(stubHttpLifecycles.get(0), "response", stubResponsesOne); // Turn existing StubResponse objects into Mockito.spy - final LinkedList stubResponsesTwo = new LinkedList() {{ - add(spy(stubHttpLifecycles.get(1).getResponses().get(0))); - add(spy(stubHttpLifecycles.get(1).getResponses().get(1))); - }}; + final LinkedList stubResponsesTwo = new LinkedList() { + { + add(spy(stubHttpLifecycles.get(1).getResponses().get(0))); + add(spy(stubHttpLifecycles.get(1).getResponses().get(1))); + } + }; injectObjectFields(stubHttpLifecycles.get(1), "response", stubResponsesTwo); spyStubRepository.resetStubsCache(new YamlParseResultSet(stubHttpLifecycles, new HashMap<>())); @@ -927,7 +996,8 @@ public void shouldAdjustResourceIDHeadersAccordingly_WhenSomeHttpCycleWasDeleted .withSequenceResponseLiteralBody("BodyContentTwo") .build(); - final String cycleThree = YAML_BUILDER.newStubbedRequest() + final String cycleThree = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri/2") .withQuery("paramName2", "paramValue2") @@ -947,7 +1017,8 @@ public void shouldAdjustResourceIDHeadersAccordingly_WhenSomeHttpCycleWasDeleted for (int sequence = 0; sequence < allResponses.size(); sequence++) { final StubResponse sequenceStubResponse = allResponses.get(sequence); assertThat(sequenceStubResponse.getHeaders()).containsKey(Common.HEADER_X_STUBBY_RESOURCE_ID); - assertThat(sequenceStubResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)).isEqualTo(String.valueOf(resourceId)); + assertThat(sequenceStubResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)) + .isEqualTo(String.valueOf(resourceId)); } } @@ -963,7 +1034,8 @@ public void shouldAdjustResourceIDHeadersAccordingly_WhenSomeHttpCycleWasDeleted for (int sequence = 0; sequence < allResponses.size(); sequence++) { final StubResponse sequenceStubResponse = allResponses.get(sequence); assertThat(sequenceStubResponse.getHeaders()).containsKey(Common.HEADER_X_STUBBY_RESOURCE_ID); - assertThat(sequenceStubResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)).isEqualTo(String.valueOf(resourceId)); + assertThat(sequenceStubResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)) + .isEqualTo(String.valueOf(resourceId)); } } } @@ -991,7 +1063,8 @@ public void shouldAdjustResourceIDHeadersAccordingly_WhenHttpCyclesWereReset() t for (int sequence = 0; sequence < allResponses.size(); sequence++) { final StubResponse sequenceStubResponse = allResponses.get(sequence); assertThat(sequenceStubResponse.getHeaders()).containsKey(Common.HEADER_X_STUBBY_RESOURCE_ID); - assertThat(sequenceStubResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)).isEqualTo(String.valueOf(resourceId)); + assertThat(sequenceStubResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)) + .isEqualTo(String.valueOf(resourceId)); } } @@ -1008,7 +1081,8 @@ public void shouldAdjustResourceIDHeadersAccordingly_WhenHttpCyclesWereReset() t .withSequenceResponseLiteralBody("BodyContentTwo") .build(); - final String cycleThree = YAML_BUILDER.newStubbedRequest() + final String cycleThree = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri/2") .withQuery("paramName2", "paramValue2") @@ -1016,7 +1090,8 @@ public void shouldAdjustResourceIDHeadersAccordingly_WhenHttpCyclesWereReset() t .withStatus("201") .build(); - final YamlParseResultSet yamlParseResultSet = new YamlParser().parse(".", String.format("%s%s%s", cycleTwo, FileUtils.BR, cycleThree)); + final YamlParseResultSet yamlParseResultSet = + new YamlParser().parse(".", String.format("%s%s%s", cycleTwo, FileUtils.BR, cycleThree)); spyStubRepository.resetStubsCache(yamlParseResultSet); List afterResetHttpCycles = spyStubRepository.getStubs(); @@ -1029,7 +1104,8 @@ public void shouldAdjustResourceIDHeadersAccordingly_WhenHttpCyclesWereReset() t for (int sequence = 0; sequence < allResponses.size(); sequence++) { final StubResponse sequenceStubResponse = allResponses.get(sequence); assertThat(sequenceStubResponse.getHeaders()).containsKey(Common.HEADER_X_STUBBY_RESOURCE_ID); - assertThat(sequenceStubResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)).isEqualTo(String.valueOf(resourceId)); + assertThat(sequenceStubResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)) + .isEqualTo(String.valueOf(resourceId)); } } } @@ -1050,7 +1126,8 @@ public void shouldAdjustResourceIDHeadersAccordingly_WhenSomeHttpCycleWasUpdated .withSequenceResponseLiteralBody("BodyContentTwo") .build(); - final String cycleThree = YAML_BUILDER.newStubbedRequest() + final String cycleThree = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri/2") .withQuery("paramName2", "paramValue2") @@ -1070,7 +1147,8 @@ public void shouldAdjustResourceIDHeadersAccordingly_WhenSomeHttpCycleWasUpdated for (int sequence = 0; sequence < allResponses.size(); sequence++) { final StubResponse sequenceStubResponse = allResponses.get(sequence); assertThat(sequenceStubResponse.getHeaders()).containsKey(Common.HEADER_X_STUBBY_RESOURCE_ID); - assertThat(sequenceStubResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)).isEqualTo(String.valueOf(resourceId)); + assertThat(sequenceStubResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)) + .isEqualTo(String.valueOf(resourceId)); } } @@ -1083,7 +1161,8 @@ public void shouldAdjustResourceIDHeadersAccordingly_WhenSomeHttpCycleWasUpdated .withStatus("200") .build(); - final List stubHttpLifecycles = new YamlParser().parse(".", cycleOne).getStubs(); + final List stubHttpLifecycles = + new YamlParser().parse(".", cycleOne).getStubs(); final StubHttpLifecycle updatingStubHttpLifecycle = stubHttpLifecycles.get(0); spyStubRepository.updateStubByIndex(0, updatingStubHttpLifecycle); @@ -1100,7 +1179,8 @@ public void shouldAdjustResourceIDHeadersAccordingly_WhenSomeHttpCycleWasUpdated for (int sequence = 0; sequence < allResponses.size(); sequence++) { final StubResponse sequenceStubResponse = allResponses.get(sequence); assertThat(sequenceStubResponse.getHeaders()).containsKey(Common.HEADER_X_STUBBY_RESOURCE_ID); - assertThat(sequenceStubResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)).isEqualTo(String.valueOf(resourceId)); + assertThat(sequenceStubResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)) + .isEqualTo(String.valueOf(resourceId)); } } } @@ -1108,7 +1188,8 @@ public void shouldAdjustResourceIDHeadersAccordingly_WhenSomeHttpCycleWasUpdated @Test public void shouldThrowWhenDefaultProxyConfigMissing() throws Exception { - final StubRepository stubRepository = new StubRepository(CONFIG_FILE, spyDefaultCache, YAML_PARSE_RESULT_SET_FUTURE, new StubbyHttpTransport()); + final StubRepository stubRepository = new StubRepository( + CONFIG_FILE, spyDefaultCache, YAML_PARSE_RESULT_SET_FUTURE, new StubbyHttpTransport()); final URL yamlUrl = this.getClass().getResource("/yaml/proxy-config-without-default-config.yaml"); final InputStream stubsConfigStream = yamlUrl.openStream(); @@ -1116,7 +1197,8 @@ public void shouldThrowWhenDefaultProxyConfigMissing() throws Exception { stubRepository.resetStubsCache(new YamlParser().parse(".", inputStreamToString(stubsConfigStream))); }); - String expectedMessage = "YAML config contains proxy configs, but the 'default' proxy config is not configured, how so?"; + String expectedMessage = + "YAML config contains proxy configs, but the 'default' proxy config is not configured, how so?"; String actualMessage = exception.getMessage(); assertThat(actualMessage).isEqualTo(expectedMessage); @@ -1124,12 +1206,14 @@ public void shouldThrowWhenDefaultProxyConfigMissing() throws Exception { @Test @PotentiallyFlaky("This test sending the request over the wire to https://jsonplaceholder.typicode.com") - public void shouldReturnProxiedResponseUsingDefaultProxyConfig_WhenStubsWereNotMatched_PotentiallyFlaky() throws Exception { + public void shouldReturnProxiedResponseUsingDefaultProxyConfig_WhenStubsWereNotMatched_PotentiallyFlaky() + throws Exception { // https://jsonplaceholder.typicode.com/todos/1 final String targetUriPath = "/todos/1"; - final String stubsYaml = YAML_BUILDER.newStubbedRequest() + final String stubsYaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl("/a/totally/different/endpoint/stubbed") .newStubbedResponse() @@ -1146,32 +1230,31 @@ public void shouldReturnProxiedResponseUsingDefaultProxyConfig_WhenStubsWereNotM loadYamlToDataStore(stubsYaml + BR + BR + proxyConfigYaml); final StubRequest assertingRequest = - requestBuilder - .withUrl(targetUriPath) - .withMethodGet().build(); + requestBuilder.withUrl(targetUriPath).withMethodGet().build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); assertThat(Code.OK).isEqualTo(foundStubResponse.getHttpStatusCode()); assertThat(foundStubResponse.getHeaders().isEmpty()).isFalse(); - assertThat(foundStubResponse.getBody()).isEqualTo( - "{" + BR + - " \"userId\": 1," + BR + - " \"id\": 1," + BR + - " \"title\": \"delectus aut autem\"," + BR + - " \"completed\": false" + BR + - "}"); + assertThat(foundStubResponse.getBody()) + .isEqualTo("{" + BR + " \"userId\": 1," + + BR + " \"id\": 1," + + BR + " \"title\": \"delectus aut autem\"," + + BR + " \"completed\": false" + + BR + "}"); } @Test @PotentiallyFlaky("This test sending the request over the wire to https://jsonplaceholder.typicode.com") - public void shouldReturnProxiedResponseUsingSpecificProxyConfig_WhenStubsWereNotMatched_PotentiallyFlaky() throws Exception { + public void shouldReturnProxiedResponseUsingSpecificProxyConfig_WhenStubsWereNotMatched_PotentiallyFlaky() + throws Exception { // https://jsonplaceholder.typicode.com/todos/1 final String targetUriPath = "/todos/1"; - final String stubsYaml = YAML_BUILDER.newStubbedRequest() + final String stubsYaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl("/a/totally/different/endpoint/stubbed") .newStubbedResponse() @@ -1193,38 +1276,39 @@ public void shouldReturnProxiedResponseUsingSpecificProxyConfig_WhenStubsWereNot .withPropertyEndpoint("https://google.com") .build(); - loadYamlToDataStore(stubsYaml + BR + BR + specificProxyConfigYaml+ BR + BR + defaultProxyConfigYaml); + loadYamlToDataStore(stubsYaml + BR + BR + specificProxyConfigYaml + BR + BR + defaultProxyConfigYaml); // Setting HEADER_X_STUBBY_PROXY_CONFIG with existing value in proxyConfigs map will select // a proxy config by the value of the header at runtime, even if the default proxy config is defined - final StubRequest assertingRequest = - requestBuilder - .withUrl(targetUriPath) - .withHeader(HEADER_X_STUBBY_PROXY_CONFIG, headerProxyConfigUuid) - .withMethodGet().build(); + final StubRequest assertingRequest = requestBuilder + .withUrl(targetUriPath) + .withHeader(HEADER_X_STUBBY_PROXY_CONFIG, headerProxyConfigUuid) + .withMethodGet() + .build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); assertThat(Code.OK).isEqualTo(foundStubResponse.getHttpStatusCode()); assertThat(foundStubResponse.getHeaders().isEmpty()).isFalse(); - assertThat(foundStubResponse.getBody()).isEqualTo( - "{" + BR + - " \"userId\": 1," + BR + - " \"id\": 1," + BR + - " \"title\": \"delectus aut autem\"," + BR + - " \"completed\": false" + BR + - "}"); + assertThat(foundStubResponse.getBody()) + .isEqualTo("{" + BR + " \"userId\": 1," + + BR + " \"id\": 1," + + BR + " \"title\": \"delectus aut autem\"," + + BR + " \"completed\": false" + + BR + "}"); } @Test @PotentiallyFlaky("This test sending the request over the wire to https://jsonplaceholder.typicode.com") - public void shouldReturnProxiedResponseFallingBackOnDefaultProxyConfig_WhenStubsWereNotMatched_PotentiallyFlaky() throws Exception { + public void shouldReturnProxiedResponseFallingBackOnDefaultProxyConfig_WhenStubsWereNotMatched_PotentiallyFlaky() + throws Exception { // https://jsonplaceholder.typicode.com/todos/1 final String targetUriPath = "/todos/1"; - final String stubsYaml = YAML_BUILDER.newStubbedRequest() + final String stubsYaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl("/a/totally/different/endpoint/stubbed") .newStubbedResponse() @@ -1246,27 +1330,26 @@ public void shouldReturnProxiedResponseFallingBackOnDefaultProxyConfig_WhenStubs .withPropertyEndpoint("https://jsonplaceholder.typicode.com") .build(); - loadYamlToDataStore(stubsYaml + BR + BR + specificProxyConfigYaml+ BR + BR + defaultProxyConfigYaml); + loadYamlToDataStore(stubsYaml + BR + BR + specificProxyConfigYaml + BR + BR + defaultProxyConfigYaml); // Setting HEADER_X_STUBBY_PROXY_CONFIG with WRONG value will select default proxy config at runtime - final StubRequest assertingRequest = - requestBuilder - .withUrl(targetUriPath) - .withHeader(HEADER_X_STUBBY_PROXY_CONFIG, "WRONGHeaderProxyConfigUuid") - .withMethodGet().build(); + final StubRequest assertingRequest = requestBuilder + .withUrl(targetUriPath) + .withHeader(HEADER_X_STUBBY_PROXY_CONFIG, "WRONGHeaderProxyConfigUuid") + .withMethodGet() + .build(); final StubResponse foundStubResponse = setUpStubSearchBehavior(assertingRequest); assertThat(Code.OK).isEqualTo(foundStubResponse.getHttpStatusCode()); assertThat(foundStubResponse.getHeaders().isEmpty()).isFalse(); - assertThat(foundStubResponse.getBody()).isEqualTo( - "{" + BR + - " \"userId\": 1," + BR + - " \"id\": 1," + BR + - " \"title\": \"delectus aut autem\"," + BR + - " \"completed\": false" + BR + - "}"); + assertThat(foundStubResponse.getBody()) + .isEqualTo("{" + BR + " \"userId\": 1," + + BR + " \"id\": 1," + + BR + " \"title\": \"delectus aut autem\"," + + BR + " \"completed\": false" + + BR + "}"); } private void loadYamlToDataStore(final String yaml) throws Exception { @@ -1277,7 +1360,8 @@ private void resetStubHttpLifeCyclesFromYamlResource(final String resourcePath) final URL yamlUrl = StubRepositoryTest.class.getResource(resourcePath); final InputStream stubsDataInputStream = yamlUrl.openStream(); final String parentDirectory = new File(yamlUrl.getPath()).getParent(); - spyStubRepository.resetStubsCache(new YamlParser().parse(parentDirectory, inputStreamToString(stubsDataInputStream))); + spyStubRepository.resetStubsCache( + new YamlParser().parse(parentDirectory, inputStreamToString(stubsDataInputStream))); } private StubResponse setUpStubSearchBehavior(final StubRequest assertingRequest) throws IOException { @@ -1285,4 +1369,4 @@ private StubResponse setUpStubSearchBehavior(final StubRequest assertingRequest) final StubSearchResult stubSearchResult = spyStubRepository.search(mockHttpServletRequest); return stubSearchResult.getMatch(); } -} \ No newline at end of file +} diff --git a/src/integrationTest/java/io/github/azagniotov/stubby4j/utils/ConsoleUtilsTest.java b/src/integrationTest/java/io/github/azagniotov/stubby4j/utils/ConsoleUtilsTest.java index 030c057dc..f43833b2d 100644 --- a/src/integrationTest/java/io/github/azagniotov/stubby4j/utils/ConsoleUtilsTest.java +++ b/src/integrationTest/java/io/github/azagniotov/stubby4j/utils/ConsoleUtilsTest.java @@ -1,7 +1,29 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.utils; +import static com.google.common.truth.Truth.assertThat; +import static org.mockito.Mockito.when; + import io.github.azagniotov.stubby4j.cli.ANSITerminal; -import org.eclipse.jetty.http.HttpScheme; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; @@ -10,14 +32,6 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -import static com.google.common.truth.Truth.assertThat; -import static org.mockito.Mockito.when; - @RunWith(MockitoJUnitRunner.class) public class ConsoleUtilsTest { @@ -60,7 +74,8 @@ public void shouldPrintToConsoleExpectedErrorWithColor_WhenStatus_500() throws E when(mockHttpServletResponse.getStatus()).thenReturn(expectedStatus); ConsoleUtils.logOutgoingResponse(mockHttpServletRequest.getRequestURI(), mockHttpServletResponse); - final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + final String actualConsoleOutput = + consoleCaptor.toString(StringUtils.UTF_8).trim(); assertThat(actualConsoleOutput).contains(expectedConsoleOutput); assertThat(actualConsoleOutput).contains(expectedConsoleColor); @@ -76,7 +91,8 @@ public void shouldPrintToConsoleExpectedErrorWithColor_WhenStatus_301() throws E when(mockHttpServletResponse.getStatus()).thenReturn(expectedStatus); ConsoleUtils.logOutgoingResponse(mockHttpServletRequest.getRequestURI(), mockHttpServletResponse); - final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + final String actualConsoleOutput = + consoleCaptor.toString(StringUtils.UTF_8).trim(); assertThat(actualConsoleOutput).contains(expectedConsoleOutput); assertThat(actualConsoleOutput).contains(expectedConsoleColor); @@ -92,7 +108,8 @@ public void shouldPrintToConsoleExpectedErrorWithColor_WhenStatus_201() throws E when(mockHttpServletResponse.getStatus()).thenReturn(expectedStatus); ConsoleUtils.logOutgoingResponse(mockHttpServletRequest.getRequestURI(), mockHttpServletResponse); - final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + final String actualConsoleOutput = + consoleCaptor.toString(StringUtils.UTF_8).trim(); assertThat(actualConsoleOutput).contains(expectedConsoleOutput); assertThat(actualConsoleOutput).contains(expectedConsoleColor); @@ -108,7 +125,8 @@ public void shouldPrintToConsoleExpectedErrorWithColor_WhenStatus_200() throws E when(mockHttpServletResponse.getStatus()).thenReturn(expectedStatus); ConsoleUtils.logOutgoingResponse(mockHttpServletRequest.getRequestURI(), mockHttpServletResponse); - final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + final String actualConsoleOutput = + consoleCaptor.toString(StringUtils.UTF_8).trim(); assertThat(actualConsoleOutput).contains(expectedConsoleOutput); assertThat(actualConsoleOutput).contains(expectedConsoleColor); @@ -124,7 +142,8 @@ public void shouldPrintToConsoleExpectedErrorWithColor_WhenStatus_100() throws E when(mockHttpServletResponse.getStatus()).thenReturn(expectedStatus); ConsoleUtils.logOutgoingResponse(mockHttpServletRequest.getRequestURI(), mockHttpServletResponse); - final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + final String actualConsoleOutput = + consoleCaptor.toString(StringUtils.UTF_8).trim(); assertThat(actualConsoleOutput).contains(expectedConsoleOutput); assertThat(actualConsoleOutput).contains(expectedConsoleColor); @@ -139,7 +158,8 @@ public void shouldPrintToConsoleExpectedErrorWithColor_WhenStatus_LessThan100() when(mockHttpServletResponse.getStatus()).thenReturn(expectedStatus); ConsoleUtils.logOutgoingResponse(mockHttpServletRequest.getRequestURI(), mockHttpServletResponse); - final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + final String actualConsoleOutput = + consoleCaptor.toString(StringUtils.UTF_8).trim(); assertThat(actualConsoleOutput).contains(expectedConsoleOutput); } diff --git a/src/integrationTest/java/io/github/azagniotov/stubby4j/utils/HandlerUtilsTest.java b/src/integrationTest/java/io/github/azagniotov/stubby4j/utils/HandlerUtilsTest.java index 4e6f8356c..7f94ca9d2 100644 --- a/src/integrationTest/java/io/github/azagniotov/stubby4j/utils/HandlerUtilsTest.java +++ b/src/integrationTest/java/io/github/azagniotov/stubby4j/utils/HandlerUtilsTest.java @@ -1,13 +1,28 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.utils; +import static com.google.common.truth.Truth.assertThat; + +import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.io.IOException; - -import static com.google.common.truth.Truth.assertThat; - public class HandlerUtilsTest { @Rule diff --git a/src/integrationTest/java/io/github/azagniotov/stubby4j/utils/JarUtilsTest.java b/src/integrationTest/java/io/github/azagniotov/stubby4j/utils/JarUtilsTest.java index b2b48db64..d22f610e6 100644 --- a/src/integrationTest/java/io/github/azagniotov/stubby4j/utils/JarUtilsTest.java +++ b/src/integrationTest/java/io/github/azagniotov/stubby4j/utils/JarUtilsTest.java @@ -1,9 +1,25 @@ -package io.github.azagniotov.stubby4j.utils; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import org.junit.Test; +package io.github.azagniotov.stubby4j.utils; import static com.google.common.truth.Truth.assertThat; +import org.junit.Test; + public class JarUtilsTest { @Test @@ -19,5 +35,4 @@ public void shouldReadManifestBuiltDate() throws Exception { assertThat(result).contains("20"); } - -} \ No newline at end of file +} diff --git a/src/integrationTest/java/io/github/azagniotov/stubby4j/yaml/YamlParserLoadTest.java b/src/integrationTest/java/io/github/azagniotov/stubby4j/yaml/YamlParserLoadTest.java index 91150db05..75a6eb4f6 100644 --- a/src/integrationTest/java/io/github/azagniotov/stubby4j/yaml/YamlParserLoadTest.java +++ b/src/integrationTest/java/io/github/azagniotov/stubby4j/yaml/YamlParserLoadTest.java @@ -1,18 +1,33 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.yaml; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; + import io.github.azagniotov.stubby4j.stubs.StubHttpLifecycle; import io.github.azagniotov.stubby4j.stubs.StubRequest; import io.github.azagniotov.stubby4j.stubs.StubResponse; import org.junit.Test; -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; - public class YamlParserLoadTest { private static final YamlBuilder YAML_BUILDER = new YamlBuilder(); - @Test public void loadTest_shouldUnmarshallHugeYamlIntoObjectTree_WhenYAMLValid() throws Exception { @@ -33,7 +48,8 @@ public void loadTest_shouldUnmarshallHugeYamlIntoObjectTree_WhenYAMLValid() thro for (int idx = 1; idx <= NUMBER_OF_HTTPCYCLES; idx++) { String expectedUrl = String.format("%s/%s", baseRequestUrl, idx); - String yaml = YAML_BUILDER.newStubbedRequest() + String yaml = YAML_BUILDER + .newStubbedRequest() .withMethodGet() .withUrl(expectedUrl) .withQuery(expectedParamOne, String.valueOf(idx)) @@ -41,7 +57,8 @@ public void loadTest_shouldUnmarshallHugeYamlIntoObjectTree_WhenYAMLValid() thro .newStubbedResponse() .withStatus(stubbedResponseStatus) .withHeaders(expectedHeaderKey, expectedHeaderValue) - .withLiteralBody(stubbedResponseBody).build(); + .withLiteralBody(stubbedResponseBody) + .build(); BUILDER.append(yaml).append(BR).append(BR); } @@ -53,7 +70,8 @@ public void loadTest_shouldUnmarshallHugeYamlIntoObjectTree_WhenYAMLValid() thro final YamlParseResultSet yamlParseResultSet = loadYamlToDataStore(rawYaml); assertThat(yamlParseResultSet.getStubs().size()).isEqualTo(NUMBER_OF_HTTPCYCLES); - final StubHttpLifecycle actualHttpLifecycle = yamlParseResultSet.getStubs().get(498); + final StubHttpLifecycle actualHttpLifecycle = + yamlParseResultSet.getStubs().get(498); final StubRequest actualRequest = actualHttpLifecycle.getRequest(); final StubResponse actualResponse = actualHttpLifecycle.getResponse(true); @@ -67,5 +85,4 @@ public void loadTest_shouldUnmarshallHugeYamlIntoObjectTree_WhenYAMLValid() thro private YamlParseResultSet loadYamlToDataStore(final String yaml) throws Exception { return new YamlParser().parse(".", yaml); } - } diff --git a/src/integrationTest/java/io/github/azagniotov/stubby4j/yaml/YamlParserTest.java b/src/integrationTest/java/io/github/azagniotov/stubby4j/yaml/YamlParserTest.java index 1f991c7a8..708d955dc 100644 --- a/src/integrationTest/java/io/github/azagniotov/stubby4j/yaml/YamlParserTest.java +++ b/src/integrationTest/java/io/github/azagniotov/stubby4j/yaml/YamlParserTest.java @@ -1,5 +1,30 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.yaml; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.stubs.StubbableAuthorizationType.BASIC; +import static io.github.azagniotov.stubby4j.stubs.StubbableAuthorizationType.BEARER; +import static io.github.azagniotov.stubby4j.stubs.StubbableAuthorizationType.CUSTOM; +import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; +import static io.github.azagniotov.stubby4j.utils.StringUtils.getBytesUtf8; +import static io.github.azagniotov.stubby4j.utils.StringUtils.inputStreamToString; +import static org.junit.Assert.assertThrows; + import com.google.api.client.http.HttpMethods; import io.github.azagniotov.stubby4j.common.Common; import io.github.azagniotov.stubby4j.stubs.StubHttpLifecycle; @@ -14,13 +39,6 @@ import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponse; import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponsePolicy; import io.github.azagniotov.stubby4j.utils.StringUtils; -import org.eclipse.jetty.http.HttpStatus; -import org.eclipse.jetty.http.HttpStatus.Code; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -30,21 +48,18 @@ import java.net.URL; import java.util.List; import java.util.Map; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.stubs.StubbableAuthorizationType.BASIC; -import static io.github.azagniotov.stubby4j.stubs.StubbableAuthorizationType.BEARER; -import static io.github.azagniotov.stubby4j.stubs.StubbableAuthorizationType.CUSTOM; -import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; -import static io.github.azagniotov.stubby4j.utils.StringUtils.getBytesUtf8; -import static io.github.azagniotov.stubby4j.utils.StringUtils.inputStreamToString; -import static org.junit.Assert.assertThrows; - +import org.eclipse.jetty.http.HttpStatus; +import org.eclipse.jetty.http.HttpStatus.Code; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; public class YamlParserTest { @Rule public ExpectedException expectedException = ExpectedException.none(); + private YamlBuilder yamlBuilder; @Before @@ -55,7 +70,8 @@ public void setUp() throws Exception { @Test public void shouldThrow_WhenEmptyYAMLGiven() throws Exception { expectedException.expect(IOException.class); - expectedException.expectMessage("Loaded YAML root node must be an instance of ArrayList, otherwise something went wrong. Check provided YAML"); + expectedException.expectMessage( + "Loaded YAML root node must be an instance of ArrayList, otherwise something went wrong. Check provided YAML"); unmarshall(""); } @@ -77,13 +93,11 @@ public void shouldThrow_WhenRequestYAMLContainsUnknownProperty() throws Exceptio expectedException.expect(IllegalStateException.class); expectedException.expectMessage("An unknown property configured: methodd"); - final String yaml = - "- request:\n" + - " methodd: [PUT]\n" + - " url: /invoice\n" + - "\n" + - " response:\n" + - " status: 200"; + final String yaml = "- request:\n" + " methodd: [PUT]\n" + + " url: /invoice\n" + + "\n" + + " response:\n" + + " status: 200"; unmarshall(yaml); } @@ -93,13 +107,11 @@ public void shouldThrow_WhenResponseYAMLContainsUnknownProperty() throws Excepti expectedException.expect(IllegalStateException.class); expectedException.expectMessage("An unknown property configured: statuss"); - final String yaml = - "- request:\n" + - " method: [PUT]\n" + - " url: /invoice\n" + - "\n" + - " response:\n" + - " statuss: 200"; + final String yaml = "- request:\n" + " method: [PUT]\n" + + " url: /invoice\n" + + "\n" + + " response:\n" + + " statuss: 200"; unmarshall(yaml); } @@ -109,20 +121,18 @@ public void shouldThrow_WhenResponseListYAMLContainsUnknownProperty() throws Exc expectedException.expect(IllegalStateException.class); expectedException.expectMessage("An unknown property configured: bodyy"); - final String yaml = - "- request:\n" + - " method: [PUT]\n" + - " url: /invoice\n" + - "\n" + - " response:\n" + - " - status: 200\n" + - " body: OK\n" + - "\n" + - " - status: 200\n" + - " bodyy: OK\n" + - "\n" + - " - status: 200\n" + - " body: OK"; + final String yaml = "- request:\n" + " method: [PUT]\n" + + " url: /invoice\n" + + "\n" + + " response:\n" + + " - status: 200\n" + + " body: OK\n" + + "\n" + + " - status: 200\n" + + " bodyy: OK\n" + + "\n" + + " - status: 200\n" + + " body: OK"; unmarshall(yaml); } @@ -130,16 +140,15 @@ public void shouldThrow_WhenResponseListYAMLContainsUnknownProperty() throws Exc @Test public void shouldThrow_WhenResponseYAMLContainsPropertyThatDoesNotBelong() throws Exception { expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Invalid property 'post' configured. This property does not belong in object 'response'"); + expectedException.expectMessage( + "Invalid property 'post' configured. This property does not belong in object 'response'"); - final String yaml = - "- request:\n" + - " method: [PUT]\n" + - " url: /invoice\n" + - "\n" + - " response:\n" + - " post: 200\n" + - " status: 200"; + final String yaml = "- request:\n" + " method: [PUT]\n" + + " url: /invoice\n" + + "\n" + + " response:\n" + + " post: 200\n" + + " status: 200"; unmarshall(yaml); } @@ -147,19 +156,18 @@ public void shouldThrow_WhenResponseYAMLContainsPropertyThatDoesNotBelong() thro @Test public void shouldThrow_WhenRequestYAMLContainsPropertyThatDoesNotBelong() throws Exception { expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Invalid property 'status' configured. This property does not belong in object 'request'"); - - final String yaml = - "- description: This is a stub\n" + - " uuid: abc-123-def-456\n" + - " request:\n" + - " method: [PUT]\n" + - " url: /invoice\n" + - " status: /invoice\n" + - "\n" + - " response:\n" + - " body: OK\n" + - " status: 200"; + expectedException.expectMessage( + "Invalid property 'status' configured. This property does not belong in object 'request'"); + + final String yaml = "- description: This is a stub\n" + " uuid: abc-123-def-456\n" + + " request:\n" + + " method: [PUT]\n" + + " url: /invoice\n" + + " status: /invoice\n" + + "\n" + + " response:\n" + + " body: OK\n" + + " status: 200"; unmarshall(yaml); } @@ -167,19 +175,18 @@ public void shouldThrow_WhenRequestYAMLContainsPropertyThatDoesNotBelong() throw @Test public void shouldThrow_WhenHttpLifeCycleYAMLContainsPropertyThatDoesNotBelong() throws Exception { expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Invalid property 'method' configured. This property cannot be configured above the 'request'"); - - final String yaml = - "- description: This is a stub\n" + - " uuid: abc-123-def-456\n" + - " method: does-not-belong\n" + - " request:\n" + - " method: [PUT]\n" + - " url: /invoice\n" + - "\n" + - " response:\n" + - " body: OK\n" + - " status: 200"; + expectedException.expectMessage( + "Invalid property 'method' configured. This property cannot be configured above the 'request'"); + + final String yaml = "- description: This is a stub\n" + " uuid: abc-123-def-456\n" + + " method: does-not-belong\n" + + " request:\n" + + " method: [PUT]\n" + + " url: /invoice\n" + + "\n" + + " response:\n" + + " body: OK\n" + + " status: 200"; unmarshall(yaml); } @@ -187,18 +194,17 @@ public void shouldThrow_WhenHttpLifeCycleYAMLContainsPropertyThatDoesNotBelong() @Test public void shouldThrow_WhenProxyConfigYAMLContainsPropertyThatDoesNotBelong() throws Exception { expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Invalid property 'file' configured. This property does not belong in object 'proxy-config'"); - - final String yaml = - "- proxy-config:\n" + - " uuid: some-unique-name\n" + - " description: this is our first proxy\n" + - " strategy: additive\n" + - " file: ../json/payload.json\n" + - " headers:\n" + - " x-original-stubby4j-custom-header: custom/value\n" + - " properties:\n" + - " endpoint: https://jsonplaceholder.typicode.com"; + expectedException.expectMessage( + "Invalid property 'file' configured. This property does not belong in object 'proxy-config'"); + + final String yaml = "- proxy-config:\n" + " uuid: some-unique-name\n" + + " description: this is our first proxy\n" + + " strategy: additive\n" + + " file: ../json/payload.json\n" + + " headers:\n" + + " x-original-stubby4j-custom-header: custom/value\n" + + " properties:\n" + + " endpoint: https://jsonplaceholder.typicode.com"; unmarshall(yaml); } @@ -261,12 +267,13 @@ public void shouldUnmarshall_WhenYAMLValid_WithOneSequenceResponse() throws Exce final StubResponse actualResponse = actualHttpLifecycle.getResponse(true); assertThat(actualResponse).isInstanceOf(StubResponse.class); - assertThat(actualResponse.getHeaders()).containsEntry(sequenceResponseHeaderKey, Common.HEADER_APPLICATION_JSON); - assertThat(actualResponse.getHttpStatusCode()).isEqualTo(HttpStatus.getCode(Integer.parseInt(sequenceResponseStatus))); + assertThat(actualResponse.getHeaders()) + .containsEntry(sequenceResponseHeaderKey, Common.HEADER_APPLICATION_JSON); + assertThat(actualResponse.getHttpStatusCode()) + .isEqualTo(HttpStatus.getCode(Integer.parseInt(sequenceResponseStatus))); assertThat(actualResponse.getBody()).isEqualTo(sequenceResponseBody); } - @Test public void shouldUnmarshall_AndReturnResponsesInSequence_WithManySequenceResponse() throws Exception { @@ -296,21 +303,24 @@ public void shouldUnmarshall_AndReturnResponsesInSequence_WithManySequenceRespon final StubResponse actualSequenceResponse = actualHttpLifecycle.getResponse(true); assertThat(actualSequenceResponse).isInstanceOf(StubResponse.class); - assertThat(actualSequenceResponse.getHeaders()).containsEntry(sequenceResponseHeaderKey, sequenceResponseHeaderValue); - assertThat(actualSequenceResponse.getHttpStatusCode()).isEqualTo(HttpStatus.getCode(Integer.parseInt(sequenceResponseStatus))); + assertThat(actualSequenceResponse.getHeaders()) + .containsEntry(sequenceResponseHeaderKey, sequenceResponseHeaderValue); + assertThat(actualSequenceResponse.getHttpStatusCode()) + .isEqualTo(HttpStatus.getCode(Integer.parseInt(sequenceResponseStatus))); assertThat(actualSequenceResponse.getBody()).isEqualTo(sequenceResponseBody); } - @Test public void shouldUnmarshall_WhenYAMLValid_WithUrlAsRegex() throws Exception { final String url = "^/[a-z]{3}/[0-9]+/?$"; - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl(url) .newStubbedResponse() - .withStatus("301").build(); + .withStatus("301") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -330,7 +340,8 @@ public void shouldUnmarshall_WhenYAMLValid_WithDescription() throws Exception { .withMethodGet() .withUrl(url) .newStubbedResponse() - .withStatus("301").build(); + .withStatus("301") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -351,7 +362,8 @@ public void shouldUnmarshall_WhenYAMLValid_WithUUID() throws Exception { .withMethodGet() .withUrl(url) .newStubbedResponse() - .withStatus("301").build(); + .withStatus("301") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -371,20 +383,20 @@ public void shouldUnmarshall_toCompleteYaml_WithUUIDAndDescription() throws Exce .withMethodGet() .withUrl(url) .newStubbedResponse() - .withStatus("301").build(); + .withStatus("301") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); - assertThat(actualHttpLifecycle.getCompleteYaml()).isEqualTo( - "- uuid: 9136d8b7-f7a7-478d-97a5-53292484aaf6\n" + - " description: wobble\n" + - " request:\n" + - " method:\n" + - " - GET\n" + - " url: ^/[a-z]{3}/[0-9]+/?$\n" + - " response:\n" + - " status: 301\n"); + assertThat(actualHttpLifecycle.getCompleteYaml()) + .isEqualTo("- uuid: 9136d8b7-f7a7-478d-97a5-53292484aaf6\n" + " description: wobble\n" + + " request:\n" + + " method:\n" + + " - GET\n" + + " url: ^/[a-z]{3}/[0-9]+/?$\n" + + " response:\n" + + " status: 301\n"); } @Test @@ -393,19 +405,20 @@ public void shouldUnmarshall_toCompleteYamlFromFile_WithUUIDAndDescription() thr final InputStream stubsConfigStream = yamlUrl.openStream(); final String parentDirectory = new File(yamlUrl.getPath()).getParent(); - final YamlParseResultSet yamlParseResultSet = new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); - final StubHttpLifecycle actualHttpLifecycle = yamlParseResultSet.getStubs().get(0); - - assertThat(actualHttpLifecycle.getCompleteYaml()).isEqualTo( - "- description: Stub one\n" + - " uuid: 9136d8b7-f7a7-478d-97a5-53292484aaf6\n" + - " request:\n" + - " url: ^/one$\n" + - " method: GET\n" + - " response:\n" + - " status: 200\n" + - " latency: 100\n" + - " body: One!\n"); + final YamlParseResultSet yamlParseResultSet = + new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); + final StubHttpLifecycle actualHttpLifecycle = + yamlParseResultSet.getStubs().get(0); + + assertThat(actualHttpLifecycle.getCompleteYaml()) + .isEqualTo("- description: Stub one\n" + " uuid: 9136d8b7-f7a7-478d-97a5-53292484aaf6\n" + + " request:\n" + + " url: ^/one$\n" + + " method: GET\n" + + " response:\n" + + " status: 200\n" + + " latency: 100\n" + + " body: One!\n"); assertThat(actualHttpLifecycle.getDescription()).isEqualTo("Stub one"); assertThat(actualHttpLifecycle.getUUID()).isEqualTo("9136d8b7-f7a7-478d-97a5-53292484aaf6"); @@ -423,11 +436,13 @@ public void shouldUnmarshall_toCompleteYamlFromFile() throws Exception { @Test public void shouldUnmarshall_WhenYAMLValid_WithMultipleHTTPMethods() throws Exception { - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withMethodHead() .newStubbedResponse() - .withStatus("301").build(); + .withStatus("301") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -439,10 +454,12 @@ public void shouldUnmarshall_WhenYAMLValid_WithMultipleHTTPMethods() throws Exce @Test public void shouldUnmarshall_WhenYAMLValid_WithDefaultHTTPResponseStatus() throws Exception { - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .newStubbedResponse() - .withLiteralBody("hello").build(); + .withLiteralBody("hello") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -456,12 +473,14 @@ public void shouldUnmarshall_WhenYAMLValid_WithFoldedPost() throws Exception { final String stubbedRequestPost = "{\"message\", \"Hello, this is a request post\"}"; - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .withFoldedPost(stubbedRequestPost) .newStubbedResponse() - .withStatus("201").build(); + .withStatus("201") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -476,21 +495,23 @@ public void shouldUnmarshall_WhenYAMLValid_WithFileFailedToLoadAndPostSet() thro final String stubbedRequestFile = "../../very.big.soap.request.xml"; final String expectedPost = "{\"message\", \"Hello, this is HTTP request post\"}"; - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .withFile(stubbedRequestFile) .withFoldedPost(expectedPost) .newStubbedResponse() .withLiteralBody("OK") - .withStatus("201").build(); + .withStatus("201") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); final StubRequest actualRequest = actualHttpLifecycle.getRequest(); - assertThat(actualRequest.getFile()).isEqualTo(new byte[]{}); + assertThat(actualRequest.getFile()).isEqualTo(new byte[] {}); assertThat(actualRequest.getPostBody()).isEqualTo(expectedPost); } @@ -500,14 +521,16 @@ public void shouldCaptureConsoleErrorOutput_WhenYAMLValid_WithFileFailedToLoadAn final String stubbedRequestFile = "../../very.big.soap.request.xml"; final String expectedPost = "{\"message\", \"Hello, this is HTTP request post\"}"; - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .withFile(stubbedRequestFile) .withFoldedPost(expectedPost) .newStubbedResponse() .withLiteralBody("OK") - .withStatus("201").build(); + .withStatus("201") + .build(); final ByteArrayOutputStream consoleCaptor = new ByteArrayOutputStream(); final boolean NO_AUTO_FLUSH = false; @@ -517,34 +540,37 @@ public void shouldCaptureConsoleErrorOutput_WhenYAMLValid_WithFileFailedToLoadAn System.setOut(System.out); - final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + final String actualConsoleOutput = + consoleCaptor.toString(StringUtils.UTF_8).trim(); assertThat(actualConsoleOutput).contains("Could not load file from path: ../../very.big.soap.request.xml"); assertThat(actualConsoleOutput).contains(YamlParser.FAILED_TO_LOAD_FILE_ERR); } - @Test public void shouldUnmarshall_WhenYAMLValid_WithFileFailedToLoadAndBodySet() throws Exception { final String stubbedResponseFile = "../../very.big.soap.response.xml"; final String expectedBody = "{\"message\", \"Hello, this is HTTP response body\"}"; - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .newStubbedResponse() .withFoldedBody(expectedBody) .withFile(stubbedResponseFile) - .withStatus("201").build(); + .withStatus("201") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); final StubResponse actualResponse = actualHttpLifecycle.getResponse(true); - assertThat(actualResponse.getFile()).isEqualTo(new byte[]{}); - assertThat(StringUtils.newStringUtf8(actualResponse.getResponseBodyAsBytes())).isEqualTo(expectedBody); + assertThat(actualResponse.getFile()).isEqualTo(new byte[] {}); + assertThat(StringUtils.newStringUtf8(actualResponse.getResponseBodyAsBytes())) + .isEqualTo(expectedBody); } @Test @@ -553,13 +579,15 @@ public void shouldCaptureConsoleErrorOutput_WhenYAMLValid_WithFileFailedToLoadAn final String stubbedResponseFile = "../../very.big.soap.response.xml"; final String expectedBody = "{\"message\", \"Hello, this is HTTP response body\"}"; - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .newStubbedResponse() .withFoldedBody(expectedBody) .withFile(stubbedResponseFile) - .withStatus("201").build(); + .withStatus("201") + .build(); final ByteArrayOutputStream consoleCaptor = new ByteArrayOutputStream(); final boolean NO_AUTO_FLUSH = false; @@ -569,7 +597,8 @@ public void shouldCaptureConsoleErrorOutput_WhenYAMLValid_WithFileFailedToLoadAn System.setOut(System.out); - final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + final String actualConsoleOutput = + consoleCaptor.toString(StringUtils.UTF_8).trim(); assertThat(actualConsoleOutput).contains("Could not load file from path: ../../very.big.soap.response.xml"); assertThat(actualConsoleOutput).contains(YamlParser.FAILED_TO_LOAD_FILE_ERR); @@ -580,12 +609,14 @@ public void shouldUnmarshall_WhenYAMLValid_WithLiteralPost() throws Exception { final String stubbedRequestPost = "Hello, this is a request post"; - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .withLiteralPost(stubbedRequestPost) .newStubbedResponse() - .withStatus("201").build(); + .withStatus("201") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -600,27 +631,30 @@ public void shouldFailUnmarshallYaml_WithJsonAsLiteralPost() throws Exception { expectedException.expect(ClassCastException.class); expectedException.expectMessage("Expected: java.lang.String, instead got: java.util.LinkedHashMap"); - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .withLiteralPost("{\"message\", \"Hello, this is a request body\"}") .newStubbedResponse() - .withStatus("201").build(); + .withStatus("201") + .build(); unmarshall(yaml); } - @Test public void shouldUnmarshall_WhenYAMLValid_WithFoldedBody() throws Exception { final String stubbedResponseBody = "{\"message\", \"Hello, this is a response body\"}"; - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .newStubbedResponse() - .withFoldedBody(stubbedResponseBody).build(); + .withFoldedBody(stubbedResponseBody) + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -634,11 +668,13 @@ public void shouldFailUnmarshallYaml_WithJsonAsLiteralBody() throws Exception { expectedException.expect(ClassCastException.class); - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .newStubbedResponse() - .withLiteralBody("{\"message\", \"Hello, this is a response body\"}").build(); + .withLiteralBody("{\"message\", \"Hello, this is a response body\"}") + .build(); unmarshall(yaml); } @@ -648,11 +684,13 @@ public void shouldUnmarshall_WhenYAMLValid_WithLiteralBody() throws Exception { final String stubbedResponseBody = "This is a sentence"; - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .newStubbedResponse() - .withLiteralBody(stubbedResponseBody).build(); + .withLiteralBody(stubbedResponseBody) + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -661,7 +699,6 @@ public void shouldUnmarshall_WhenYAMLValid_WithLiteralBody() throws Exception { assertThat(actualResponse.getBody()).isEqualTo(stubbedResponseBody); } - @Test public void shouldUnmarshall_WhenYAMLValid_WithMultipleQueryParams() throws Exception { @@ -673,13 +710,15 @@ public void shouldUnmarshall_WhenYAMLValid_WithMultipleQueryParams() throws Exce final String expectedParamTwoValue = "two"; final String fullQueryTwo = String.format("%s=%s", expectedParamTwo, expectedParamTwoValue); - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .withQuery(expectedParamOne, expectedParamOneValue) .withQuery(expectedParamTwo, expectedParamTwoValue) .newStubbedResponse() - .withStatus("500").build(); + .withStatus("500") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -696,18 +735,21 @@ public void shouldUnmarshall_WhenYAMLValid_WithAuthorizationHeaderBasic() throws final String authorization = "bob:secret"; - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .withHeaderAuthorizationBasic(authorization) .newStubbedResponse() - .withStatus("301").build(); + .withStatus("301") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); final StubRequest actualRequest = actualHttpLifecycle.getRequest(); - final String encodedAuthorizationHeader = String.format("%s %s", "Basic", StringUtils.encodeBase64(authorization)); + final String encodedAuthorizationHeader = + String.format("%s %s", "Basic", StringUtils.encodeBase64(authorization)); assertThat(actualRequest.getHeaders()).containsEntry(BASIC.asYAMLProp(), encodedAuthorizationHeader); } @@ -715,12 +757,14 @@ public void shouldUnmarshall_WhenYAMLValid_WithAuthorizationHeaderBasic() throws @Test public void shouldUnmarshall_WhenYAMLValid_WithEmptyAuthorizationHeaderBasic() throws Exception { - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .withHeaderAuthorizationBasic("") .newStubbedResponse() - .withStatus("301").build(); + .withStatus("301") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -736,12 +780,14 @@ public void shouldUnmarshall_WhenYAMLValid_WithAuthorizationHeaderBearer() throw final String authorization = "Ym9iOnNlY3JldA=="; - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .withHeaderAuthorizationBearer(authorization) .newStubbedResponse() - .withStatus("301").build(); + .withStatus("301") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -755,12 +801,14 @@ public void shouldUnmarshall_WhenYAMLValid_WithAuthorizationHeaderBearer() throw @Test public void shouldUnmarshall_WhenYAMLValid_WithEmptyAuthorizationHeaderBearer() throws Exception { - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .withHeaderAuthorizationBearer("") .newStubbedResponse() - .withStatus("301").build(); + .withStatus("301") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -776,12 +824,14 @@ public void shouldUnmarshall_WhenYAMLValid_WithAuthorizationHeaderCustom() throw final String authorizationHeader = "CustomAuthorizationName AuthorizationValue"; - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .withHeaderAuthorizationCustom(authorizationHeader) .newStubbedResponse() - .withStatus("301").build(); + .withStatus("301") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -793,12 +843,14 @@ public void shouldUnmarshall_WhenYAMLValid_WithAuthorizationHeaderCustom() throw @Test public void shouldUnmarshall_WhenYAMLValid_WithEmptyAuthorizationHeaderCustom() throws Exception { - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .withHeaderAuthorizationCustom("") .newStubbedResponse() - .withStatus("301").build(); + .withStatus("301") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -813,12 +865,14 @@ public void shouldUnmarshall_WhenYAMLValid_WithMultipleHeaders() throws Exceptio final String location = "/invoice/123"; final String contentType = "application-json"; - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .newStubbedResponse() .withHeaderContentType(contentType) - .withHeaderLocation(location).build(); + .withHeaderLocation(location) + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -828,7 +882,6 @@ public void shouldUnmarshall_WhenYAMLValid_WithMultipleHeaders() throws Exceptio assertThat(actualResponse.getHeaders()).containsEntry("content-type", contentType); } - @Test public void shouldUnmarshall_WhenYAMLValid_WitQueryParamIsArrayHavingDoubleQuotes() throws Exception { @@ -836,12 +889,14 @@ public void shouldUnmarshall_WhenYAMLValid_WitQueryParamIsArrayHavingDoubleQuote final String expectedParamOneValue = "[\"apple\",\"orange\",\"banana\"]"; final String fullQueryOne = String.format("%s=%s", expectedParamOne, expectedParamOneValue); - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .withQuery(expectedParamOne, String.format("'%s'", expectedParamOneValue)) .newStubbedResponse() - .withStatus("201").build(); + .withStatus("201") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -858,12 +913,14 @@ public void shouldUnmarshall_WhenYAMLValid_WitQueryParamIsArrayHavingSingleQuote final String expectedParamOneValue = "['apple','orange','banana']"; final String fullQueryOne = String.format("%s=%s", expectedParamOne, expectedParamOneValue); - final String yaml = yamlBuilder.newStubbedRequest() + final String yaml = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri") .withQuery(expectedParamOne, String.format("\"%s\"", expectedParamOneValue)) .newStubbedResponse() - .withStatus("201").build(); + .withStatus("201") + .build(); final List loadedHttpCycles = unmarshall(yaml).getStubs(); final StubHttpLifecycle actualHttpLifecycle = loadedHttpCycles.get(0); @@ -874,7 +931,8 @@ public void shouldUnmarshall_WhenYAMLValid_WitQueryParamIsArrayHavingSingleQuote } @Test - public void shouldContainExpectedResourceIdHeaderUponSuccessfulYamlMarshall_WhenMultipleResponses() throws Exception { + public void shouldContainExpectedResourceIdHeaderUponSuccessfulYamlMarshall_WhenMultipleResponses() + throws Exception { final String cycleOne = yamlBuilder .newStubbedRequest() @@ -885,7 +943,8 @@ public void shouldContainExpectedResourceIdHeaderUponSuccessfulYamlMarshall_When .withStatus("200") .build(); - final String cycleTwo = yamlBuilder.newStubbedRequest() + final String cycleTwo = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri/2") .withQuery("paramName2", "paramValue2") @@ -893,7 +952,8 @@ public void shouldContainExpectedResourceIdHeaderUponSuccessfulYamlMarshall_When .withStatus("201") .build(); - final List loadedHttpCycles = unmarshall(String.format("%s\n%s", cycleOne, cycleTwo)).getStubs(); + final List loadedHttpCycles = + unmarshall(String.format("%s\n%s", cycleOne, cycleTwo)).getStubs(); assertThat(loadedHttpCycles.size()).isEqualTo(2); for (int idx = 0; idx < loadedHttpCycles.size(); idx++) { @@ -901,7 +961,8 @@ public void shouldContainExpectedResourceIdHeaderUponSuccessfulYamlMarshall_When final StubResponse cycleResponse = cycle.getResponse(true); assertThat(cycleResponse.getHeaders()).containsKey(Common.HEADER_X_STUBBY_RESOURCE_ID); - assertThat(cycleResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)).isEqualTo(String.valueOf(idx)); + assertThat(cycleResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)) + .isEqualTo(String.valueOf(idx)); } } @@ -930,12 +991,14 @@ public void shouldContainTheSameResourceIdHeader_ForEachSequencedResponse() thro for (int idx = 0; idx < allResponses.size(); idx++) { final StubResponse sequenceStubResponse = allResponses.get(idx); assertThat(sequenceStubResponse.getHeaders()).containsKey(Common.HEADER_X_STUBBY_RESOURCE_ID); - assertThat(sequenceStubResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)).isEqualTo(String.valueOf(0)); + assertThat(sequenceStubResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)) + .isEqualTo(String.valueOf(0)); } } @Test - public void shouldContainExpectedResourceIdHeaderUponSuccessfulYamlMarshall_WhenMultipleAndSqequencedResponses() throws Exception { + public void shouldContainExpectedResourceIdHeaderUponSuccessfulYamlMarshall_WhenMultipleAndSqequencedResponses() + throws Exception { final String cycleOne = yamlBuilder .newStubbedRequest() @@ -959,7 +1022,8 @@ public void shouldContainExpectedResourceIdHeaderUponSuccessfulYamlMarshall_When .withSequenceResponseLiteralBody("BodyContentTwo") .build(); - final String cycleThree = yamlBuilder.newStubbedRequest() + final String cycleThree = yamlBuilder + .newStubbedRequest() .withMethodGet() .withUrl("/some/uri/2") .withQuery("paramName2", "paramValue2") @@ -967,7 +1031,9 @@ public void shouldContainExpectedResourceIdHeaderUponSuccessfulYamlMarshall_When .withStatus("201") .build(); - final List loadedHttpCycles = unmarshall(String.format("%s%s%s%s%s", cycleOne, BR, cycleTwo, BR, cycleThree)).getStubs(); + final List loadedHttpCycles = unmarshall( + String.format("%s%s%s%s%s", cycleOne, BR, cycleTwo, BR, cycleThree)) + .getStubs(); assertThat(loadedHttpCycles.size()).isEqualTo(3); for (int resourceId = 0; resourceId < loadedHttpCycles.size(); resourceId++) { @@ -977,7 +1043,8 @@ public void shouldContainExpectedResourceIdHeaderUponSuccessfulYamlMarshall_When for (int sequence = 0; sequence < allResponses.size(); sequence++) { final StubResponse sequenceStubResponse = allResponses.get(sequence); assertThat(sequenceStubResponse.getHeaders()).containsKey(Common.HEADER_X_STUBBY_RESOURCE_ID); - assertThat(sequenceStubResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)).isEqualTo(String.valueOf(resourceId)); + assertThat(sequenceStubResponse.getHeaders().get(Common.HEADER_X_STUBBY_RESOURCE_ID)) + .isEqualTo(String.valueOf(resourceId)); } } } @@ -988,34 +1055,34 @@ public void shouldUnmarshall_toCompleteYamlFromFile_WithIncludes() throws Except final InputStream stubsConfigStream = yamlUrl.openStream(); final String parentDirectory = new File(yamlUrl.getPath()).getParent(); - final YamlParseResultSet yamlParseResultSet = new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); - - final StubHttpLifecycle actualHttpLifecycle = yamlParseResultSet.getStubs().get(0); - assertThat(actualHttpLifecycle.getCompleteYaml()).isEqualTo( - "- request:\n" + - " method:\n" + - " - GET\n" + - " - POST\n" + - " - PUT\n" + - " url: ^/resources/asn/.*$\n" + - " response:\n" + - " status: 200\n" + - " body: |\n" + - " {\"status\": \"ASN found!\"}\n" + - " headers:\n" + - " content-type: application/json\n"); - - final StubHttpLifecycle actualLastHttpLifecycle = yamlParseResultSet.getStubs().get(3); - assertThat(actualLastHttpLifecycle.getCompleteYaml()).isEqualTo( - "- request:\n" + - " url: /individuals/.*/address$\n" + - " method: PUT\n" + - " post: |\n" + - " {\"type\": \"HOME\"}\n" + - " response:\n" + - " body: OK\n" + - " status: 200\n"); - + final YamlParseResultSet yamlParseResultSet = + new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); + + final StubHttpLifecycle actualHttpLifecycle = + yamlParseResultSet.getStubs().get(0); + assertThat(actualHttpLifecycle.getCompleteYaml()) + .isEqualTo("- request:\n" + " method:\n" + + " - GET\n" + + " - POST\n" + + " - PUT\n" + + " url: ^/resources/asn/.*$\n" + + " response:\n" + + " status: 200\n" + + " body: |\n" + + " {\"status\": \"ASN found!\"}\n" + + " headers:\n" + + " content-type: application/json\n"); + + final StubHttpLifecycle actualLastHttpLifecycle = + yamlParseResultSet.getStubs().get(3); + assertThat(actualLastHttpLifecycle.getCompleteYaml()) + .isEqualTo("- request:\n" + " url: /individuals/.*/address$\n" + + " method: PUT\n" + + " post: |\n" + + " {\"type\": \"HOME\"}\n" + + " response:\n" + + " body: OK\n" + + " status: 200\n"); } @Test @@ -1025,8 +1092,8 @@ public void shouldLoadYamlIncludesAsFileObjects() throws Exception { final String parentDirectory = new File(yamlUrl.getPath()).getParent(); final YamlParser yamlParser = new YamlParser(); - final List yamlIncludes = yamlParser.getYamlIncludes(parentDirectory, - yamlParser.loadRawYamlConfig(stubsConfigStream)); + final List yamlIncludes = + yamlParser.getYamlIncludes(parentDirectory, yamlParser.loadRawYamlConfig(stubsConfigStream)); assertThat(yamlIncludes.isEmpty()).isFalse(); assertThat(yamlIncludes.size()).isEqualTo(3); @@ -1039,7 +1106,8 @@ public void shouldUnmarshall_toProxyConfigs() throws Exception { final InputStream stubsConfigStream = yamlUrl.openStream(); final String parentDirectory = new File(yamlUrl.getPath()).getParent(); - final YamlParseResultSet yamlParseResultSet = new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); + final YamlParseResultSet yamlParseResultSet = + new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); final Map proxyConfigs = yamlParseResultSet.getProxyConfigs(); assertThat(proxyConfigs.isEmpty()).isFalse(); @@ -1047,31 +1115,31 @@ public void shouldUnmarshall_toProxyConfigs() throws Exception { assertThat(defaultStubProxyConfig.getUUID()).isEqualTo("default"); assertThat(defaultStubProxyConfig.getStrategy()).isEqualTo(StubProxyStrategy.AS_IS); assertThat(defaultStubProxyConfig.getProperties().size()).isEqualTo(1); - assertThat(defaultStubProxyConfig.getProperties().get("endpoint")).isEqualTo("https://jsonplaceholder.typicode.com"); + assertThat(defaultStubProxyConfig.getProperties().get("endpoint")) + .isEqualTo("https://jsonplaceholder.typicode.com"); final StubProxyConfig customStubProxyConfig = proxyConfigs.get("some-unique-name"); assertThat(customStubProxyConfig.getUUID()).isEqualTo("some-unique-name"); assertThat(customStubProxyConfig.getStrategy()).isEqualTo(StubProxyStrategy.ADDITIVE); assertThat(customStubProxyConfig.getProperties().size()).isEqualTo(1); - assertThat(customStubProxyConfig.getProperties().get("endpoint")).isEqualTo("https://jsonplaceholder.typicode.com"); - - assertThat(defaultStubProxyConfig.getProxyConfigAsYAML()).isEqualTo( - "- proxy-config:\n" + - " description: this is a default catch-all config\n" + - " strategy: as-is\n" + - " properties:\n" + - " endpoint: https://jsonplaceholder.typicode.com\n" + - " headers:\n" + - " headerKeyOne: headerValueOne\n" + - " headerKeyTwo: headerValueTwo\n"); - - assertThat(customStubProxyConfig.getProxyConfigAsYAML()).isEqualTo( - "- proxy-config:\n" + - " description: woah! this is a unique proxy-config\n" + - " uuid: some-unique-name\n" + - " strategy: additive\n" + - " properties:\n" + - " endpoint: https://jsonplaceholder.typicode.com\n"); + assertThat(customStubProxyConfig.getProperties().get("endpoint")) + .isEqualTo("https://jsonplaceholder.typicode.com"); + + assertThat(defaultStubProxyConfig.getProxyConfigAsYAML()) + .isEqualTo("- proxy-config:\n" + " description: this is a default catch-all config\n" + + " strategy: as-is\n" + + " properties:\n" + + " endpoint: https://jsonplaceholder.typicode.com\n" + + " headers:\n" + + " headerKeyOne: headerValueOne\n" + + " headerKeyTwo: headerValueTwo\n"); + + assertThat(customStubProxyConfig.getProxyConfigAsYAML()) + .isEqualTo("- proxy-config:\n" + " description: woah! this is a unique proxy-config\n" + + " uuid: some-unique-name\n" + + " strategy: additive\n" + + " properties:\n" + + " endpoint: https://jsonplaceholder.typicode.com\n"); } @Test @@ -1080,7 +1148,8 @@ public void shouldUnmarshall_toProxyConfigsWithStubs() throws Exception { final InputStream stubsConfigStream = yamlUrl.openStream(); final String parentDirectory = new File(yamlUrl.getPath()).getParent(); - final YamlParseResultSet yamlParseResultSet = new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); + final YamlParseResultSet yamlParseResultSet = + new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); final Map proxyConfigs = yamlParseResultSet.getProxyConfigs(); assertThat(proxyConfigs.isEmpty()).isFalse(); @@ -1094,26 +1163,26 @@ public void shouldUnmarshall_toProxyConfigsWithStubs() throws Exception { assertThat(defaultStubProxyConfig.getUUID()).isEqualTo("default"); assertThat(defaultStubProxyConfig.getStrategy()).isEqualTo(StubProxyStrategy.AS_IS); assertThat(defaultStubProxyConfig.getProperties().size()).isEqualTo(1); - assertThat(defaultStubProxyConfig.getProperties().get("endpoint")).isEqualTo("https://jsonplaceholder.typicode.com"); + assertThat(defaultStubProxyConfig.getProperties().get("endpoint")) + .isEqualTo("https://jsonplaceholder.typicode.com"); final StubProxyConfig customStubProxyConfig = proxyConfigs.get("some-unique-name"); assertThat(customStubProxyConfig.getUUID()).isEqualTo("some-unique-name"); assertThat(customStubProxyConfig.getStrategy()).isEqualTo(StubProxyStrategy.ADDITIVE); assertThat(customStubProxyConfig.getProperties().size()).isEqualTo(1); - assertThat(customStubProxyConfig.getProperties().get("endpoint")).isEqualTo("https://jsonplaceholder.typicode.com"); - - assertThat(defaultStubProxyConfig.getProxyConfigAsYAML()).isEqualTo( - "- proxy-config:\n" + - " strategy: as-is\n" + - " properties:\n" + - " endpoint: https://jsonplaceholder.typicode.com\n"); - - assertThat(customStubProxyConfig.getProxyConfigAsYAML()).isEqualTo( - "- proxy-config:\n" + - " uuid: some-unique-name\n" + - " strategy: additive\n" + - " properties:\n" + - " endpoint: https://jsonplaceholder.typicode.com\n"); + assertThat(customStubProxyConfig.getProperties().get("endpoint")) + .isEqualTo("https://jsonplaceholder.typicode.com"); + + assertThat(defaultStubProxyConfig.getProxyConfigAsYAML()) + .isEqualTo("- proxy-config:\n" + " strategy: as-is\n" + + " properties:\n" + + " endpoint: https://jsonplaceholder.typicode.com\n"); + + assertThat(customStubProxyConfig.getProxyConfigAsYAML()) + .isEqualTo("- proxy-config:\n" + " uuid: some-unique-name\n" + + " strategy: additive\n" + + " properties:\n" + + " endpoint: https://jsonplaceholder.typicode.com\n"); } @Test @@ -1156,13 +1225,15 @@ public void shouldUnmarshall_toWebSocketConfigs() throws Exception { final InputStream stubsConfigStream = yamlUrl.openStream(); final String parentDirectory = new File(yamlUrl.getPath()).getParent(); - final YamlParseResultSet yamlParseResultSet = new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); + final YamlParseResultSet yamlParseResultSet = + new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); final Map webSocketConfigs = yamlParseResultSet.getWebSocketConfigs(); assertThat(webSocketConfigs.isEmpty()).isFalse(); assertThat(webSocketConfigs.size()).isEqualTo(3); - final StubWebSocketConfig stubWebSocketConfig = webSocketConfigs.values().iterator().next(); + final StubWebSocketConfig stubWebSocketConfig = + webSocketConfigs.values().iterator().next(); final StubWebSocketConfig stubWebSocketConfigCopy = webSocketConfigs.get(stubWebSocketConfig.getUrl()); assertThat(stubWebSocketConfig).isSameInstanceAs(stubWebSocketConfigCopy); assertThat(stubWebSocketConfig).isEqualTo(stubWebSocketConfigCopy); @@ -1180,19 +1251,18 @@ public void shouldUnmarshall_toWebSocketConfigs() throws Exception { assertThat(onOpenServerResponse.getMessageType()).isEqualTo(StubWebSocketMessageType.TEXT); assertThat(onOpenServerResponse.getPolicy()).isEqualTo(StubWebSocketServerResponsePolicy.ONCE); - final StubWebSocketOnMessageLifeCycle stubWebSocketOnMessageLifeCycle = stubWebSocketConfig.getOnMessage().get(0); + final StubWebSocketOnMessageLifeCycle stubWebSocketOnMessageLifeCycle = + stubWebSocketConfig.getOnMessage().get(0); assertThat(stubWebSocketOnMessageLifeCycle.getClientRequest()).isNotNull(); assertThat(stubWebSocketOnMessageLifeCycle.getServerResponse()).isNotNull(); - assertThat(stubWebSocketOnMessageLifeCycle.getCompleteYAML()).isEqualTo( - "- client-request:\n" + - " message-type: text\n" + - " body: Hey, server, say apple\n" + - " server-response:\n" + - " policy: push\n" + - " message-type: text\n" + - " body: apple\n" + - " delay: 500\n" - ); + assertThat(stubWebSocketOnMessageLifeCycle.getCompleteYAML()) + .isEqualTo("- client-request:\n" + " message-type: text\n" + + " body: Hey, server, say apple\n" + + " server-response:\n" + + " policy: push\n" + + " message-type: text\n" + + " body: apple\n" + + " delay: 500\n"); final StubWebSocketClientRequest clientRequest = stubWebSocketOnMessageLifeCycle.getClientRequest(); assertThat(clientRequest.getMessageType()).isEqualTo(StubWebSocketMessageType.TEXT); @@ -1204,45 +1274,45 @@ public void shouldUnmarshall_toWebSocketConfigs() throws Exception { assertThat(serverResponse.getMessageType()).isEqualTo(StubWebSocketMessageType.TEXT); assertThat(serverResponse.getPolicy()).isEqualTo(StubWebSocketServerResponsePolicy.PUSH); - final StubWebSocketServerResponse lastServerResponse = stubWebSocketConfig.getOnMessage().get(2).getServerResponse(); + final StubWebSocketServerResponse lastServerResponse = + stubWebSocketConfig.getOnMessage().get(2).getServerResponse(); final String actualFileContent = "This is response 1 content"; assertThat(lastServerResponse.getBodyAsString()).isEqualTo(actualFileContent); assertThat(lastServerResponse.getBodyAsBytes()).isEqualTo(getBytesUtf8(actualFileContent)); final String expectedWebSocketConfigAsYAML = - "- web-socket:\n" + - " description: this is a web-socket config\n" + - " url: /items/furniture\n" + - " sub-protocols: echo, mamba, zumba\n" + - " on-open:\n" + - " policy: once\n" + - " message-type: text\n" + - " body: You have been successfully connected\n" + - " delay: 2000\n" + - " on-message:\n" + - " - client-request:\n" + - " message-type: text\n" + - " body: Hey, server, say apple\n" + - " server-response:\n" + - " policy: push\n" + - " message-type: text\n" + - " body: apple\n" + - " delay: 500\n" + - " - client-request:\n" + - " message-type: text\n" + - " body: JSON file\n" + - " server-response:\n" + - " policy: push\n" + - " message-type: text\n" + - " body: no files for you\n" + - " delay: 250\n" + - " - client-request:\n" + - " message-type: text\n" + - " body: JSON file, please\n" + - " server-response:\n" + - " policy: disconnect\n" + - " message-type: text\n" + - " file: ../json/response.1.external.file.json\n"; + "- web-socket:\n" + " description: this is a web-socket config\n" + + " url: /items/furniture\n" + + " sub-protocols: echo, mamba, zumba\n" + + " on-open:\n" + + " policy: once\n" + + " message-type: text\n" + + " body: You have been successfully connected\n" + + " delay: 2000\n" + + " on-message:\n" + + " - client-request:\n" + + " message-type: text\n" + + " body: Hey, server, say apple\n" + + " server-response:\n" + + " policy: push\n" + + " message-type: text\n" + + " body: apple\n" + + " delay: 500\n" + + " - client-request:\n" + + " message-type: text\n" + + " body: JSON file\n" + + " server-response:\n" + + " policy: push\n" + + " message-type: text\n" + + " body: no files for you\n" + + " delay: 250\n" + + " - client-request:\n" + + " message-type: text\n" + + " body: JSON file, please\n" + + " server-response:\n" + + " policy: disconnect\n" + + " message-type: text\n" + + " file: ../json/response.1.external.file.json\n"; assertThat(stubWebSocketConfig.getWebSocketConfigAsYAML()).isEqualTo(expectedWebSocketConfigAsYAML); } @@ -1252,13 +1322,15 @@ public void shouldUnmarshall_toWebSocketConfigs_withoutOnOpenSection() throws Ex final InputStream stubsConfigStream = yamlUrl.openStream(); final String parentDirectory = new File(yamlUrl.getPath()).getParent(); - final YamlParseResultSet yamlParseResultSet = new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); + final YamlParseResultSet yamlParseResultSet = + new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); final Map webSocketConfigs = yamlParseResultSet.getWebSocketConfigs(); assertThat(webSocketConfigs.isEmpty()).isFalse(); assertThat(webSocketConfigs.size()).isEqualTo(2); - final StubWebSocketConfig stubWebSocketConfig = webSocketConfigs.values().iterator().next(); + final StubWebSocketConfig stubWebSocketConfig = + webSocketConfigs.values().iterator().next(); final StubWebSocketConfig stubWebSocketConfigCopy = webSocketConfigs.get(stubWebSocketConfig.getUrl()); assertThat(stubWebSocketConfig).isSameInstanceAs(stubWebSocketConfigCopy); assertThat(stubWebSocketConfig).isEqualTo(stubWebSocketConfigCopy); @@ -1271,19 +1343,18 @@ public void shouldUnmarshall_toWebSocketConfigs_withoutOnOpenSection() throws Ex assertThat(stubWebSocketConfig.getOnOpenServerResponse()).isNull(); - final StubWebSocketOnMessageLifeCycle stubWebSocketOnMessageLifeCycle = stubWebSocketConfig.getOnMessage().get(0); + final StubWebSocketOnMessageLifeCycle stubWebSocketOnMessageLifeCycle = + stubWebSocketConfig.getOnMessage().get(0); assertThat(stubWebSocketOnMessageLifeCycle.getClientRequest()).isNotNull(); assertThat(stubWebSocketOnMessageLifeCycle.getServerResponse()).isNotNull(); - assertThat(stubWebSocketOnMessageLifeCycle.getCompleteYAML()).isEqualTo( - "- client-request:\n" + - " message-type: text\n" + - " body: Hey, server, say apple\n" + - " server-response:\n" + - " policy: push\n" + - " message-type: text\n" + - " body: apple\n" + - " delay: 500\n" - ); + assertThat(stubWebSocketOnMessageLifeCycle.getCompleteYAML()) + .isEqualTo("- client-request:\n" + " message-type: text\n" + + " body: Hey, server, say apple\n" + + " server-response:\n" + + " policy: push\n" + + " message-type: text\n" + + " body: apple\n" + + " delay: 500\n"); final StubWebSocketClientRequest clientRequest = stubWebSocketOnMessageLifeCycle.getClientRequest(); assertThat(clientRequest.getMessageType()).isEqualTo(StubWebSocketMessageType.TEXT); @@ -1295,40 +1366,40 @@ public void shouldUnmarshall_toWebSocketConfigs_withoutOnOpenSection() throws Ex assertThat(serverResponse.getMessageType()).isEqualTo(StubWebSocketMessageType.TEXT); assertThat(serverResponse.getPolicy()).isEqualTo(StubWebSocketServerResponsePolicy.PUSH); - final StubWebSocketServerResponse lastServerResponse = stubWebSocketConfig.getOnMessage().get(2).getServerResponse(); + final StubWebSocketServerResponse lastServerResponse = + stubWebSocketConfig.getOnMessage().get(2).getServerResponse(); final String actualFileContent = "This is response 1 content"; assertThat(lastServerResponse.getBodyAsString()).isEqualTo(actualFileContent); assertThat(lastServerResponse.getBodyAsBytes()).isEqualTo(getBytesUtf8(actualFileContent)); final String expectedWebSocketConfigAsYAML = - "- web-socket:\n" + - " description: this is a web-socket config\n" + - " url: /items/furniture\n" + - " sub-protocols: echo, mamba, zumba\n" + - " on-message:\n" + - " - client-request:\n" + - " message-type: text\n" + - " body: Hey, server, say apple\n" + - " server-response:\n" + - " policy: push\n" + - " message-type: text\n" + - " body: apple\n" + - " delay: 500\n" + - " - client-request:\n" + - " message-type: text\n" + - " body: JSON file\n" + - " server-response:\n" + - " policy: push\n" + - " message-type: text\n" + - " body: no files for you\n" + - " delay: 250\n" + - " - client-request:\n" + - " message-type: text\n" + - " body: JSON file, please\n" + - " server-response:\n" + - " policy: disconnect\n" + - " message-type: text\n" + - " file: ../json/response.1.external.file.json\n"; + "- web-socket:\n" + " description: this is a web-socket config\n" + + " url: /items/furniture\n" + + " sub-protocols: echo, mamba, zumba\n" + + " on-message:\n" + + " - client-request:\n" + + " message-type: text\n" + + " body: Hey, server, say apple\n" + + " server-response:\n" + + " policy: push\n" + + " message-type: text\n" + + " body: apple\n" + + " delay: 500\n" + + " - client-request:\n" + + " message-type: text\n" + + " body: JSON file\n" + + " server-response:\n" + + " policy: push\n" + + " message-type: text\n" + + " body: no files for you\n" + + " delay: 250\n" + + " - client-request:\n" + + " message-type: text\n" + + " body: JSON file, please\n" + + " server-response:\n" + + " policy: disconnect\n" + + " message-type: text\n" + + " file: ../json/response.1.external.file.json\n"; assertThat(stubWebSocketConfig.getWebSocketConfigAsYAML()).isEqualTo(expectedWebSocketConfigAsYAML); } @@ -1338,13 +1409,15 @@ public void shouldUnmarshall_toWebSocketConfigsWithoutOnMessage() throws Excepti final InputStream stubsConfigStream = yamlUrl.openStream(); final String parentDirectory = new File(yamlUrl.getPath()).getParent(); - final YamlParseResultSet yamlParseResultSet = new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); + final YamlParseResultSet yamlParseResultSet = + new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); final Map webSocketConfigs = yamlParseResultSet.getWebSocketConfigs(); assertThat(webSocketConfigs.isEmpty()).isFalse(); assertThat(webSocketConfigs.size()).isEqualTo(1); - final StubWebSocketConfig stubWebSocketConfig = webSocketConfigs.values().iterator().next(); + final StubWebSocketConfig stubWebSocketConfig = + webSocketConfigs.values().iterator().next(); final StubWebSocketConfig stubWebSocketConfigCopy = webSocketConfigs.get(stubWebSocketConfig.getUrl()); assertThat(stubWebSocketConfig).isSameInstanceAs(stubWebSocketConfigCopy); assertThat(stubWebSocketConfig).isEqualTo(stubWebSocketConfigCopy); @@ -1359,17 +1432,20 @@ public void shouldUnmarshall_toWebSocketConfigsWithoutOnMessage() throws Excepti @Test public void shouldUnmarshall_toWebSocketConfigsWithUuidAndDescription() throws Exception { - final URL yamlUrl = YamlParserTest.class.getResource("/yaml/web-socket-valid-config-with-uuid-and-description-on-top.yaml"); + final URL yamlUrl = + YamlParserTest.class.getResource("/yaml/web-socket-valid-config-with-uuid-and-description-on-top.yaml"); final InputStream stubsConfigStream = yamlUrl.openStream(); final String parentDirectory = new File(yamlUrl.getPath()).getParent(); - final YamlParseResultSet yamlParseResultSet = new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); + final YamlParseResultSet yamlParseResultSet = + new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); final Map webSocketConfigs = yamlParseResultSet.getWebSocketConfigs(); assertThat(webSocketConfigs.isEmpty()).isFalse(); assertThat(webSocketConfigs.size()).isEqualTo(1); - final StubWebSocketConfig stubWebSocketConfig = webSocketConfigs.values().iterator().next(); + final StubWebSocketConfig stubWebSocketConfig = + webSocketConfigs.values().iterator().next(); final StubWebSocketConfig stubWebSocketConfigCopy = webSocketConfigs.get(stubWebSocketConfig.getUrl()); assertThat(stubWebSocketConfig).isSameInstanceAs(stubWebSocketConfigCopy); assertThat(stubWebSocketConfig).isEqualTo(stubWebSocketConfigCopy); @@ -1387,7 +1463,8 @@ public void shouldUnmarshall_toWebSocketConfigsWithUuidAndDescription() throws E public void shouldThrowWhenWebSocketConfigWithInvalidServerResponsePolicyName() throws Exception { Exception exception = assertThrows(IllegalArgumentException.class, () -> { - final URL yamlUrl = YamlParserTest.class.getResource("/yaml/web-socket-invalid-config-with-invalid-policy-name.yaml"); + final URL yamlUrl = + YamlParserTest.class.getResource("/yaml/web-socket-invalid-config-with-invalid-policy-name.yaml"); final InputStream stubsConfigStream = yamlUrl.openStream(); final String parentDirectory = new File(yamlUrl.getPath()).getParent(); @@ -1404,7 +1481,8 @@ public void shouldThrowWhenWebSocketConfigWithInvalidServerResponsePolicyName() public void shouldThrowWhenWebSocketConfigWithDuplicateURL() throws Exception { Exception exception = assertThrows(IOException.class, () -> { - final URL yamlUrl = YamlParserTest.class.getResource("/yaml/web-socket-invalid-config-with-duplicate-url.yaml"); + final URL yamlUrl = + YamlParserTest.class.getResource("/yaml/web-socket-invalid-config-with-duplicate-url.yaml"); final InputStream stubsConfigStream = yamlUrl.openStream(); final String parentDirectory = new File(yamlUrl.getPath()).getParent(); @@ -1421,7 +1499,8 @@ public void shouldThrowWhenWebSocketConfigWithDuplicateURL() throws Exception { public void shouldThrowWhenWebSocketConfigWithDuplicateClientRequestBodyText() throws Exception { Exception exception = assertThrows(UncheckedIOException.class, () -> { - final URL yamlUrl = YamlParserTest.class.getResource("/yaml/web-socket-invalid-config-with-duplicate-client-request-body-text.yaml"); + final URL yamlUrl = YamlParserTest.class.getResource( + "/yaml/web-socket-invalid-config-with-duplicate-client-request-body-text.yaml"); final InputStream stubsConfigStream = yamlUrl.openStream(); final String parentDirectory = new File(yamlUrl.getPath()).getParent(); @@ -1438,7 +1517,8 @@ public void shouldThrowWhenWebSocketConfigWithDuplicateClientRequestBodyText() t public void shouldThrowWhenWebSocketConfigWithDuplicateClientRequestBodyBytes() throws Exception { Exception exception = assertThrows(UncheckedIOException.class, () -> { - final URL yamlUrl = YamlParserTest.class.getResource("/yaml/web-socket-invalid-config-with-duplicate-client-request-body-bytes.yaml"); + final URL yamlUrl = YamlParserTest.class.getResource( + "/yaml/web-socket-invalid-config-with-duplicate-client-request-body-bytes.yaml"); final InputStream stubsConfigStream = yamlUrl.openStream(); final String parentDirectory = new File(yamlUrl.getPath()).getParent(); @@ -1455,14 +1535,16 @@ public void shouldThrowWhenWebSocketConfigWithDuplicateClientRequestBodyBytes() public void shouldThrowWhenWebSocketConfigWithoutOnOpenNorOnMessage() throws Exception { Exception exception = assertThrows(IOException.class, () -> { - final URL yamlUrl = YamlParserTest.class.getResource("/yaml/web-socket-valid-config-with-no-on-open-no-on-message.yaml"); + final URL yamlUrl = YamlParserTest.class.getResource( + "/yaml/web-socket-valid-config-with-no-on-open-no-on-message.yaml"); final InputStream stubsConfigStream = yamlUrl.openStream(); final String parentDirectory = new File(yamlUrl.getPath()).getParent(); new YamlParser().parse(parentDirectory, inputStreamToString(stubsConfigStream)); }); - String expectedMessage = "Web socket config must have at least one of the two 'on-open' or 'on-message' defined"; + String expectedMessage = + "Web socket config must have at least one of the two 'on-open' or 'on-message' defined"; String actualMessage = exception.getMessage(); assertThat(actualMessage).contains(expectedMessage); @@ -1472,4 +1554,4 @@ private YamlParseResultSet unmarshall(final String yaml) throws Exception { return new YamlParser().parse(".", yaml); } } -//web-socket-invalid-config-with-duplicate-client-request-body-text.yaml \ No newline at end of file +// web-socket-invalid-config-with-duplicate-client-request-body-text.yaml diff --git a/src/loadTest/java/io/github/azagniotov/stubby4j/HttpUtils.java b/src/loadTest/java/io/github/azagniotov/stubby4j/HttpUtils.java index 50d6902cf..fd826f9aa 100644 --- a/src/loadTest/java/io/github/azagniotov/stubby4j/HttpUtils.java +++ b/src/loadTest/java/io/github/azagniotov/stubby4j/HttpUtils.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; import com.google.api.client.http.ByteArrayContent; @@ -6,13 +22,12 @@ import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.apache.v2.ApacheHttpTransport; import io.github.azagniotov.stubby4j.utils.StringUtils; -import org.apache.http.client.HttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.SystemDefaultRoutePlanner; - import java.io.IOException; import java.net.ProxySelector; import java.util.concurrent.TimeUnit; +import org.apache.http.client.HttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.SystemDefaultRoutePlanner; /** * @author: Alexander Zagniotov @@ -28,7 +43,7 @@ public final class HttpUtils { */ final HttpClient apacheHttpClient = HttpClientBuilder.create() .useSystemProperties() - //.setSSLSocketFactory(SSLConnectionSocketFactory.getSocketFactory()) + // .setSSLSocketFactory(SSLConnectionSocketFactory.getSocketFactory()) .setSSLHostnameVerifier((hostname, session) -> true) .setMaxConnTotal(200) .setMaxConnPerRoute(20) @@ -45,21 +60,17 @@ public final class HttpUtils { }); } - private HttpUtils() { - - } + private HttpUtils() {} public static HttpRequest constructHttpRequest(final String method, final String targetUrl) throws IOException { - return WEB_CLIENT.buildRequest(method, - new GenericUrl(targetUrl), - null); + return WEB_CLIENT.buildRequest(method, new GenericUrl(targetUrl), null); } - public static HttpRequest constructHttpRequest(final String method, final String targetUrl, final String content) throws IOException { + public static HttpRequest constructHttpRequest(final String method, final String targetUrl, final String content) + throws IOException { - return WEB_CLIENT.buildRequest(method, - new GenericUrl(targetUrl), - new ByteArrayContent(null, StringUtils.getBytesUtf8(content))); + return WEB_CLIENT.buildRequest( + method, new GenericUrl(targetUrl), new ByteArrayContent(null, StringUtils.getBytesUtf8(content))); } } diff --git a/src/loadTest/java/io/github/azagniotov/stubby4j/PortTestUtils.java b/src/loadTest/java/io/github/azagniotov/stubby4j/PortTestUtils.java index 6521f6e1b..e6f8e6f00 100644 --- a/src/loadTest/java/io/github/azagniotov/stubby4j/PortTestUtils.java +++ b/src/loadTest/java/io/github/azagniotov/stubby4j/PortTestUtils.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; import static io.github.azagniotov.stubby4j.SpringSocketUtils.PORT_RANGE_MAX; @@ -5,9 +21,7 @@ final class PortTestUtils { - private PortTestUtils() { - - } + private PortTestUtils() {} static int findAvailableTcpPort() { return SpringSocketUtils.findAvailableTcpPort(PORT_RANGE_MIN, PORT_RANGE_MAX); diff --git a/src/loadTest/java/io/github/azagniotov/stubby4j/SpringSocketUtils.java b/src/loadTest/java/io/github/azagniotov/stubby4j/SpringSocketUtils.java index ce41c8cd7..d91d89d06 100644 --- a/src/loadTest/java/io/github/azagniotov/stubby4j/SpringSocketUtils.java +++ b/src/loadTest/java/io/github/azagniotov/stubby4j/SpringSocketUtils.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; /* @@ -16,11 +32,11 @@ * limitations under the License. */ -import javax.net.ServerSocketFactory; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.ServerSocket; import java.util.Random; +import javax.net.ServerSocketFactory; /** * Simple utility methods for working with network sockets — for example, @@ -50,10 +66,8 @@ public class SpringSocketUtils { */ static final int PORT_RANGE_MAX = 65535; - private static final Random random = new Random(System.nanoTime()); - /** * Although {@code SocketUtils} consists solely of static utility methods, * this constructor is intentionally {@code public}. @@ -70,8 +84,7 @@ public class SpringSocketUtils { * <bean id="bean1" ... p:port="#{socketUtils.findAvailableTcpPort(12000)}" /> * <bean id="bean2" ... p:port="#{socketUtils.findAvailableTcpPort(30000)}" /> */ - public SpringSocketUtils() { - } + public SpringSocketUtils() {} /** * Find an available TCP port randomly selected from the range @@ -87,13 +100,12 @@ static int findAvailableTcpPort(int minPort, int maxPort) { } private enum SocketType { - TCP { @Override protected boolean isPortAvailable(int port) { try { - ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket( - port, 1, InetAddress.getByName("localhost")); + ServerSocket serverSocket = ServerSocketFactory.getDefault() + .createServerSocket(port, 1, InetAddress.getByName("localhost")); serverSocket.close(); return true; } catch (Exception ex) { @@ -142,11 +154,9 @@ int findAvailablePort(int minPort, int maxPort) { } candidatePort = findRandomPort(minPort, maxPort); searchCounter++; - } - while (!isPortAvailable(candidatePort)); + } while (!isPortAvailable(candidatePort)); return candidatePort; } } - } diff --git a/src/loadTest/java/io/github/azagniotov/stubby4j/StubsPortalLoadTest.java b/src/loadTest/java/io/github/azagniotov/stubby4j/StubsPortalLoadTest.java index 6e13b0970..85c9ea5f8 100644 --- a/src/loadTest/java/io/github/azagniotov/stubby4j/StubsPortalLoadTest.java +++ b/src/loadTest/java/io/github/azagniotov/stubby4j/StubsPortalLoadTest.java @@ -1,5 +1,24 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.common.Common.HEADER_APPLICATION_JSON; + import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpMethods; import com.google.api.client.http.HttpRequest; @@ -12,11 +31,6 @@ import io.github.azagniotov.stubby4j.yaml.YamlBuilder; import io.github.azagniotov.stubby4j.yaml.YamlParseResultSet; import io.github.azagniotov.stubby4j.yaml.YamlParser; -import org.eclipse.jetty.http.HttpStatus; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -25,9 +39,10 @@ import java.io.UncheckedIOException; import java.net.URL; import java.util.concurrent.CompletableFuture; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.common.Common.HEADER_APPLICATION_JSON; +import org.eclipse.jetty.http.HttpStatus; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; public class StubsPortalLoadTest { @@ -48,13 +63,17 @@ public static void beforeClass() throws Exception { final InputStream stubsDataInputStream = url.openStream(); stubsDataInputStream.close(); - final String[] args = new String[]{ - "-m", - "-l", JettyFactory.DEFAULT_HOST, - "-s", String.valueOf(STUBS_PORT), - "-a", String.valueOf(ADMIN_PORT), - "-t", String.valueOf(STUBS_SSL_PORT), - //"--disable_stub_caching", + final String[] args = new String[] { + "-m", + "-l", + JettyFactory.DEFAULT_HOST, + "-s", + String.valueOf(STUBS_PORT), + "-a", + String.valueOf(ADMIN_PORT), + "-t", + String.valueOf(STUBS_SSL_PORT), + // "--disable_stub_caching", }; final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); @@ -69,7 +88,8 @@ public static void beforeClass() throws Exception { } }); - stubbyManager = new StubbyManagerFactory().construct(configFile, commandLineInterpreter.getCommandlineParams(), stubLoadComputation); + stubbyManager = new StubbyManagerFactory() + .construct(configFile, commandLineInterpreter.getCommandlineParams(), stubLoadComputation); stubbyManager.startJetty(); } @@ -97,11 +117,10 @@ public void dataGenerator() throws Exception { .build(); builder.append(yamlToUpdate).append("\n\n\n"); - } try (final FileWriter fileWriter = new FileWriter(new File("./load_test_data.yaml")); - final BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) { + final BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) { bufferedWriter.write(builder.toString()); bufferedWriter.flush(); } @@ -138,7 +157,6 @@ public void cacheTesting_CheckResponseTimeOnRepeatedRequests() throws Exception System.out.println(String.format("It took %s milliseconds to make a 1st request", firstElapsed)); System.out.println("**************************************************************\n"); - //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Making repeated requess //////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -151,7 +169,8 @@ public void cacheTesting_CheckResponseTimeOnRepeatedRequests() throws Exception final HttpResponse responseTwo = requestTwo.execute(); final long secondElapsed = System.currentTimeMillis() - secondStart; - final String responseTwoContentAsString = responseTwo.parseAsString().trim(); + final String responseTwoContentAsString = + responseTwo.parseAsString().trim(); assertThat(responseTwo.getStatusCode()).isEqualTo(HttpStatus.CREATED_201); assertThat("{\"status\":\"CREATED RESOURCE#" + idx + "!\"}").isEqualTo(responseTwoContentAsString); diff --git a/src/main/java/io/github/azagniotov/stubby4j/Main.java b/src/main/java/io/github/azagniotov/stubby4j/Main.java index 6760ac33f..613ea07e4 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/Main.java +++ b/src/main/java/io/github/azagniotov/stubby4j/Main.java @@ -1,5 +1,23 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j; +import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; + import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.cli.CommandLineInterpreter; @@ -9,10 +27,6 @@ import io.github.azagniotov.stubby4j.utils.DateTimeUtils; import io.github.azagniotov.stubby4j.yaml.YamlParseResultSet; import io.github.azagniotov.stubby4j.yaml.YamlParser; -import org.apache.commons.cli.ParseException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -24,8 +38,9 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; - -import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; +import org.apache.commons.cli.ParseException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @GeneratedCodeClassCoverageExclusion public final class Main { @@ -37,9 +52,7 @@ public final class Main { private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(5); private static CommandLineInterpreter commandLineInterpreter; - private Main() { - - } + private Main() {} public static void main(String[] args) { // See SslUtils static { ... } @@ -60,8 +73,7 @@ private static void parseCommandLineArgs(final String[] args) { commandLineInterpreter.parseCommandLine(args); } catch (final ParseException ex) { final String msg = - String.format("Could not parse provided command line arguments, error: %s", - ex.toString()); + String.format("Could not parse provided command line arguments, error: %s", ex.toString()); throw new IllegalArgumentException(msg); } @@ -98,19 +110,26 @@ private static void startStubby4jUsingCommandLineArgs() { ConsoleUtils.enableDebug(commandLineInterpreter.isDebug()); final File configFile = buildYamlConfigFile(configFilename); - final CompletableFuture stubLoadComputation = CompletableFuture.supplyAsync(() -> { - try { - return new YamlParser().parse(configFile.getParent(), configFile); - } catch (IOException ioEx) { - throw new UncheckedIOException(ioEx); - } - }, EXECUTOR_SERVICE); - - final StubbyManager stubbyManager = new StubbyManagerFactory().construct(configFile, commandLineArgs, stubLoadComputation); + final CompletableFuture stubLoadComputation = CompletableFuture.supplyAsync( + () -> { + try { + return new YamlParser().parse(configFile.getParent(), configFile); + } catch (IOException ioEx) { + throw new UncheckedIOException(ioEx); + } + }, + EXECUTOR_SERVICE); + + final StubbyManager stubbyManager = + new StubbyManagerFactory().construct(configFile, commandLineArgs, stubLoadComputation); stubbyManager.startJetty(); final long totalEnd = System.currentTimeMillis(); - ANSITerminal.status(String.format(BR + "stubby4j successfully started after %s milliseconds at %s", (totalEnd - initialStart), DateTimeUtils.systemDefault()) + BR); + ANSITerminal.status(String.format( + BR + "stubby4j successfully started after %s milliseconds at %s", + (totalEnd - initialStart), + DateTimeUtils.systemDefault()) + + BR); LOGGER.debug("stubby4j successfully started after {} milliseconds.", totalEnd - initialStart); ANSITerminal.status(stubbyManager.statuses().toString()); @@ -120,8 +139,7 @@ private static void startStubby4jUsingCommandLineArgs() { LOGGER.info("Quit: ctrl-c"); } catch (final Exception ex) { - final String msg = - String.format("Could not init stubby4j, error: %s", ex.toString()); + final String msg = String.format("Could not init stubby4j, error: %s", ex.toString()); throw new IllegalStateException(msg, ex); } @@ -130,16 +148,17 @@ private static void startStubby4jUsingCommandLineArgs() { private static File buildYamlConfigFile(final String configFilename) throws IOException { if (!commandLineInterpreter.isYamlProvided()) { - final String msg = - String.format("[WARNING] YAML data was not provided using command line option '--%s'." + - " Is this intentional??? %s" - + "To see all command line options run again with option '--%s'", - CommandLineInterpreter.OPTION_CONFIG, BR, CommandLineInterpreter.OPTION_HELP); + final String msg = String.format( + "[WARNING] YAML data was not provided using command line option '--%s'." + + " Is this intentional??? %s" + + "To see all command line options run again with option '--%s'", + CommandLineInterpreter.OPTION_CONFIG, BR, CommandLineInterpreter.OPTION_HELP); ANSITerminal.warn(BR + msg + BR); LOGGER.debug("No YAML config provided upon startup. Is this intentional???"); - final File tempTargetFile = Files.createFile(Paths.get("./empty.yaml")).toFile(); + final File tempTargetFile = + Files.createFile(Paths.get("./empty.yaml")).toFile(); try (final InputStream inputStream = Main.class.getResourceAsStream(DEFAULT_CONFIG_FILE)) { Files.copy(inputStream, tempTargetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } diff --git a/src/main/java/io/github/azagniotov/stubby4j/annotations/GeneratedCodeClassCoverageExclusion.java b/src/main/java/io/github/azagniotov/stubby4j/annotations/GeneratedCodeClassCoverageExclusion.java index 984bb77b8..fe5c3972b 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/annotations/GeneratedCodeClassCoverageExclusion.java +++ b/src/main/java/io/github/azagniotov/stubby4j/annotations/GeneratedCodeClassCoverageExclusion.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.annotations; import java.lang.annotation.Documented; @@ -18,6 +34,4 @@ @Documented @Retention(RetentionPolicy.CLASS) @Target({ElementType.TYPE}) -public @interface GeneratedCodeClassCoverageExclusion { - -} +public @interface GeneratedCodeClassCoverageExclusion {} diff --git a/src/main/java/io/github/azagniotov/stubby4j/annotations/GeneratedCodeMethodCoverageExclusion.java b/src/main/java/io/github/azagniotov/stubby4j/annotations/GeneratedCodeMethodCoverageExclusion.java index 559f312c8..3f88faf82 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/annotations/GeneratedCodeMethodCoverageExclusion.java +++ b/src/main/java/io/github/azagniotov/stubby4j/annotations/GeneratedCodeMethodCoverageExclusion.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.annotations; import java.lang.annotation.Documented; @@ -18,6 +34,4 @@ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.CONSTRUCTOR, ElementType.METHOD}) -public @interface GeneratedCodeMethodCoverageExclusion { - -} +public @interface GeneratedCodeMethodCoverageExclusion {} diff --git a/src/main/java/io/github/azagniotov/stubby4j/annotations/PotentiallyFlaky.java b/src/main/java/io/github/azagniotov/stubby4j/annotations/PotentiallyFlaky.java index a3a5fc9b7..d95efa0f1 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/annotations/PotentiallyFlaky.java +++ b/src/main/java/io/github/azagniotov/stubby4j/annotations/PotentiallyFlaky.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.annotations; import java.lang.annotation.ElementType; @@ -5,7 +21,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) public @interface PotentiallyFlaky { diff --git a/src/main/java/io/github/azagniotov/stubby4j/annotations/VisibleForTesting.java b/src/main/java/io/github/azagniotov/stubby4j/annotations/VisibleForTesting.java index 7f1d604ea..6b1e5d77f 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/annotations/VisibleForTesting.java +++ b/src/main/java/io/github/azagniotov/stubby4j/annotations/VisibleForTesting.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.annotations; import java.lang.annotation.ElementType; @@ -11,5 +27,4 @@ */ @Retention(RetentionPolicy.CLASS) @Target({ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.FIELD}) -public @interface VisibleForTesting { -} +public @interface VisibleForTesting {} diff --git a/src/main/java/io/github/azagniotov/stubby4j/caching/Cache.java b/src/main/java/io/github/azagniotov/stubby4j/caching/Cache.java index 0d6dadea7..1b4a18272 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/caching/Cache.java +++ b/src/main/java/io/github/azagniotov/stubby4j/caching/Cache.java @@ -1,16 +1,30 @@ -package io.github.azagniotov.stubby4j.caching; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.azagniotov.stubby4j.caching; import io.github.azagniotov.stubby4j.stubs.StubHttpLifecycle; -import org.ehcache.UserManagedCache; - import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; +import org.ehcache.UserManagedCache; public interface Cache { - long CACHE_ENTRY_LIFETIME_SECONDS = 3600L; // 3600 secs => 60 minutes + long CACHE_ENTRY_LIFETIME_SECONDS = 3600L; // 3600 secs => 60 minutes static Cache stubHttpLifecycleCache(final boolean buildNoOpCache) { if (buildNoOpCache) { diff --git a/src/main/java/io/github/azagniotov/stubby4j/caching/NoOpStubHttpLifecycleCache.java b/src/main/java/io/github/azagniotov/stubby4j/caching/NoOpStubHttpLifecycleCache.java index d6bf2b70c..b8f64d17c 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/caching/NoOpStubHttpLifecycleCache.java +++ b/src/main/java/io/github/azagniotov/stubby4j/caching/NoOpStubHttpLifecycleCache.java @@ -1,19 +1,31 @@ -package io.github.azagniotov.stubby4j.caching; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.azagniotov.stubby4j.caching; import io.github.azagniotov.stubby4j.stubs.StubHttpLifecycle; -import org.ehcache.UserManagedCache; - import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; +import org.ehcache.UserManagedCache; class NoOpStubHttpLifecycleCache implements Cache { private static final AtomicInteger ATOMIC_INTEGER_ZERO = new AtomicInteger(); - NoOpStubHttpLifecycleCache() { - - } + NoOpStubHttpLifecycleCache() {} @Override public Optional get(final String key) { diff --git a/src/main/java/io/github/azagniotov/stubby4j/caching/RegexPatternCache.java b/src/main/java/io/github/azagniotov/stubby4j/caching/RegexPatternCache.java index f9d6dfe84..f42576bdc 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/caching/RegexPatternCache.java +++ b/src/main/java/io/github/azagniotov/stubby4j/caching/RegexPatternCache.java @@ -1,15 +1,29 @@ -package io.github.azagniotov.stubby4j.caching; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.azagniotov.stubby4j.caching; +import java.time.Duration; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.regex.Pattern; import org.ehcache.UserManagedCache; import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.builders.UserManagedCacheBuilder; -import java.time.Duration; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.regex.Pattern; - class RegexPatternCache implements Cache { private final AtomicInteger cacheSize; @@ -18,8 +32,7 @@ class RegexPatternCache implements Cache { RegexPatternCache(final long cacheEntryLifetimeSeconds) { final Duration timeToLiveExpiration = Duration.ofSeconds(cacheEntryLifetimeSeconds); - this.localCache = UserManagedCacheBuilder - .newUserManagedCacheBuilder(Integer.class, Pattern.class) + this.localCache = UserManagedCacheBuilder.newUserManagedCacheBuilder(Integer.class, Pattern.class) .withResourcePools(ResourcePoolsBuilder.heap(500L)) .identifier(this.getClass().getSimpleName()) .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(timeToLiveExpiration)) diff --git a/src/main/java/io/github/azagniotov/stubby4j/caching/StubHttpLifecycleCache.java b/src/main/java/io/github/azagniotov/stubby4j/caching/StubHttpLifecycleCache.java index a2b03b195..9a1319c2b 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/caching/StubHttpLifecycleCache.java +++ b/src/main/java/io/github/azagniotov/stubby4j/caching/StubHttpLifecycleCache.java @@ -1,15 +1,29 @@ -package io.github.azagniotov.stubby4j.caching; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.azagniotov.stubby4j.caching; import io.github.azagniotov.stubby4j.stubs.StubHttpLifecycle; +import java.time.Duration; +import java.util.concurrent.atomic.AtomicInteger; import org.ehcache.UserManagedCache; import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.builders.UserManagedCacheBuilder; -import java.time.Duration; -import java.util.concurrent.atomic.AtomicInteger; - class StubHttpLifecycleCache implements Cache { private final AtomicInteger cacheSize; @@ -18,8 +32,7 @@ class StubHttpLifecycleCache implements Cache { StubHttpLifecycleCache(final long cacheEntryLifetimeSeconds) { final Duration timeToLiveExpiration = Duration.ofSeconds(cacheEntryLifetimeSeconds); - this.localCache = UserManagedCacheBuilder - .newUserManagedCacheBuilder(String.class, StubHttpLifecycle.class) + this.localCache = UserManagedCacheBuilder.newUserManagedCacheBuilder(String.class, StubHttpLifecycle.class) .withResourcePools(ResourcePoolsBuilder.heap(500L)) .identifier(this.getClass().getSimpleName()) .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(timeToLiveExpiration)) diff --git a/src/main/java/io/github/azagniotov/stubby4j/cli/ANSITerminal.java b/src/main/java/io/github/azagniotov/stubby4j/cli/ANSITerminal.java index 550ffe778..021656790 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/cli/ANSITerminal.java +++ b/src/main/java/io/github/azagniotov/stubby4j/cli/ANSITerminal.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.cli; /** @@ -24,9 +40,7 @@ public final class ANSITerminal { private static final String YELLOW = String.format("%s[33m", ESCAPE); private static boolean mute = false; - private ANSITerminal() { - - } + private ANSITerminal() {} private static void print(final String color, final String msg) { if (mute) { diff --git a/src/main/java/io/github/azagniotov/stubby4j/cli/CommandLineInterpreter.java b/src/main/java/io/github/azagniotov/stubby4j/cli/CommandLineInterpreter.java index 4cdaf468e..f7ed6c8e3 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/cli/CommandLineInterpreter.java +++ b/src/main/java/io/github/azagniotov/stubby4j/cli/CommandLineInterpreter.java @@ -1,7 +1,32 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.cli; +import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; +import static io.github.azagniotov.stubby4j.utils.JarUtils.readManifestImplementationVersion; + import io.github.azagniotov.stubby4j.annotations.GeneratedCodeMethodCoverageExclusion; import io.github.azagniotov.stubby4j.utils.ObjectUtils; +import java.io.PrintWriter; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; @@ -10,16 +35,6 @@ import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; -import java.io.PrintWriter; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; -import static io.github.azagniotov.stubby4j.utils.JarUtils.readManifestImplementationVersion; - public final class CommandLineInterpreter { public static final List PROVIDED_OPTIONS = Collections.synchronizedList(new LinkedList<>()); @@ -47,25 +62,46 @@ public final class CommandLineInterpreter { OPTIONS.addOption("s", OPTION_CLIENTPORT, true, "Port for stub portal. Defaults to 8882."); OPTIONS.addOption("a", OPTION_ADMINPORT, true, "Port for admin portal. Defaults to 8889."); OPTIONS.addOption("t", OPTION_TLSPORT, true, "Port for TLS connection. Defaults to 7443."); - OPTIONS.addOption("d", OPTION_CONFIG, true, "Data file to pre-load endpoints. Data file to pre-load endpoints. Optional valid YAML 1.1 is expected. If YAML is not provided, you will be expected to configure stubs via the stubby4j HTTP POST API."); - OPTIONS.addOption("k", OPTION_KEYSTORE, true, "Keystore file for custom TLS. By default TLS is enabled using internal self-signed certificate."); + OPTIONS.addOption( + "d", + OPTION_CONFIG, + true, + "Data file to pre-load endpoints. Data file to pre-load endpoints. Optional valid YAML 1.1 is expected. If YAML is not provided, you will be expected to configure stubs via the stubby4j HTTP POST API."); + OPTIONS.addOption( + "k", + OPTION_KEYSTORE, + true, + "Keystore file for custom TLS. By default TLS is enabled using internal self-signed certificate."); OPTIONS.addOption("p", OPTION_KEYPASS, true, "Password for the provided keystore file."); OPTIONS.addOption("h", OPTION_HELP, false, "This help text."); OPTIONS.addOption("m", OPTION_MUTE, false, "Mute console output."); OPTIONS.addOption("v", OPTION_VERSION, false, "Prints out to console stubby version."); - OPTIONS.addOption("o", OPTION_DEBUG, false, "Dumps raw HTTP request to the console (if console is not muted!)."); + OPTIONS.addOption( + "o", OPTION_DEBUG, false, "Dumps raw HTTP request to the console (if console is not muted!)."); OPTIONS.addOption("da", OPTION_DISABLE_ADMIN, false, "Does not start Admin portal"); - OPTIONS.addOption("dc", OPTION_DISABLE_STUB_CACHING, false, "Since v7.2.0. Disables stubs in-memory caching when stubs are successfully matched to the incoming HTTP requests"); - OPTIONS.addOption("ta", OPTION_ENABLE_TLS_WITH_ALPN_AND_HTTP_2, false, "Since v7.4.0. Enables HTTP/2 over TCP (h2c) and HTTP/2 over TLS (h2) on TLS v1.2 or newer using ALPN extension"); - OPTIONS.addOption("ds", OPTION_DISABLE_SSL, false, "Disables TLS support (enabled by default) and disables the '--enable_tls_with_alpn_and_http_2' flag, if the latter was provided"); + OPTIONS.addOption( + "dc", + OPTION_DISABLE_STUB_CACHING, + false, + "Since v7.2.0. Disables stubs in-memory caching when stubs are successfully matched to the incoming HTTP requests"); + OPTIONS.addOption( + "ta", + OPTION_ENABLE_TLS_WITH_ALPN_AND_HTTP_2, + false, + "Since v7.4.0. Enables HTTP/2 over TCP (h2c) and HTTP/2 over TLS (h2) on TLS v1.2 or newer using ALPN extension"); + OPTIONS.addOption( + "ds", + OPTION_DISABLE_SSL, + false, + "Disables TLS support (enabled by default) and disables the '--enable_tls_with_alpn_and_http_2' flag, if the latter was provided"); @SuppressWarnings("static-access") - Option watch = - Option.builder("w") - .desc("Since v2.0.11. Periodically scans for changes in last modification date of the main YAML and referenced external files (if any). The flag can accept an optional arg value which is the watch scan time in milliseconds. If milliseconds is not provided, the watch scans every 100ms. If last modification date changed since the last scan period, the stub configuration is reloaded") - .longOpt(OPTION_WATCH) - .hasArg(true) - .optionalArg(true) - .build(); + Option watch = Option.builder("w") + .desc( + "Since v2.0.11. Periodically scans for changes in last modification date of the main YAML and referenced external files (if any). The flag can accept an optional arg value which is the watch scan time in milliseconds. If milliseconds is not provided, the watch scans every 100ms. If last modification date changed since the last scan period, the stub configuration is reloaded") + .longOpt(OPTION_WATCH) + .hasArg(true) + .optionalArg(true) + .build(); OPTIONS.addOption(watch); } @@ -141,7 +177,6 @@ public void printVersion() { } } - /** * Identifies what command line arguments that have been passed by user are matching available options * @@ -151,20 +186,23 @@ public Map getCommandlineParams() { final Option[] options = line.getOptions(); - final Map providedOptions = new HashMap() {{ - for (final Option option : options) { - put(option.getLongOpt(), option.getValue()); - final String argValue = ObjectUtils.isNull(option.getValue()) ? "" : "=" + option.getValue(); - PROVIDED_OPTIONS.add("--" + option.getLongOpt() + argValue); + final Map providedOptions = new HashMap() { + { + for (final Option option : options) { + put(option.getLongOpt(), option.getValue()); + final String argValue = ObjectUtils.isNull(option.getValue()) ? "" : "=" + option.getValue(); + PROVIDED_OPTIONS.add("--" + option.getLongOpt() + argValue); + } } - }}; + }; if (providedOptions.containsKey(OPTION_DISABLE_SSL)) { providedOptions.remove(OPTION_ENABLE_TLS_WITH_ALPN_AND_HTTP_2); } if (PROVIDED_OPTIONS.contains("--" + OPTION_DISABLE_SSL)) { - PROVIDED_OPTIONS.removeIf(element -> element.equalsIgnoreCase("--" + OPTION_ENABLE_TLS_WITH_ALPN_AND_HTTP_2)); + PROVIDED_OPTIONS.removeIf( + element -> element.equalsIgnoreCase("--" + OPTION_ENABLE_TLS_WITH_ALPN_AND_HTTP_2)); } return new HashMap<>(providedOptions); diff --git a/src/main/java/io/github/azagniotov/stubby4j/cli/EmptyLogger.java b/src/main/java/io/github/azagniotov/stubby4j/cli/EmptyLogger.java index b73f94024..21efc1e94 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/cli/EmptyLogger.java +++ b/src/main/java/io/github/azagniotov/stubby4j/cli/EmptyLogger.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.cli; import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; @@ -16,28 +32,22 @@ public String getName() { } @Override - public void warn(final String s, final Object... objects) { - } + public void warn(final String s, final Object... objects) {} @Override - public void warn(final Throwable throwable) { - } + public void warn(final Throwable throwable) {} @Override - public void warn(final String s, final Throwable throwable) { - } + public void warn(final String s, final Throwable throwable) {} @Override - public void info(final String s, final Object... objects) { - } + public void info(final String s, final Object... objects) {} @Override - public void info(final Throwable throwable) { - } + public void info(final Throwable throwable) {} @Override - public void info(final String s, final Throwable throwable) { - } + public void info(final String s, final Throwable throwable) {} @Override public boolean isDebugEnabled() { @@ -45,25 +55,19 @@ public boolean isDebugEnabled() { } @Override - public void setDebugEnabled(final boolean b) { - } + public void setDebugEnabled(final boolean b) {} @Override - public void debug(final String s, final Object... objects) { - } + public void debug(final String s, final Object... objects) {} @Override - public void debug(final String msg, final long value) { - - } + public void debug(final String msg, final long value) {} @Override - public void debug(final Throwable throwable) { - } + public void debug(final Throwable throwable) {} @Override - public void debug(final String s, final Throwable throwable) { - } + public void debug(final String s, final Throwable throwable) {} @Override public Logger getLogger(final String s) { @@ -71,6 +75,5 @@ public Logger getLogger(final String s) { } @Override - public void ignore(final Throwable throwable) { - } + public void ignore(final Throwable throwable) {} } diff --git a/src/main/java/io/github/azagniotov/stubby4j/client/Authorization.java b/src/main/java/io/github/azagniotov/stubby4j/client/Authorization.java index be33de479..62203c062 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/client/Authorization.java +++ b/src/main/java/io/github/azagniotov/stubby4j/client/Authorization.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.client; import io.github.azagniotov.stubby4j.annotations.GeneratedCodeMethodCoverageExclusion; @@ -12,7 +28,6 @@ public Authorization(final AuthorizationType authorizationType, final String val this.value = value; } - public String asFullValue() { if (authorizationType == AuthorizationType.CUSTOM) { return value; diff --git a/src/main/java/io/github/azagniotov/stubby4j/client/StubbyClient.java b/src/main/java/io/github/azagniotov/stubby4j/client/StubbyClient.java index ed89d3c12..c8e6e8b6b 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/client/StubbyClient.java +++ b/src/main/java/io/github/azagniotov/stubby4j/client/StubbyClient.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.client; import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; @@ -12,10 +28,6 @@ import io.github.azagniotov.stubby4j.utils.StringUtils; import io.github.azagniotov.stubby4j.yaml.YamlParseResultSet; import io.github.azagniotov.stubby4j.yaml.YamlParser; -import org.eclipse.jetty.http.HttpMethod; -import org.eclipse.jetty.http.HttpScheme; -import org.eclipse.jetty.http.HttpStatus; - import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; @@ -30,6 +42,9 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import org.eclipse.jetty.http.HttpMethod; +import org.eclipse.jetty.http.HttpScheme; +import org.eclipse.jetty.http.HttpStatus; @GeneratedCodeClassCoverageExclusion public final class StubbyClient { @@ -38,9 +53,7 @@ public final class StubbyClient { private StubbyManager stubbyManager; - public StubbyClient() { - - } + public StubbyClient() {} /** * Starts stubby using default ports of Stubs (8882), Admin (8889) and TlsStubs portals (7443) on localhost. @@ -48,9 +61,13 @@ public StubbyClient() { * @param yamlConfigurationFilename an absolute or relative file path for YAML stubs configuration file * @throws Exception */ - public void startJetty(final String yamlConfigurationFilename) throws Exception { - startJetty(JettyFactory.DEFAULT_STUBS_PORT, JettyFactory.DEFAULT_SSL_PORT, JettyFactory.DEFAULT_ADMIN_PORT, JettyFactory.DEFAULT_HOST, yamlConfigurationFilename); + startJetty( + JettyFactory.DEFAULT_STUBS_PORT, + JettyFactory.DEFAULT_SSL_PORT, + JettyFactory.DEFAULT_ADMIN_PORT, + JettyFactory.DEFAULT_HOST, + yamlConfigurationFilename); } /** @@ -60,9 +77,13 @@ public void startJetty(final String yamlConfigurationFilename) throws Exception * @param yamlConfigurationFilename an absolute or relative file path for YAML stubs configuration file * @throws Exception */ - public void startJetty(final int stubsPort, final String yamlConfigurationFilename) throws Exception { - startJetty(stubsPort, JettyFactory.DEFAULT_SSL_PORT, JettyFactory.DEFAULT_ADMIN_PORT, JettyFactory.DEFAULT_HOST, yamlConfigurationFilename); + startJetty( + stubsPort, + JettyFactory.DEFAULT_SSL_PORT, + JettyFactory.DEFAULT_ADMIN_PORT, + JettyFactory.DEFAULT_HOST, + yamlConfigurationFilename); } /** @@ -73,9 +94,14 @@ public void startJetty(final int stubsPort, final String yamlConfigurationFilena * @param yamlConfigurationFilename an absolute or relative file path for YAML stubs configuration file * @throws Exception */ - - public void startJetty(final int stubsPort, final int adminPort, final String yamlConfigurationFilename) throws Exception { - startJetty(stubsPort, JettyFactory.DEFAULT_SSL_PORT, adminPort, JettyFactory.DEFAULT_HOST, yamlConfigurationFilename); + public void startJetty(final int stubsPort, final int adminPort, final String yamlConfigurationFilename) + throws Exception { + startJetty( + stubsPort, + JettyFactory.DEFAULT_SSL_PORT, + adminPort, + JettyFactory.DEFAULT_HOST, + yamlConfigurationFilename); } /** @@ -87,8 +113,9 @@ public void startJetty(final int stubsPort, final int adminPort, final String ya * @param yamlConfigurationFilename an absolute or relative file path for YAML stubs configuration file * @throws Exception */ - - public void startJetty(final int stubsPort, final int tlsPort, final int adminPort, final String yamlConfigurationFilename) throws Exception { + public void startJetty( + final int stubsPort, final int tlsPort, final int adminPort, final String yamlConfigurationFilename) + throws Exception { startJetty(stubsPort, tlsPort, adminPort, JettyFactory.DEFAULT_HOST, yamlConfigurationFilename); } @@ -101,8 +128,12 @@ public void startJetty(final int stubsPort, final int tlsPort, final int adminPo * @param yamlConfigurationFilename an absolute or relative file path for YAML stubs configuration file * @throws Exception */ - - public void startJetty(final int stubsPort, final int adminPort, final String addressToBind, final String yamlConfigurationFilename) throws Exception { + public void startJetty( + final int stubsPort, + final int adminPort, + final String addressToBind, + final String yamlConfigurationFilename) + throws Exception { startJetty(stubsPort, JettyFactory.DEFAULT_SSL_PORT, adminPort, addressToBind, yamlConfigurationFilename); } @@ -117,8 +148,25 @@ public void startJetty(final int stubsPort, final int adminPort, final String ad * @param flags Optional additional stubby4j command line arguments. * @throws Exception */ - public void startJetty(final int stubsPort, final int tlsPort, final int adminPort, final String addressToBind, final String yamlConfigurationFilename, final String... flags) throws Exception { - final String[] defaultFlags = new String[]{"-m", "-l", addressToBind, "-s", String.valueOf(stubsPort), "-a", String.valueOf(adminPort), "-t", String.valueOf(tlsPort)}; + public void startJetty( + final int stubsPort, + final int tlsPort, + final int adminPort, + final String addressToBind, + final String yamlConfigurationFilename, + final String... flags) + throws Exception { + final String[] defaultFlags = new String[] { + "-m", + "-l", + addressToBind, + "-s", + String.valueOf(stubsPort), + "-a", + String.valueOf(adminPort), + "-t", + String.valueOf(tlsPort) + }; final String[] args = CollectionUtils.concatWithArrayCopy(defaultFlags, flags); final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); @@ -127,7 +175,8 @@ public void startJetty(final int stubsPort, final int tlsPort, final int adminPo final File configFile = new File(yamlConfigurationFilename); final CompletableFuture stubLoadComputation = parseYamlAsync(configFile); - stubbyManager = new StubbyManagerFactory().construct(configFile, commandLineInterpreter.getCommandlineParams(), stubLoadComputation); + stubbyManager = new StubbyManagerFactory() + .construct(configFile, commandLineInterpreter.getCommandlineParams(), stubLoadComputation); stubbyManager.startJetty(); } @@ -153,27 +202,37 @@ public void startJetty(final int stubsPort, final int tlsPort, final int adminPo * @throws Exception * @see io.github.azagniotov.stubby4j.utils.NetworkPortUtils */ - public void startJettyYamless(final String stubsYamlConfigurationData, - final int stubsPort, - final int tlsPort, - final int adminPort, - final String addressToBind, - final String... additionalFlags) throws Exception { - final String[] defaultFlags = new String[]{"-l", addressToBind, "-s", String.valueOf(stubsPort), "-a", String.valueOf(adminPort), "-t", String.valueOf(tlsPort)}; + public void startJettyYamless( + final String stubsYamlConfigurationData, + final int stubsPort, + final int tlsPort, + final int adminPort, + final String addressToBind, + final String... additionalFlags) + throws Exception { + final String[] defaultFlags = new String[] { + "-l", + addressToBind, + "-s", + String.valueOf(stubsPort), + "-a", + String.valueOf(adminPort), + "-t", + String.valueOf(tlsPort) + }; final String[] args = CollectionUtils.concatWithArrayCopy(defaultFlags, additionalFlags); final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); commandLineInterpreter.parseCommandLine(args); - final String emptyYaml = - "- request:\n" + - " method: [GET]\n" + - " url: /stubby4j/default/placeholder/stub\n" + - "\n" + - " response:\n" + - " status: 302"; + final String emptyYaml = "- request:\n" + " method: [GET]\n" + + " url: /stubby4j/default/placeholder/stub\n" + + "\n" + + " response:\n" + + " status: 302"; - final File tempTargetFile = Files.createTempFile("stubby4jTempYamlConfig_", ".yaml").toFile(); + final File tempTargetFile = + Files.createTempFile("stubby4jTempYamlConfig_", ".yaml").toFile(); try (final InputStream inputStream = new ByteArrayInputStream(StringUtils.getBytesUtf8(emptyYaml))) { Files.copy(inputStream, tempTargetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } @@ -181,7 +240,8 @@ public void startJettyYamless(final String stubsYamlConfigurationData, final CompletableFuture stubLoadComputation = parseYamlAsync(tempTargetFile); - stubbyManager = new StubbyManagerFactory().construct(tempTargetFile, commandLineInterpreter.getCommandlineParams(), stubLoadComputation); + stubbyManager = new StubbyManagerFactory() + .construct(tempTargetFile, commandLineInterpreter.getCommandlineParams(), stubLoadComputation); stubbyManager.startJetty(); final String adminUrl = String.format("http://%s:%s", addressToBind, adminPort); @@ -195,7 +255,6 @@ public void startJettyYamless(final String stubsYamlConfigurationData, * * @throws Exception */ - public void stopJetty() throws Exception { if (ObjectUtils.isNotNull(stubbyManager)) { stubbyManager.stopJetty(); @@ -207,7 +266,6 @@ public void stopJetty() throws Exception { * * @throws Exception */ - public void joinJetty() throws Exception { if (ObjectUtils.isNotNull(stubbyManager)) { stubbyManager.joinJetty(); @@ -223,7 +281,6 @@ public void joinJetty() throws Exception { * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - public StubbyResponse doGet(final String host, final String uri, final int stubsPort) throws Exception { return doGet(host, uri, stubsPort, null); } @@ -236,7 +293,6 @@ public StubbyResponse doGet(final String host, final String uri, final int stubs * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - public StubbyResponse doGetOverSsl(final String host, final String uri) throws Exception { return doGetOverSsl(host, uri, JettyFactory.DEFAULT_SSL_PORT, null); } @@ -250,7 +306,6 @@ public StubbyResponse doGetOverSsl(final String host, final String uri) throws E * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - public StubbyResponse doGetOverSsl(final String host, final String uri, final int port) throws Exception { return doGetOverSsl(host, uri, port, null); } @@ -267,9 +322,15 @@ public StubbyResponse doGetOverSsl(final String host, final String uri, final in * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - - public StubbyResponse doGetOverSsl(final String host, final String uri, final int port, final Authorization authorization) throws Exception { - final StubbyRequest stubbyRequest = new StubbyRequest(HttpScheme.HTTPS.asString().toLowerCase(Locale.US), HttpMethod.GET.asString(), uri, host, port, authorization); + public StubbyResponse doGetOverSsl( + final String host, final String uri, final int port, final Authorization authorization) throws Exception { + final StubbyRequest stubbyRequest = new StubbyRequest( + HttpScheme.HTTPS.asString().toLowerCase(Locale.US), + HttpMethod.GET.asString(), + uri, + host, + port, + authorization); return makeRequest(stubbyRequest); } @@ -286,14 +347,20 @@ public StubbyResponse doGetOverSsl(final String host, final String uri, final in * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - - public StubbyResponse doGet(final String host, final String uri, final int stubsPort, final Authorization authorization) throws Exception { - final StubbyRequest stubbyRequest = new StubbyRequest(HttpScheme.HTTP.asString().toLowerCase(Locale.US), HttpMethod.GET.asString(), uri, host, stubsPort, authorization); + public StubbyResponse doGet( + final String host, final String uri, final int stubsPort, final Authorization authorization) + throws Exception { + final StubbyRequest stubbyRequest = new StubbyRequest( + HttpScheme.HTTP.asString().toLowerCase(Locale.US), + HttpMethod.GET.asString(), + uri, + host, + stubsPort, + authorization); return makeRequest(stubbyRequest); } - /** * Makes GET HTTP request to stubby running on default host and port - localhost:8882 * @@ -301,7 +368,6 @@ public StubbyResponse doGet(final String host, final String uri, final int stubs * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - public StubbyResponse doGetUsingDefaults(final String uri) throws Exception { return doGetUsingDefaults(uri, null); } @@ -316,7 +382,6 @@ public StubbyResponse doGetUsingDefaults(final String uri) throws Exception { * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - public StubbyResponse doGetUsingDefaults(final String uri, final Authorization authorization) throws Exception { return doGet(JettyFactory.DEFAULT_HOST, uri, JettyFactory.DEFAULT_STUBS_PORT, authorization); } @@ -331,8 +396,8 @@ public StubbyResponse doGetUsingDefaults(final String uri, final Authorization a * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - - public StubbyResponse doPost(final String host, final String uri, final int stubsPort, final String payload) throws Exception { + public StubbyResponse doPost(final String host, final String uri, final int stubsPort, final String payload) + throws Exception { return doPost(host, uri, stubsPort, null, payload); } @@ -349,9 +414,21 @@ public StubbyResponse doPost(final String host, final String uri, final int stub * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - - public StubbyResponse doPost(final String host, final String uri, final int stubsPort, final Authorization authorization, final String payload) throws Exception { - final StubbyRequest stubbyRequest = new StubbyRequest(HttpScheme.HTTP.asString().toLowerCase(Locale.US), HttpMethod.POST.asString(), uri, host, stubsPort, authorization, payload); + public StubbyResponse doPost( + final String host, + final String uri, + final int stubsPort, + final Authorization authorization, + final String payload) + throws Exception { + final StubbyRequest stubbyRequest = new StubbyRequest( + HttpScheme.HTTP.asString().toLowerCase(Locale.US), + HttpMethod.POST.asString(), + uri, + host, + stubsPort, + authorization, + payload); return makeRequest(stubbyRequest); } @@ -364,7 +441,6 @@ public StubbyResponse doPost(final String host, final String uri, final int stub * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - public StubbyResponse doPostUsingDefaults(final String uri, final String payload) throws Exception { return doPostUsingDefaults(uri, payload, null); } @@ -380,8 +456,8 @@ public StubbyResponse doPostUsingDefaults(final String uri, final String payload * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - - public StubbyResponse doPostUsingDefaults(final String uri, final String payload, final Authorization authorization) throws Exception { + public StubbyResponse doPostUsingDefaults(final String uri, final String payload, final Authorization authorization) + throws Exception { return doPost(JettyFactory.DEFAULT_HOST, uri, JettyFactory.DEFAULT_STUBS_PORT, authorization, payload); } @@ -398,9 +474,21 @@ public StubbyResponse doPostUsingDefaults(final String uri, final String payload * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - - public StubbyResponse doPut(final String host, final String uri, final int stubsPort, final Authorization authorization, final String payload) throws Exception { - final StubbyRequest stubbyRequest = new StubbyRequest(HttpScheme.HTTP.asString().toLowerCase(Locale.US), HttpMethod.PUT.asString(), uri, host, stubsPort, authorization, payload); + public StubbyResponse doPut( + final String host, + final String uri, + final int stubsPort, + final Authorization authorization, + final String payload) + throws Exception { + final StubbyRequest stubbyRequest = new StubbyRequest( + HttpScheme.HTTP.asString().toLowerCase(Locale.US), + HttpMethod.PUT.asString(), + uri, + host, + stubsPort, + authorization, + payload); return makeRequest(stubbyRequest); } @@ -419,9 +507,21 @@ public StubbyResponse doPut(final String host, final String uri, final int stubs * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - - public StubbyResponse doPutOverSsl(final String host, final String uri, final int stubsPort, final Authorization authorization, final String payload) throws Exception { - final StubbyRequest stubbyRequest = new StubbyRequest(HttpScheme.HTTPS.asString().toLowerCase(Locale.US), HttpMethod.PUT.asString(), uri, host, stubsPort, authorization, payload); + public StubbyResponse doPutOverSsl( + final String host, + final String uri, + final int stubsPort, + final Authorization authorization, + final String payload) + throws Exception { + final StubbyRequest stubbyRequest = new StubbyRequest( + HttpScheme.HTTPS.asString().toLowerCase(Locale.US), + HttpMethod.PUT.asString(), + uri, + host, + stubsPort, + authorization, + payload); return makeRequest(stubbyRequest); } @@ -438,9 +538,16 @@ public StubbyResponse doPutOverSsl(final String host, final String uri, final in * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - - public StubbyResponse doDelete(final String host, final String uri, final int stubsPort, final Authorization authorization) throws Exception { - final StubbyRequest stubbyRequest = new StubbyRequest(HttpScheme.HTTP.asString().toLowerCase(Locale.US), HttpMethod.DELETE.asString(), uri, host, stubsPort, authorization); + public StubbyResponse doDelete( + final String host, final String uri, final int stubsPort, final Authorization authorization) + throws Exception { + final StubbyRequest stubbyRequest = new StubbyRequest( + HttpScheme.HTTP.asString().toLowerCase(Locale.US), + HttpMethod.DELETE.asString(), + uri, + host, + stubsPort, + authorization); return makeRequest(stubbyRequest); } @@ -458,9 +565,15 @@ public StubbyResponse doDelete(final String host, final String uri, final int st * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - - public StubbyResponse doDeleteOverSsl(final String host, final String uri, final int port, final Authorization authorization) throws Exception { - final StubbyRequest stubbyRequest = new StubbyRequest(HttpScheme.HTTPS.asString().toLowerCase(Locale.US), HttpMethod.DELETE.asString(), uri, host, port, authorization); + public StubbyResponse doDeleteOverSsl( + final String host, final String uri, final int port, final Authorization authorization) throws Exception { + final StubbyRequest stubbyRequest = new StubbyRequest( + HttpScheme.HTTPS.asString().toLowerCase(Locale.US), + HttpMethod.DELETE.asString(), + uri, + host, + port, + authorization); return makeRequest(stubbyRequest); } @@ -476,13 +589,20 @@ public StubbyResponse doDeleteOverSsl(final String host, final String uri, final * @param method POST or PUT * @param stubsData data to post/put */ - public StubbyResponse updateStubbedData(final String url, HttpMethod method, final String stubsData) throws Exception { + public StubbyResponse updateStubbedData(final String url, HttpMethod method, final String stubsData) + throws Exception { if (method != HttpMethod.PUT && method != HttpMethod.POST) { throw new IllegalArgumentException("Unexpected HTTP method: " + method.asString()); } final URL adminUrl = new URL(url); - return makeRequest(adminUrl.getProtocol(), method.asString(), adminUrl.getHost(), adminUrl.getPath(), adminUrl.getPort(), stubsData); + return makeRequest( + adminUrl.getProtocol(), + method.asString(), + adminUrl.getHost(), + adminUrl.getPath(), + adminUrl.getPort(), + stubsData); } /** @@ -497,7 +617,13 @@ public StubbyResponse updateStubbedData(final String url, HttpMethod method, fin public StubbyResponse updateStubbedData(final String url, final String stubsData) throws Exception { final URL adminUrl = new URL(url); - return makeRequest(adminUrl.getProtocol(), HttpMethod.POST.asString(), adminUrl.getHost(), adminUrl.getPath(), adminUrl.getPort(), stubsData); + return makeRequest( + adminUrl.getProtocol(), + HttpMethod.POST.asString(), + adminUrl.getHost(), + adminUrl.getPath(), + adminUrl.getPort(), + stubsData); } /** @@ -512,13 +638,14 @@ public StubbyResponse updateStubbedData(final String url, final String stubsData * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - - public StubbyResponse makeRequest(final String scheme, - final String method, - final String host, - final String uri, - final int port, - final String post) throws Exception { + public StubbyResponse makeRequest( + final String scheme, + final String method, + final String host, + final String uri, + final int port, + final String post) + throws Exception { return makeRequest(scheme, method, host, uri, port, post, null); } @@ -535,14 +662,15 @@ public StubbyResponse makeRequest(final String scheme, * @return StubbyResponse with HTTP status code and message from the server * @throws Exception */ - - public StubbyResponse makeRequest(final String scheme, - final String method, - final String host, - final String uri, - final int port, - final String post, - final Authorization authorization) throws Exception { + public StubbyResponse makeRequest( + final String scheme, + final String method, + final String host, + final String uri, + final int port, + final String post, + final Authorization authorization) + throws Exception { final StubbyRequest stubbyRequest = new StubbyRequest(scheme, method, uri, host, port, authorization, post); return makeRequest(stubbyRequest); @@ -555,21 +683,24 @@ private StubbyResponse makeRequest(final StubbyRequest stubbyRequest) throws Exc headers.put("Authorization", stubbyRequest.getAuthorization().asFullValue()); } - return new StubbyHttpTransport().request( - stubbyRequest.getMethod(), - stubbyRequest.constructFullUrl(), - stubbyRequest.getPost(), - headers, - stubbyRequest.calculatePostLength()); + return new StubbyHttpTransport() + .request( + stubbyRequest.getMethod(), + stubbyRequest.constructFullUrl(), + stubbyRequest.getPost(), + headers, + stubbyRequest.calculatePostLength()); } private CompletableFuture parseYamlAsync(final File configFile) { - return CompletableFuture.supplyAsync(() -> { - try { - return new YamlParser().parse(configFile.getParent(), configFile); - } catch (IOException ioEx) { - throw new UncheckedIOException(ioEx); - } - }, EXECUTOR_SERVICE); + return CompletableFuture.supplyAsync( + () -> { + try { + return new YamlParser().parse(configFile.getParent(), configFile); + } catch (IOException ioEx) { + throw new UncheckedIOException(ioEx); + } + }, + EXECUTOR_SERVICE); } } diff --git a/src/main/java/io/github/azagniotov/stubby4j/client/StubbyRequest.java b/src/main/java/io/github/azagniotov/stubby4j/client/StubbyRequest.java index 10f77f69b..52d36f8de 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/client/StubbyRequest.java +++ b/src/main/java/io/github/azagniotov/stubby4j/client/StubbyRequest.java @@ -1,7 +1,22 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.client; import io.github.azagniotov.stubby4j.utils.StringUtils; - import java.util.Locale; final class StubbyRequest { @@ -16,23 +31,24 @@ final class StubbyRequest { private final Authorization authorization; private final int clientPort; - - StubbyRequest(final String scheme, - final String method, - final String uri, - final String host, - final int port, - final Authorization authorization) { + StubbyRequest( + final String scheme, + final String method, + final String uri, + final String host, + final int port, + final Authorization authorization) { this(scheme, method, uri, host, port, authorization, null); } - StubbyRequest(final String scheme, - final String method, - final String uri, - final String host, - final int clientPort, - final Authorization authorization, - final String post) { + StubbyRequest( + final String scheme, + final String method, + final String uri, + final String host, + final int clientPort, + final Authorization authorization, + final String post) { this.scheme = scheme; this.method = method; this.uri = uri; @@ -55,7 +71,8 @@ Authorization getAuthorization() { } String constructFullUrl() { - return String.format(URL_TEMPLATE, scheme.toLowerCase(Locale.US), host, clientPort, StringUtils.isSet(uri) ? uri : ""); + return String.format( + URL_TEMPLATE, scheme.toLowerCase(Locale.US), host, clientPort, StringUtils.isSet(uri) ? uri : ""); } int calculatePostLength() { diff --git a/src/main/java/io/github/azagniotov/stubby4j/client/StubbyResponse.java b/src/main/java/io/github/azagniotov/stubby4j/client/StubbyResponse.java index 31f66a50e..4a3e0e70d 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/client/StubbyResponse.java +++ b/src/main/java/io/github/azagniotov/stubby4j/client/StubbyResponse.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.client; import java.util.HashMap; @@ -10,9 +26,7 @@ public final class StubbyResponse { private final String body; private final Map> headerFields; - public StubbyResponse(final int statusCode, - final String body, - final Map> headerFields) { + public StubbyResponse(final int statusCode, final String body, final Map> headerFields) { this.statusCode = statusCode; this.body = body; this.headerFields = headerFields; @@ -29,4 +43,4 @@ public String body() { public Map> headers() { return new HashMap<>(headerFields); } -} \ No newline at end of file +} diff --git a/src/main/java/io/github/azagniotov/stubby4j/common/Common.java b/src/main/java/io/github/azagniotov/stubby4j/common/Common.java index 3554db3ee..6387110f4 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/common/Common.java +++ b/src/main/java/io/github/azagniotov/stubby4j/common/Common.java @@ -1,20 +1,37 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.common; import io.github.azagniotov.stubby4j.http.HttpMethodExtended; -import org.eclipse.jetty.http.HttpMethod; - import java.util.Collections; import java.util.HashSet; import java.util.Set; +import org.eclipse.jetty.http.HttpMethod; public final class Common { - public static final Set POSTING_METHODS = Collections.unmodifiableSet(new HashSet() {{ - add(HttpMethod.PUT.asString()); - add(HttpMethod.POST.asString()); - // PATCH is not a part of org.eclipse.jetty.http.HttpMethod - add(HttpMethodExtended.PATCH.asString()); - }}); + public static final Set POSTING_METHODS = Collections.unmodifiableSet(new HashSet() { + { + add(HttpMethod.PUT.asString()); + add(HttpMethod.POST.asString()); + // PATCH is not a part of org.eclipse.jetty.http.HttpMethod + add(HttpMethodExtended.PATCH.asString()); + } + }); public static final String HEADER_APPLICATION_JSON = "application/json"; public static final String HEADER_APPLICATION_XML = "application/xml"; @@ -24,7 +41,5 @@ public final class Common { public static final String HEADER_X_STUBBY_PROXY_RESPONSE = "x-stubby4j-proxy-response-uuid"; public static final String HEADER_X_STUBBY_HTTP_ERROR_REAL_REASON = "x-stubby4j-http-error-real-reason"; - private Common() { - - } + private Common() {} } diff --git a/src/main/java/io/github/azagniotov/stubby4j/filesystem/ExternalFilesScanner.java b/src/main/java/io/github/azagniotov/stubby4j/filesystem/ExternalFilesScanner.java index 284bb2814..b7a6824c0 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/filesystem/ExternalFilesScanner.java +++ b/src/main/java/io/github/azagniotov/stubby4j/filesystem/ExternalFilesScanner.java @@ -1,17 +1,32 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.filesystem; +import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; + import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.utils.DateTimeUtils; import io.github.azagniotov.stubby4j.yaml.YamlParser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.File; import java.util.Map; - -import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @GeneratedCodeClassCoverageExclusion public final class ExternalFilesScanner implements Runnable { @@ -23,8 +38,11 @@ public final class ExternalFilesScanner implements Runnable { public ExternalFilesScanner(final StubRepository stubRepository, final long sleepTime) { this.sleepTime = sleepTime; this.stubRepository = stubRepository; - ANSITerminal.status(String.format("External file scan enabled, watching external files referenced from %s", stubRepository.getYamlConfigCanonicalPath())); - LOGGER.debug("External file scan enabled, watching external files referenced from {}.", + ANSITerminal.status(String.format( + "External file scan enabled, watching external files referenced from %s", + stubRepository.getYamlConfigCanonicalPath())); + LOGGER.debug( + "External file scan enabled, watching external files referenced from {}.", stubRepository.getYamlConfigCanonicalPath()); } @@ -57,18 +75,25 @@ public void run() { continue; } - ANSITerminal.info(String.format("%sExternal file scan detected change in %s%s", BR, offendingFilename, BR)); + ANSITerminal.info( + String.format("%sExternal file scan detected change in %s%s", BR, offendingFilename, BR)); LOGGER.info("External file scan detected change in {}.", offendingFilename); try { stubRepository.refreshStubsFromYamlConfig(new YamlParser()); - ANSITerminal.ok(String.format("%sSuccessfully performed live refresh of main YAML with external files from: %s on [" + DateTimeUtils.systemDefault() + "]%s", - BR, stubRepository.getYamlConfig(), BR)); - LOGGER.info("Successfully performed live refresh of main YAML with external files from: {}.", + ANSITerminal.ok(String.format( + "%sSuccessfully performed live refresh of main YAML with external files from: %s on [" + + DateTimeUtils.systemDefault() + "]%s", + BR, + stubRepository.getYamlConfig(), + BR)); + LOGGER.info( + "Successfully performed live refresh of main YAML with external files from: {}.", stubRepository.getYamlConfig()); } catch (final Exception ex) { - ANSITerminal.error("Could not refresh YAML configuration, previously loaded stubs remain untouched." + ex.toString()); + ANSITerminal.error("Could not refresh YAML configuration, previously loaded stubs remain untouched." + + ex.toString()); LOGGER.error("Could not refresh YAML configuration, previously loaded stubs remain untouched.", ex); } } @@ -78,4 +103,4 @@ public void run() { LOGGER.error("Could not perform live YAML scan.", ex); } } -} \ No newline at end of file +} diff --git a/src/main/java/io/github/azagniotov/stubby4j/filesystem/MainIncludedYamlScanner.java b/src/main/java/io/github/azagniotov/stubby4j/filesystem/MainIncludedYamlScanner.java index dd4602cba..97da1df91 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/filesystem/MainIncludedYamlScanner.java +++ b/src/main/java/io/github/azagniotov/stubby4j/filesystem/MainIncludedYamlScanner.java @@ -1,21 +1,36 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.filesystem; +import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; + import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.utils.DateTimeUtils; import io.github.azagniotov.stubby4j.utils.FileUtils; import io.github.azagniotov.stubby4j.yaml.YamlParser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.File; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; - -import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @GeneratedCodeClassCoverageExclusion public final class MainIncludedYamlScanner implements Runnable { @@ -51,8 +66,11 @@ public void run() { return; } - ANSITerminal.status(String.format("Main YAML with included YAMLs scan enabled, watching included YAMLs referenced from %s", stubRepository.getYamlConfigCanonicalPath())); - LOGGER.debug("Main YAML with included YAMLs scan enabled, watching included YAMLs referenced from {}.", + ANSITerminal.status(String.format( + "Main YAML with included YAMLs scan enabled, watching included YAMLs referenced from %s", + stubRepository.getYamlConfigCanonicalPath())); + LOGGER.debug( + "Main YAML with included YAMLs scan enabled, watching included YAMLs referenced from {}.", stubRepository.getYamlConfigCanonicalPath()); final List yamlIncludes = yamlParser.getYamlIncludes(mainYamlParentDirectory, rawYamlConfig); @@ -84,26 +102,34 @@ public void run() { continue; } - ANSITerminal.info(String.format("%sMain YAML included YAMLs scan detected change in %s%s", BR, offendingFilename, BR)); + ANSITerminal.info(String.format( + "%sMain YAML included YAMLs scan detected change in %s%s", BR, offendingFilename, BR)); LOGGER.info("Main YAML included YAMLs scan detected change in {}.", offendingFilename); try { stubRepository.refreshStubsFromYamlConfig(yamlParser); - ANSITerminal.ok(String.format("%sSuccessfully performed live refresh of main YAML with included YAMLs from: %s on [" + DateTimeUtils.systemDefault() + "]%s", - BR, stubRepository.getYamlConfig(), BR)); - LOGGER.info("Successfully performed live refresh of main YAML with included YAMLs from: {}.", + ANSITerminal.ok(String.format( + "%sSuccessfully performed live refresh of main YAML with included YAMLs from: %s on [" + + DateTimeUtils.systemDefault() + "]%s", + BR, + stubRepository.getYamlConfig(), + BR)); + LOGGER.info( + "Successfully performed live refresh of main YAML with included YAMLs from: {}.", stubRepository.getYamlConfig()); } catch (final Exception ex) { - ANSITerminal.error("Could not refresh YAML configuration, previously loaded stubs remain untouched." + ex.toString()); - LOGGER.error("Could not refresh YAML configuration, previously loaded stubs remain untouched.", ex); + ANSITerminal.error( + "Could not refresh YAML configuration, previously loaded stubs remain untouched." + + ex.toString()); + LOGGER.error( + "Could not refresh YAML configuration, previously loaded stubs remain untouched.", ex); } } - } } catch (final Exception ex) { ex.printStackTrace(); LOGGER.error("Could not perform live main YAML scan with included YAMLs.", ex); } } -} \ No newline at end of file +} diff --git a/src/main/java/io/github/azagniotov/stubby4j/filesystem/MainYamlScanner.java b/src/main/java/io/github/azagniotov/stubby4j/filesystem/MainYamlScanner.java index aa7141625..c468052ae 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/filesystem/MainYamlScanner.java +++ b/src/main/java/io/github/azagniotov/stubby4j/filesystem/MainYamlScanner.java @@ -1,17 +1,32 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.filesystem; +import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; + import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.utils.DateTimeUtils; import io.github.azagniotov.stubby4j.yaml.YamlParser; +import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; - -import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; - @GeneratedCodeClassCoverageExclusion public final class MainYamlScanner implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(MainYamlScanner.class); @@ -22,7 +37,8 @@ public final class MainYamlScanner implements Runnable { public MainYamlScanner(final StubRepository stubRepository, final long sleepTime) { this.sleepTime = sleepTime; this.stubRepository = stubRepository; - ANSITerminal.status(String.format("Main YAML scan enabled, watching %s", stubRepository.getYamlConfigCanonicalPath())); + ANSITerminal.status( + String.format("Main YAML scan enabled, watching %s", stubRepository.getYamlConfigCanonicalPath())); LOGGER.debug("Main YAML scan enabled, watching {}.", stubRepository.getYamlConfigCanonicalPath()); } @@ -42,19 +58,26 @@ public void run() { continue; } - ANSITerminal.info(String.format("%sMain YAML scan detected change in %s%s", BR, stubRepository.getYamlConfigCanonicalPath(), BR)); + ANSITerminal.info(String.format( + "%sMain YAML scan detected change in %s%s", + BR, stubRepository.getYamlConfigCanonicalPath(), BR)); LOGGER.info("Main YAML scan detected change in {}.", stubRepository.getYamlConfigCanonicalPath()); try { mainYamlLastModified = currentFileModified; stubRepository.refreshStubsFromYamlConfig(new YamlParser()); - ANSITerminal.ok(String.format("%sSuccessfully performed live refresh of main YAML file from: %s on [" + DateTimeUtils.systemDefault() + "]%s", - BR, dataYaml.getAbsolutePath(), BR)); - LOGGER.info("Successfully performed live refresh of main YAML from: {}.", - dataYaml.getAbsolutePath()); + ANSITerminal.ok(String.format( + "%sSuccessfully performed live refresh of main YAML file from: %s on [" + + DateTimeUtils.systemDefault() + "]%s", + BR, + dataYaml.getAbsolutePath(), + BR)); + LOGGER.info( + "Successfully performed live refresh of main YAML from: {}.", dataYaml.getAbsolutePath()); } catch (final Exception ex) { - ANSITerminal.error("Could not refresh main YAML configuration, in-memory stubs remain untouched." + ex.toString()); + ANSITerminal.error("Could not refresh main YAML configuration, in-memory stubs remain untouched." + + ex.toString()); LOGGER.error("Could not refresh main YAML configuration, in-memory stubs remain untouched.", ex); } } @@ -63,4 +86,4 @@ public void run() { LOGGER.error("Could not perform live YAML scan.", ex); } } -} \ No newline at end of file +} diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/AbstractHandlerExtension.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/AbstractHandlerExtension.java index 7cd7982c0..725bccf85 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/AbstractHandlerExtension.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/AbstractHandlerExtension.java @@ -1,20 +1,37 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers; import io.github.azagniotov.stubby4j.utils.ConsoleUtils; -import org.eclipse.jetty.server.Request; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.eclipse.jetty.server.Request; public interface AbstractHandlerExtension { - default boolean logAndCheckIsHandled(final String handlerName, - final Request baseRequest, - final HttpServletRequest request, - final HttpServletResponse response) { + default boolean logAndCheckIsHandled( + final String handlerName, + final Request baseRequest, + final HttpServletRequest request, + final HttpServletResponse response) { ConsoleUtils.logIncomingRequest(request); if (baseRequest.isHandled() || response.isCommitted()) { - ConsoleUtils.logIncomingRequestError(request, handlerName, "HTTP response was committed or base request was handled, aborting.."); + ConsoleUtils.logIncomingRequestError( + request, handlerName, "HTTP response was committed or base request was handled, aborting.."); return true; } diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/AdminPortalHandler.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/AdminPortalHandler.java index 27321ebaf..190c12abe 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/AdminPortalHandler.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/AdminPortalHandler.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers; import io.github.azagniotov.stubby4j.handlers.strategy.admin.AdminResponseHandlingStrategy; @@ -5,20 +21,19 @@ import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.utils.ConsoleUtils; import io.github.azagniotov.stubby4j.utils.HandlerUtils; -import org.eclipse.jetty.http.HttpStatus; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.handler.AbstractHandler; - +import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; +import org.eclipse.jetty.http.HttpStatus; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.handler.AbstractHandler; public class AdminPortalHandler extends AbstractHandler implements AbstractHandlerExtension { public static final String NAME = "admin"; - //Do not remove this constant without changing the example in documentation + // Do not remove this constant without changing the example in documentation public static final String ADMIN_ROOT = "/"; private final StubRepository stubRepository; @@ -27,7 +42,12 @@ public AdminPortalHandler(final StubRepository stubRepository) { } @Override - public void handle(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { + public void handle( + final String target, + final Request baseRequest, + final HttpServletRequest request, + final HttpServletResponse response) + throws IOException, ServletException { if (logAndCheckIsHandled(NAME, baseRequest, request, response)) { return; } @@ -36,11 +56,15 @@ public void handle(final String target, final Request baseRequest, final HttpSer HandlerUtils.setResponseMainHeaders(response); response.setStatus(HttpStatus.OK_200); - final AdminResponseHandlingStrategy strategyStubResponse = AdminResponseHandlingStrategyFactory.getStrategy(request); + final AdminResponseHandlingStrategy strategyStubResponse = + AdminResponseHandlingStrategyFactory.getStrategy(request); try { strategyStubResponse.handle(request, response, stubRepository); } catch (final Exception ex) { - HandlerUtils.configureErrorResponse(response, HttpStatus.INTERNAL_SERVER_ERROR_500, "Problem handling request in Admin handler: " + ex.toString()); + HandlerUtils.configureErrorResponse( + response, + HttpStatus.INTERNAL_SERVER_ERROR_500, + "Problem handling request in Admin handler: " + ex.toString()); } ConsoleUtils.logOutgoingResponse(request.getRequestURI(), response); diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/AjaxEndpointStatsHandler.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/AjaxEndpointStatsHandler.java index b48fdf959..952c31972 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/AjaxEndpointStatsHandler.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/AjaxEndpointStatsHandler.java @@ -1,19 +1,34 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers; +import static io.github.azagniotov.stubby4j.utils.HandlerUtils.getHtmlResourceByName; + import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.utils.ConsoleUtils; import io.github.azagniotov.stubby4j.utils.HandlerUtils; -import org.eclipse.jetty.http.HttpStatus; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.handler.AbstractHandler; - +import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -import static io.github.azagniotov.stubby4j.utils.HandlerUtils.getHtmlResourceByName; +import org.eclipse.jetty.http.HttpStatus; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.handler.AbstractHandler; @GeneratedCodeClassCoverageExclusion public class AjaxEndpointStatsHandler extends AbstractHandler implements AbstractHandlerExtension { @@ -25,7 +40,12 @@ public AjaxEndpointStatsHandler(final StubRepository stubRepository) { } @Override - public void handle(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { + public void handle( + final String target, + final Request baseRequest, + final HttpServletRequest request, + final HttpServletResponse response) + throws IOException, ServletException { if (logAndCheckIsHandled("ajaxEndpoint", baseRequest, request, response)) { return; } diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/AjaxResourceContentHandler.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/AjaxResourceContentHandler.java index f7da8f8fc..5057882b3 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/AjaxResourceContentHandler.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/AjaxResourceContentHandler.java @@ -1,5 +1,23 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers; +import static io.github.azagniotov.stubby4j.utils.HandlerUtils.getHtmlResourceByName; + import io.github.azagniotov.stubby4j.annotations.VisibleForTesting; import io.github.azagniotov.stubby4j.stubs.StubHttpLifecycle; import io.github.azagniotov.stubby4j.stubs.StubRepository; @@ -9,18 +27,15 @@ import io.github.azagniotov.stubby4j.utils.HandlerUtils; import io.github.azagniotov.stubby4j.utils.ReflectionUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; -import org.eclipse.jetty.http.HttpStatus; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.handler.AbstractHandler; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Optional; import java.util.regex.Pattern; - -import static io.github.azagniotov.stubby4j.utils.HandlerUtils.getHtmlResourceByName; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.eclipse.jetty.http.HttpStatus; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.handler.AbstractHandler; public class AjaxResourceContentHandler extends AbstractHandler implements AbstractHandlerExtension { @@ -37,7 +52,12 @@ public AjaxResourceContentHandler(final StubRepository stubRepository) { } @Override - public void handle(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { + public void handle( + final String target, + final Request baseRequest, + final HttpServletRequest request, + final HttpServletResponse response) + throws IOException, ServletException { if (logAndCheckIsHandled("ajaxResource", baseRequest, request, response)) { return; } @@ -47,7 +67,8 @@ public void handle(final String target, final Request baseRequest, final HttpSer response.setContentType("text/plain;charset=UTF-8"); response.setStatus(HttpStatus.OK_200); - // e.g.: http://localhost:8889/ajax/resource/proxy-config/some-unique-name/proxyConfigAsYAML => /proxy-config/some-unique-name/proxyConfigAsYAML + // e.g.: http://localhost:8889/ajax/resource/proxy-config/some-unique-name/proxyConfigAsYAML => + // /proxy-config/some-unique-name/proxyConfigAsYAML // e.g.: http://localhost:8889/ajax/resource/32/httplifecycle/responseAsYAML => /32/httplifecycle/responseAsYAML // e.g.: http://localhost:8889/ajax/resource/0/response/body => /0/response/body final String[] uriFragments = request.getRequestURI().split("/"); @@ -79,7 +100,8 @@ public void handle(final String target, final Request baseRequest, final HttpSer } else if (REGEX_HTTPLIFECYCLE.matcher(stubType).matches()) { renderAjaxResponseContent(response, StubTypes.HTTPLIFECYCLE, targetFieldName, foundStub); } else { - response.getWriter().println(String.format("Could not fetch the content for stub type: %s", stubType)); + response.getWriter() + .println(String.format("Could not fetch the content for stub type: %s", stubType)); } } // e.g.: /proxy-config/some-unique-name/proxyConfigAsYAML , the 'proxy-config' @@ -89,18 +111,22 @@ else if (REGEX_PROXY_CONFIG.matcher(resourceIndexAsString).matches()) { final StubProxyConfig foundProxyConfig = stubRepository.matchProxyConfigByName(stubType); renderProxyConfigAjaxResponse(response, targetFieldName, foundProxyConfig); } else { - response.getWriter().println(String.format("Could not fetch the content for proxy config: %s", resourceIndexAsString)); + response.getWriter() + .println(String.format( + "Could not fetch the content for proxy config: %s", resourceIndexAsString)); } - } ConsoleUtils.logOutgoingResponse(request.getRequestURI(), response); } @VisibleForTesting - void renderProxyConfigAjaxResponse(final HttpServletResponse response, final String targetFieldName, final StubProxyConfig foundProxyConfig) throws IOException { + void renderProxyConfigAjaxResponse( + final HttpServletResponse response, final String targetFieldName, final StubProxyConfig foundProxyConfig) + throws IOException { try { - final String ajaxResponse = StringUtils.objectToString(ReflectionUtils.getPropertyValue(foundProxyConfig, targetFieldName)); + final String ajaxResponse = + StringUtils.objectToString(ReflectionUtils.getPropertyValue(foundProxyConfig, targetFieldName)); final String popupHtmlTemplate = getHtmlResourceByName("_popup_proxy_config"); final String htmlPopup = String.format(popupHtmlTemplate, foundProxyConfig.getUUID(), ajaxResponse); response.getWriter().println(htmlPopup); @@ -110,11 +136,17 @@ void renderProxyConfigAjaxResponse(final HttpServletResponse response, final Str } @VisibleForTesting - void renderAjaxResponseContent(final HttpServletResponse response, final StubTypes stubType, final String targetFieldName, final StubHttpLifecycle foundStub) throws IOException { + void renderAjaxResponseContent( + final HttpServletResponse response, + final StubTypes stubType, + final String targetFieldName, + final StubHttpLifecycle foundStub) + throws IOException { try { final String ajaxResponse = foundStub.getAjaxResponseContent(stubType, targetFieldName); final String popupHtmlTemplate = getHtmlResourceByName("_popup_generic"); - final String htmlPopup = String.format(popupHtmlTemplate, foundStub.getResourceId(), foundStub.getUUID(), ajaxResponse); + final String htmlPopup = + String.format(popupHtmlTemplate, foundStub.getResourceId(), foundStub.getUUID(), ajaxResponse); response.getWriter().println(htmlPopup); } catch (final Exception ex) { HandlerUtils.configureErrorResponse(response, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString()); @@ -122,11 +154,17 @@ void renderAjaxResponseContent(final HttpServletResponse response, final StubTyp } @VisibleForTesting - void renderAjaxResponseContent(final HttpServletResponse response, final int sequencedResponseId, final String targetFieldName, final StubHttpLifecycle foundStub) throws IOException { + void renderAjaxResponseContent( + final HttpServletResponse response, + final int sequencedResponseId, + final String targetFieldName, + final StubHttpLifecycle foundStub) + throws IOException { try { final String ajaxResponse = foundStub.getAjaxResponseContent(targetFieldName, sequencedResponseId); final String popupHtmlTemplate = getHtmlResourceByName("_popup_generic"); - final String htmlPopup = String.format(popupHtmlTemplate, foundStub.getResourceId(), foundStub.getUUID(), ajaxResponse); + final String htmlPopup = + String.format(popupHtmlTemplate, foundStub.getResourceId(), foundStub.getUUID(), ajaxResponse); response.getWriter().println(htmlPopup); } catch (final Exception ex) { HandlerUtils.configureErrorResponse(response, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString()); @@ -134,7 +172,8 @@ void renderAjaxResponseContent(final HttpServletResponse response, final int seq } @VisibleForTesting - StubHttpLifecycle throwErrorOnNonExistentResourceIndex(final HttpServletResponse response, final int resourceIndex) throws IOException { + StubHttpLifecycle throwErrorOnNonExistentResourceIndex(final HttpServletResponse response, final int resourceIndex) + throws IOException { final Optional foundStubOptional = stubRepository.matchStubByIndex(resourceIndex); if (!foundStubOptional.isPresent()) { final String error = "Resource does not exist for ID: " + resourceIndex; diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/FaviconHandler.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/FaviconHandler.java index 983cc378c..c90bacc96 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/FaviconHandler.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/FaviconHandler.java @@ -1,6 +1,29 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers; +import static io.github.azagniotov.stubby4j.utils.ObjectUtils.isNotNull; + import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; +import java.io.IOException; +import java.net.URL; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.server.Request; @@ -8,14 +31,6 @@ import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.resource.Resource; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.net.URL; - -import static io.github.azagniotov.stubby4j.utils.ObjectUtils.isNotNull; - @GeneratedCodeClassCoverageExclusion public class FaviconHandler extends AbstractHandler implements AbstractHandlerExtension { @@ -34,16 +49,20 @@ public FaviconHandler() { } @Override - public void handle(final String target, - final Request baseRequest, - final HttpServletRequest request, - final HttpServletResponse response) throws IOException, ServletException { + public void handle( + final String target, + final Request baseRequest, + final HttpServletRequest request, + final HttpServletResponse response) + throws IOException, ServletException { if (logAndCheckIsHandled("favicon", baseRequest, request, response)) { return; } baseRequest.setHandled(true); - if (isNotNull(faviconBytes) && HttpMethod.GET.is(request.getMethod()) && request.getRequestURI().equals("/favicon.ico")) { + if (isNotNull(faviconBytes) + && HttpMethod.GET.is(request.getMethod()) + && request.getRequestURI().equals("/favicon.ico")) { if (request.getDateHeader(HttpHeader.IF_MODIFIED_SINCE.toString()) == faviconModified) response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); else { diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/JsonErrorHandler.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/JsonErrorHandler.java index 2142e77d7..a5bcce510 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/JsonErrorHandler.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/JsonErrorHandler.java @@ -1,8 +1,30 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers; +import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_HTTP_ERROR_REAL_REASON; + import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.utils.HandlerUtils; +import java.io.IOException; +import java.io.Writer; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http.MimeTypes; @@ -12,13 +34,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.Writer; - -import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_HTTP_ERROR_REAL_REASON; - @GeneratedCodeClassCoverageExclusion public class JsonErrorHandler extends ErrorHandler { @@ -26,10 +41,12 @@ public class JsonErrorHandler extends ErrorHandler { private static final Logger LOGGER = LoggerFactory.getLogger(HandlerUtils.class); @Override - public void handle(final String target, - final Request baseRequest, - final HttpServletRequest request, - final HttpServletResponse response) throws IOException { + public void handle( + final String target, + final Request baseRequest, + final HttpServletRequest request, + final HttpServletResponse response) + throws IOException { baseRequest.setHandled(true); response.setContentType(MimeTypes.Type.APPLICATION_JSON.asString()); @@ -57,7 +74,8 @@ public boolean errorPageForMethod(final String method) { case DELETE: return true; default: - final String message = String.format("Skipped generating error JSON for method %s", httpMethod.asString()); + final String message = + String.format("Skipped generating error JSON for method %s", httpMethod.asString()); ANSITerminal.error(message); LOGGER.error(message); return false; @@ -65,17 +83,17 @@ public boolean errorPageForMethod(final String method) { } @Override - protected void writeErrorPage(final HttpServletRequest request, - final Writer writer, - final int code, - final String realReason, - final boolean showStacks) throws IOException { - writer.write("{" + - "\"code\":\"" + code + "\"," + - "\"message\":\"" + HttpStatus.getMessage(code) + "\"}"); -// writer.write("{" + -// "\"code\":\"" + code + "\"," + -// "\"message\":\"" + HttpStatus.getMessage(code) + "\"," + -// "\"reason\":" + realReason + "}"); + protected void writeErrorPage( + final HttpServletRequest request, + final Writer writer, + final int code, + final String realReason, + final boolean showStacks) + throws IOException { + writer.write("{" + "\"code\":\"" + code + "\"," + "\"message\":\"" + HttpStatus.getMessage(code) + "\"}"); + // writer.write("{" + + // "\"code\":\"" + code + "\"," + + // "\"message\":\"" + HttpStatus.getMessage(code) + "\"," + + // "\"reason\":" + realReason + "}"); } } diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/StatusPageHandler.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/StatusPageHandler.java index f97282ace..597254bbd 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/StatusPageHandler.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/StatusPageHandler.java @@ -1,5 +1,32 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers; +import static io.github.azagniotov.stubby4j.utils.HandlerUtils.getHtmlResourceByName; +import static io.github.azagniotov.stubby4j.utils.StringUtils.toUpper; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.BODY; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.FILE; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.POST; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.PROXY_CONFIG; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.REQUEST; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.RESPONSE; +import static java.util.Arrays.asList; +import static java.util.Collections.unmodifiableList; + import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; import io.github.azagniotov.stubby4j.cli.CommandLineInterpreter; import io.github.azagniotov.stubby4j.server.JettyContext; @@ -15,15 +42,6 @@ import io.github.azagniotov.stubby4j.utils.ReflectionUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; import io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty; -import org.eclipse.jetty.http.HttpHeader; -import org.eclipse.jetty.http.HttpScheme; -import org.eclipse.jetty.http.HttpStatus; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.handler.AbstractHandler; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; @@ -32,29 +50,31 @@ import java.util.List; import java.util.Locale; import java.util.Map; - -import static io.github.azagniotov.stubby4j.utils.HandlerUtils.getHtmlResourceByName; -import static io.github.azagniotov.stubby4j.utils.StringUtils.toUpper; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.BODY; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.FILE; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.POST; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.PROXY_CONFIG; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.REQUEST; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.RESPONSE; -import static java.util.Arrays.asList; -import static java.util.Collections.unmodifiableList; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.eclipse.jetty.http.HttpHeader; +import org.eclipse.jetty.http.HttpScheme; +import org.eclipse.jetty.http.HttpStatus; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.handler.AbstractHandler; @GeneratedCodeClassCoverageExclusion public final class StatusPageHandler extends AbstractHandler implements AbstractHandlerExtension { private static final RuntimeMXBean RUNTIME_MX_BEAN = ManagementFactory.getRuntimeMXBean(); private static final MemoryMXBean MEMORY_MX_BEAN = ManagementFactory.getMemoryMXBean(); - private static final List FIELDS_FOR_AJAX_LINKS = unmodifiableList(asList(FILE, BODY, POST)); - - private static final String TEMPLATE_LOADED_FILE_METADATA_PAIR = "%s=%s"; - private static final String TEMPLATE_AJAX_TO_RESOURCE_HYPERLINK = "[view]"; - private static final String TEMPLATE_AJAX_TO_STATS_HYPERLINK = "[view]"; - private static final String TEMPLATE_HTML_TABLE_ROW = "%s%s"; + private static final List FIELDS_FOR_AJAX_LINKS = + unmodifiableList(asList(FILE, BODY, POST)); + + private static final String TEMPLATE_LOADED_FILE_METADATA_PAIR = + "%s=%s"; + private static final String TEMPLATE_AJAX_TO_RESOURCE_HYPERLINK = + "[view]"; + private static final String TEMPLATE_AJAX_TO_STATS_HYPERLINK = + "[view]"; + private static final String TEMPLATE_HTML_TABLE_ROW = + "%s%s"; private static final String NEXT_IN_THE_QUEUE = " NEXT IN THE QUEUE"; private static final String HTML_BR = "
"; @@ -67,14 +87,20 @@ public StatusPageHandler(final JettyContext jettyContext, final StubRepository s } @Override - public void handle(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { + public void handle( + final String target, + final Request baseRequest, + final HttpServletRequest request, + final HttpServletResponse response) + throws IOException, ServletException { if (logAndCheckIsHandled("status", baseRequest, request, response)) { return; } baseRequest.setHandled(true); response.setContentType("text/html;charset=UTF-8"); response.setStatus(HttpStatus.OK_200); - response.setHeader(HttpHeader.SERVER.asString().toLowerCase(Locale.US), HandlerUtils.constructHeaderServerName()); + response.setHeader( + HttpHeader.SERVER.asString().toLowerCase(Locale.US), HandlerUtils.constructHeaderServerName()); try { response.getWriter().println(buildStatusPageHtml()); @@ -120,25 +146,35 @@ private String buildStatusPageHtml() throws Exception { return HandlerUtils.populateHtmlTemplate("status", timestamp, timestamp, builder.toString()); } - private String buildStubProxyConfigtHtmlTable(final StubProxyConfig stubProxyConfig, final String templateHtmlTable) throws Exception { + private String buildStubProxyConfigtHtmlTable(final StubProxyConfig stubProxyConfig, final String templateHtmlTable) + throws Exception { final String proxyUuid = stubProxyConfig.getUUID(); - final String ajaxLinkToRequestAsYaml = String.format(TEMPLATE_AJAX_TO_RESOURCE_HYPERLINK, PROXY_CONFIG, proxyUuid, "proxyConfigAsYAML"); - final StringBuilder proxyConfigTableBuilder = buildStubHtmlTableBody(proxyUuid, PROXY_CONFIG.toString(), ReflectionUtils.getProperties(stubProxyConfig)); + final String ajaxLinkToRequestAsYaml = + String.format(TEMPLATE_AJAX_TO_RESOURCE_HYPERLINK, PROXY_CONFIG, proxyUuid, "proxyConfigAsYAML"); + final StringBuilder proxyConfigTableBuilder = buildStubHtmlTableBody( + proxyUuid, PROXY_CONFIG.toString(), ReflectionUtils.getProperties(stubProxyConfig)); proxyConfigTableBuilder.append(interpolateHtmlTableRowTemplate("RAW YAML", ajaxLinkToRequestAsYaml)); return String.format(templateHtmlTable, PROXY_CONFIG, proxyConfigTableBuilder.toString()); } - private String buildStubRequestHtmlTable(final StubHttpLifecycle stubHttpLifecycle, final String templateHtmlTable) throws Exception { + private String buildStubRequestHtmlTable(final StubHttpLifecycle stubHttpLifecycle, final String templateHtmlTable) + throws Exception { final String resourceId = stubHttpLifecycle.getResourceId(); - final String ajaxLinkToRequestAsYaml = String.format(TEMPLATE_AJAX_TO_RESOURCE_HYPERLINK, resourceId, ConfigurableYAMLProperty.HTTPLIFECYCLE, "requestAsYAML"); - final StringBuilder requestTableBuilder = buildStubHtmlTableBody(resourceId, REQUEST.toString(), ReflectionUtils.getProperties(stubHttpLifecycle.getRequest())); + final String ajaxLinkToRequestAsYaml = String.format( + TEMPLATE_AJAX_TO_RESOURCE_HYPERLINK, + resourceId, + ConfigurableYAMLProperty.HTTPLIFECYCLE, + "requestAsYAML"); + final StringBuilder requestTableBuilder = buildStubHtmlTableBody( + resourceId, REQUEST.toString(), ReflectionUtils.getProperties(stubHttpLifecycle.getRequest())); requestTableBuilder.append(interpolateHtmlTableRowTemplate("RAW YAML", ajaxLinkToRequestAsYaml)); return String.format(templateHtmlTable, REQUEST, requestTableBuilder.toString()); } - private String buildStubResponseHtmlTable(final StubHttpLifecycle stubHttpLifecycle, final String templateHtmlTable) throws Exception { + private String buildStubResponseHtmlTable(final StubHttpLifecycle stubHttpLifecycle, final String templateHtmlTable) + throws Exception { final String resourceId = stubHttpLifecycle.getResourceId(); final StringBuilder responseTableBuilder = new StringBuilder(); final List allResponses = stubHttpLifecycle.getResponses(); @@ -146,15 +182,24 @@ private String buildStubResponseHtmlTable(final StubHttpLifecycle stubHttpLifecy final boolean isResponsesSequenced = allResponses.size() != 1; final int nextSequencedResponseId = stubHttpLifecycle.getNextSequencedResponseId(); - final String nextResponseLabel = (isResponsesSequenced && nextSequencedResponseId == sequenceId ? NEXT_IN_THE_QUEUE : ""); - final String responseTableTitle = (isResponsesSequenced ? String.format("%s/%s%s", RESPONSE, sequenceId, nextResponseLabel) : RESPONSE.toString()); + final String nextResponseLabel = + (isResponsesSequenced && nextSequencedResponseId == sequenceId ? NEXT_IN_THE_QUEUE : ""); + final String responseTableTitle = (isResponsesSequenced + ? String.format("%s/%s%s", RESPONSE, sequenceId, nextResponseLabel) + : RESPONSE.toString()); final StubResponse stubResponse = allResponses.get(sequenceId); final Map stubResponseProperties = ReflectionUtils.getProperties(stubResponse); - final StringBuilder sequencedResponseBuilder = buildStubHtmlTableBody(resourceId, responseTableTitle, stubResponseProperties); - final String ajaxLinkToResponseAsYaml = String.format(TEMPLATE_AJAX_TO_RESOURCE_HYPERLINK, resourceId, ConfigurableYAMLProperty.HTTPLIFECYCLE, "responseAsYAML"); + final StringBuilder sequencedResponseBuilder = + buildStubHtmlTableBody(resourceId, responseTableTitle, stubResponseProperties); + final String ajaxLinkToResponseAsYaml = String.format( + TEMPLATE_AJAX_TO_RESOURCE_HYPERLINK, + resourceId, + ConfigurableYAMLProperty.HTTPLIFECYCLE, + "responseAsYAML"); sequencedResponseBuilder.append(interpolateHtmlTableRowTemplate("RAW YAML", ajaxLinkToResponseAsYaml)); - responseTableBuilder.append(String.format(templateHtmlTable, responseTableTitle, sequencedResponseBuilder.toString())); + responseTableBuilder.append( + String.format(templateHtmlTable, responseTableTitle, sequencedResponseBuilder.toString())); } return responseTableBuilder.toString(); @@ -167,7 +212,8 @@ private String buildJvmParametersHtmlTable(final String templateHtmlTable) throw builder.append(interpolateHtmlTableRowTemplate("INPUT ARGS", RUNTIME_MX_BEAN.getInputArguments())); } builder.append(interpolateHtmlTableRowTemplate("HEAP MEMORY USAGE", MEMORY_MX_BEAN.getHeapMemoryUsage())); - builder.append(interpolateHtmlTableRowTemplate("NON-HEAP MEMORY USAGE", MEMORY_MX_BEAN.getNonHeapMemoryUsage())); + builder.append( + interpolateHtmlTableRowTemplate("NON-HEAP MEMORY USAGE", MEMORY_MX_BEAN.getNonHeapMemoryUsage())); return String.format(templateHtmlTable, "jvm", builder.toString()); } @@ -181,7 +227,8 @@ private String buildJettyParametersHtmlTable(final String templateHtmlTable) thr builder.append(interpolateHtmlTableRowTemplate("ADMIN PORT", adminPort)); builder.append(interpolateHtmlTableRowTemplate("STUBS PORT", jettyContext.getStubsPort())); builder.append(interpolateHtmlTableRowTemplate("STUBS TLS PORT", jettyContext.getStubsTlsPort())); - final String endpointRegistration = HandlerUtils.linkifyRequestUrl(HttpScheme.HTTP.asString(), AdminPortalHandler.ADMIN_ROOT, host, adminPort); + final String endpointRegistration = HandlerUtils.linkifyRequestUrl( + HttpScheme.HTTP.asString(), AdminPortalHandler.ADMIN_ROOT, host, adminPort); builder.append(interpolateHtmlTableRowTemplate("NEW STUB DATA POST URI", endpointRegistration)); return String.format(templateHtmlTable, "jetty parameters", builder.toString()); @@ -193,10 +240,13 @@ private String buildStubbyParametersHtmlTable(final String templateHtmlTable) th builder.append(interpolateHtmlTableRowTemplate("VERSION", JarUtils.readManifestImplementationVersion())); builder.append(interpolateHtmlTableRowTemplate("RUNTIME CLASSPATH", RUNTIME_MX_BEAN.getClassPath())); builder.append(interpolateHtmlTableRowTemplate("LOCAL BUILT DATE", JarUtils.readManifestBuiltDate())); - builder.append(interpolateHtmlTableRowTemplate("UPTIME", HandlerUtils.calculateStubbyUpTime(RUNTIME_MX_BEAN.getUptime()))); + builder.append(interpolateHtmlTableRowTemplate( + "UPTIME", HandlerUtils.calculateStubbyUpTime(RUNTIME_MX_BEAN.getUptime()))); builder.append(interpolateHtmlTableRowTemplate("INPUT ARGS", CommandLineInterpreter.PROVIDED_OPTIONS)); - builder.append(interpolateHtmlTableRowTemplate("STUBBED ENDPOINTS", stubRepository.getStubs().size())); - builder.append(interpolateHtmlTableRowTemplate("LOADED YAML", buildLoadedFileMetadata(stubRepository.getYamlConfig()))); + builder.append(interpolateHtmlTableRowTemplate( + "STUBBED ENDPOINTS", stubRepository.getStubs().size())); + builder.append(interpolateHtmlTableRowTemplate( + "LOADED YAML", buildLoadedFileMetadata(stubRepository.getYamlConfig()))); if (!stubRepository.getExternalFiles().isEmpty()) { final StringBuilder externalFilesMetadata = new StringBuilder(); @@ -224,19 +274,34 @@ private String buildEndpointStatsHtmlTable(final String templateHtmlTable) throw private String buildLoadedFileMetadata(final File file) throws IOException { final StringBuilder builder = new StringBuilder(); - builder.append(String.format(TEMPLATE_LOADED_FILE_METADATA_PAIR, "parentDir", determineParentDir(file))).append(HTML_BR); - builder.append(String.format(TEMPLATE_LOADED_FILE_METADATA_PAIR, "name", file.getName())).append(HTML_BR); - builder.append(String.format(TEMPLATE_LOADED_FILE_METADATA_PAIR, "size", String.format("%1$,.2f", ((double) file.length() / 1024)) + "kb")).append(HTML_BR); - builder.append(String.format(TEMPLATE_LOADED_FILE_METADATA_PAIR, "lastModified", DateTimeUtils.systemDefault(file.lastModified()))).append(HTML_BR); - - return "
" + builder.toString() + "
"; + builder.append(String.format(TEMPLATE_LOADED_FILE_METADATA_PAIR, "parentDir", determineParentDir(file))) + .append(HTML_BR); + builder.append(String.format(TEMPLATE_LOADED_FILE_METADATA_PAIR, "name", file.getName())) + .append(HTML_BR); + builder.append(String.format( + TEMPLATE_LOADED_FILE_METADATA_PAIR, + "size", + String.format("%1$,.2f", ((double) file.length() / 1024)) + "kb")) + .append(HTML_BR); + builder.append(String.format( + TEMPLATE_LOADED_FILE_METADATA_PAIR, + "lastModified", + DateTimeUtils.systemDefault(file.lastModified()))) + .append(HTML_BR); + + return "
" + builder.toString() + + "
"; } private String determineParentDir(final File file) throws IOException { - return (ObjectUtils.isNull(file.getParentFile()) ? file.getCanonicalPath().replaceAll(file.getName(), "") : file.getParentFile().getCanonicalPath() + "/"); + return (ObjectUtils.isNull(file.getParentFile()) + ? file.getCanonicalPath().replaceAll(file.getName(), "") + : file.getParentFile().getCanonicalPath() + "/"); } - private StringBuilder buildStubHtmlTableBody(final String resourceId, final String stubTypeName, final Map stubObjectProperties) throws Exception { + private StringBuilder buildStubHtmlTableBody( + final String resourceId, final String stubTypeName, final Map stubObjectProperties) + throws Exception { final StringBuilder builder = new StringBuilder(); for (final Map.Entry keyValue : stubObjectProperties.entrySet()) { @@ -252,21 +317,29 @@ private StringBuilder buildStubHtmlTableBody(final String resourceId, final Stri return builder; } - private String buildHtmlTableSingleRow(final String resourceId, final String stubTypeName, final String fieldName, final String value) { + private String buildHtmlTableSingleRow( + final String resourceId, final String stubTypeName, final String fieldName, final String value) { - if (!ConfigurableYAMLProperty.isUnknownProperty(fieldName) && FIELDS_FOR_AJAX_LINKS.contains(ConfigurableYAMLProperty.valueOf(toUpper(fieldName)))) { - final String cleansedStubTypeName = stubTypeName.replaceAll(NEXT_IN_THE_QUEUE, ""); //Only when there are sequenced responses - final String ajaxHyperlink = String.format(TEMPLATE_AJAX_TO_RESOURCE_HYPERLINK, resourceId, cleansedStubTypeName, fieldName); + if (!ConfigurableYAMLProperty.isUnknownProperty(fieldName) + && FIELDS_FOR_AJAX_LINKS.contains(ConfigurableYAMLProperty.valueOf(toUpper(fieldName)))) { + final String cleansedStubTypeName = + stubTypeName.replaceAll(NEXT_IN_THE_QUEUE, ""); // Only when there are sequenced responses + final String ajaxHyperlink = + String.format(TEMPLATE_AJAX_TO_RESOURCE_HYPERLINK, resourceId, cleansedStubTypeName, fieldName); return interpolateHtmlTableRowTemplate(StringUtils.toUpper(fieldName), ajaxHyperlink); } final String escapedValue = StringUtils.escapeHtmlEntities(value); if (fieldName.equals(ConfigurableYAMLProperty.URL.toString())) { - final String urlAsHyperlink = HandlerUtils.linkifyRequestUrl(HttpScheme.HTTP.asString(), escapedValue, jettyContext.getHost(), jettyContext.getStubsPort()); - final String tlsUrlAsHyperlink = HandlerUtils.linkifyRequestUrl(HttpScheme.HTTPS.asString(), escapedValue, jettyContext.getHost(), jettyContext.getStubsTlsPort()); - - final String tableRowWithUrl = interpolateHtmlTableRowTemplate(StringUtils.toUpper(fieldName), urlAsHyperlink); - final String tableRowWithTlsUrl = interpolateHtmlTableRowTemplate("TLS " + StringUtils.toUpper(fieldName), tlsUrlAsHyperlink); + final String urlAsHyperlink = HandlerUtils.linkifyRequestUrl( + HttpScheme.HTTP.asString(), escapedValue, jettyContext.getHost(), jettyContext.getStubsPort()); + final String tlsUrlAsHyperlink = HandlerUtils.linkifyRequestUrl( + HttpScheme.HTTPS.asString(), escapedValue, jettyContext.getHost(), jettyContext.getStubsTlsPort()); + + final String tableRowWithUrl = + interpolateHtmlTableRowTemplate(StringUtils.toUpper(fieldName), urlAsHyperlink); + final String tableRowWithTlsUrl = + interpolateHtmlTableRowTemplate("TLS " + StringUtils.toUpper(fieldName), tlsUrlAsHyperlink); return String.format("%s%s", tableRowWithUrl, tableRowWithTlsUrl); } diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/StubDataRefreshActionHandler.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/StubDataRefreshActionHandler.java index 635637343..0fc83580d 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/StubDataRefreshActionHandler.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/StubDataRefreshActionHandler.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers; import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; @@ -7,6 +23,10 @@ import io.github.azagniotov.stubby4j.utils.DateTimeUtils; import io.github.azagniotov.stubby4j.utils.HandlerUtils; import io.github.azagniotov.stubby4j.yaml.YamlParser; +import java.io.IOException; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.Request; @@ -14,11 +34,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - @SuppressWarnings("serial") @GeneratedCodeClassCoverageExclusion public final class StubDataRefreshActionHandler extends AbstractHandler implements AbstractHandlerExtension { @@ -31,7 +46,12 @@ public StubDataRefreshActionHandler(final StubRepository newStubRepository) { } @Override - public void handle(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { + public void handle( + final String target, + final Request baseRequest, + final HttpServletRequest request, + final HttpServletResponse response) + throws IOException, ServletException { if (logAndCheckIsHandled("stubData", baseRequest, request, response)) { return; } @@ -42,7 +62,9 @@ public void handle(final String target, final Request baseRequest, final HttpSer try { stubRepository.refreshStubsFromYamlConfig(new YamlParser()); - final String successMessage = String.format("Successfully performed live refresh of main YAML from: %s on [" + DateTimeUtils.systemDefault() + "]", + final String successMessage = String.format( + "Successfully performed live refresh of main YAML from: %s on [" + DateTimeUtils.systemDefault() + + "]", stubRepository.getYamlConfig()); response.getWriter().println(successMessage); ANSITerminal.ok(successMessage); @@ -53,4 +75,4 @@ public void handle(final String target, final Request baseRequest, final HttpSer ConsoleUtils.logOutgoingResponse(request.getRequestURI(), response); } -} \ No newline at end of file +} diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/StubsPortalHandler.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/StubsPortalHandler.java index 7d603b1bf..8a63a9d85 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/StubsPortalHandler.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/StubsPortalHandler.java @@ -1,20 +1,35 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers; +import static io.github.azagniotov.stubby4j.handlers.strategy.stubs.StubsResponseHandlingStrategyFactory.getStrategy; + import io.github.azagniotov.stubby4j.handlers.strategy.stubs.StubResponseHandlingStrategy; import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.stubs.StubSearchResult; import io.github.azagniotov.stubby4j.utils.ConsoleUtils; import io.github.azagniotov.stubby4j.utils.HandlerUtils; -import org.eclipse.jetty.http.HttpStatus; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.handler.AbstractHandler; - +import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -import static io.github.azagniotov.stubby4j.handlers.strategy.stubs.StubsResponseHandlingStrategyFactory.getStrategy; +import org.eclipse.jetty.http.HttpStatus; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.handler.AbstractHandler; public class StubsPortalHandler extends AbstractHandler implements AbstractHandlerExtension { @@ -25,10 +40,12 @@ public StubsPortalHandler(final StubRepository stubRepository) { } @Override - public void handle(final String target, - final Request baseRequest, - final HttpServletRequest request, - final HttpServletResponse response) throws IOException, ServletException { + public void handle( + final String target, + final Request baseRequest, + final HttpServletRequest request, + final HttpServletResponse response) + throws IOException, ServletException { if (logAndCheckIsHandled("stubs", baseRequest, request, response)) { return; } diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/AdminResponseHandlingStrategy.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/AdminResponseHandlingStrategy.java index 58fb4e73e..26be0027e 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/AdminResponseHandlingStrategy.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/AdminResponseHandlingStrategy.java @@ -1,29 +1,46 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy.admin; +import static io.github.azagniotov.stubby4j.utils.StringUtils.getBytesUtf8; + import io.github.azagniotov.stubby4j.handlers.AdminPortalHandler; import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.utils.HandlerUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; -import org.eclipse.jetty.http.HttpStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.Optional; import java.util.regex.Pattern; - -import static io.github.azagniotov.stubby4j.utils.StringUtils.getBytesUtf8; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.eclipse.jetty.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public interface AdminResponseHandlingStrategy { Logger LOGGER = LoggerFactory.getLogger(AdminResponseHandlingStrategy.class); Pattern REGEX_PROXY_CONFIG = Pattern.compile("^(proxy-config)$"); - void handle(final HttpServletRequest request, final HttpServletResponse response, final StubRepository stubRepository) throws Exception; + void handle( + final HttpServletRequest request, final HttpServletResponse response, final StubRepository stubRepository) + throws Exception; default void writeResponseOutputStream(final HttpServletResponse response, final String payload) { response.setContentType("text/plain;charset=UTF-8"); @@ -47,10 +64,12 @@ default String[] splitRequestURI(final HttpServletRequest request) { .toArray(String[]::new); } - default Optional extractRequestBodyWithOptionalError(final HttpServletRequest request, final HttpServletResponse response) throws IOException { + default Optional extractRequestBodyWithOptionalError( + final HttpServletRequest request, final HttpServletResponse response) throws IOException { final String payload = HandlerUtils.extractPostRequestBody(request, AdminPortalHandler.NAME); if (!StringUtils.isSet(payload)) { - final String errorMessage = String.format("%s request on URI %s was empty", request.getMethod(), request.getRequestURI()); + final String errorMessage = + String.format("%s request on URI %s was empty", request.getMethod(), request.getRequestURI()); HandlerUtils.configureErrorResponse(response, HttpStatus.BAD_REQUEST_400, errorMessage); return Optional.empty(); } diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/AdminResponseHandlingStrategyFactory.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/AdminResponseHandlingStrategyFactory.java index af3ea3f46..87bc0484b 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/AdminResponseHandlingStrategyFactory.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/AdminResponseHandlingStrategyFactory.java @@ -1,12 +1,26 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy.admin; import javax.servlet.http.HttpServletRequest; public final class AdminResponseHandlingStrategyFactory { - private AdminResponseHandlingStrategyFactory() { - - } + private AdminResponseHandlingStrategyFactory() {} public static AdminResponseHandlingStrategy getStrategy(final HttpServletRequest request) { diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/DeleteHandlingStrategy.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/DeleteHandlingStrategy.java index 26d113a29..d71f28f14 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/DeleteHandlingStrategy.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/DeleteHandlingStrategy.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy.admin; import io.github.azagniotov.stubby4j.handlers.AdminPortalHandler; @@ -5,16 +21,17 @@ import io.github.azagniotov.stubby4j.stubs.proxy.StubProxyConfig; import io.github.azagniotov.stubby4j.utils.HandlerUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; -import org.eclipse.jetty.http.HttpStatus; - +import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; +import org.eclipse.jetty.http.HttpStatus; public class DeleteHandlingStrategy implements AdminResponseHandlingStrategy { @Override - public void handle(final HttpServletRequest request, final HttpServletResponse response, final StubRepository stubRepository) throws IOException { + public void handle( + final HttpServletRequest request, final HttpServletResponse response, final StubRepository stubRepository) + throws IOException { if (request.getRequestURI().equals(AdminPortalHandler.ADMIN_ROOT)) { stubRepository.clear(); @@ -31,25 +48,30 @@ public void handle(final HttpServletRequest request, final HttpServletResponse r final int stubIndexToDelete = Integer.parseInt(lastUriPathSegment); if (!stubRepository.canMatchStubByIndex(stubIndexToDelete)) { - final String errorMessage = String.format("Stub request index#%s does not exist, cannot delete", stubIndexToDelete); + final String errorMessage = + String.format("Stub request index#%s does not exist, cannot delete", stubIndexToDelete); HandlerUtils.configureErrorResponse(response, HttpStatus.BAD_REQUEST_400, errorMessage); return; } stubRepository.deleteStubByIndex(stubIndexToDelete); response.setStatus(HttpStatus.OK_200); - response.getWriter().println(String.format("Stub request index#%s deleted successfully", stubIndexToDelete)); + response.getWriter() + .println(String.format("Stub request index#%s deleted successfully", stubIndexToDelete)); } else { - // We attempt to delete a stub by uuid as a fallback, e.g.: DELETE localhost:8889/9136d8b7-f7a7-478d-97a5-53292484aaf6 + // We attempt to delete a stub by uuid as a fallback, e.g.: DELETE + // localhost:8889/9136d8b7-f7a7-478d-97a5-53292484aaf6 if (!stubRepository.canMatchStubByUuid(lastUriPathSegment)) { - final String errorMessage = String.format("Stub request uuid#%s does not exist, cannot delete", lastUriPathSegment); + final String errorMessage = + String.format("Stub request uuid#%s does not exist, cannot delete", lastUriPathSegment); HandlerUtils.configureErrorResponse(response, HttpStatus.BAD_REQUEST_400, errorMessage); return; } stubRepository.deleteStubByUuid(lastUriPathSegment); response.setStatus(HttpStatus.OK_200); - response.getWriter().println(String.format("Stub request uuid#%s deleted successfully", lastUriPathSegment)); + response.getWriter() + .println(String.format("Stub request uuid#%s deleted successfully", lastUriPathSegment)); } } else if (uriFragments.length == 2) { // e.g.: http://localhost:8889/proxy-config/ @@ -58,21 +80,25 @@ public void handle(final HttpServletRequest request, final HttpServletResponse r if (REGEX_PROXY_CONFIG.matcher(maybeProxyConfig).matches()) { final String proxyConfigUuid = uriFragments[uriFragments.length - 1]; - // We attempt to delete a proxy config by uuid, e.g.: DELETE localhost:8889/proxy-config/9136d8b7-f7a7-478d-97a5-53292484aaf6 + // We attempt to delete a proxy config by uuid, e.g.: DELETE + // localhost:8889/proxy-config/9136d8b7-f7a7-478d-97a5-53292484aaf6 if (!stubRepository.canMatchProxyConfigByUuid(proxyConfigUuid)) { - final String errorMessage = String.format("Proxy config uuid#%s does not exist, cannot delete", proxyConfigUuid); + final String errorMessage = + String.format("Proxy config uuid#%s does not exist, cannot delete", proxyConfigUuid); HandlerUtils.configureErrorResponse(response, HttpStatus.BAD_REQUEST_400, errorMessage); return; } if (proxyConfigUuid.equals(StubProxyConfig.Builder.DEFAULT_UUID)) { - HandlerUtils.configureErrorResponse(response, HttpStatus.BAD_REQUEST_400, "Proxy config cannot be deleted"); + HandlerUtils.configureErrorResponse( + response, HttpStatus.BAD_REQUEST_400, "Proxy config cannot be deleted"); return; } stubRepository.deleteProxyConfigByUuid(proxyConfigUuid); response.setStatus(HttpStatus.OK_200); - response.getWriter().println(String.format("Proxy config uuid#%s deleted successfully", proxyConfigUuid)); + response.getWriter() + .println(String.format("Proxy config uuid#%s deleted successfully", proxyConfigUuid)); } else { final String errorMessage = String.format("Invalid URI path requested: %s", maybeProxyConfig); HandlerUtils.configureErrorResponse(response, HttpStatus.BAD_REQUEST_400, errorMessage); diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/GetHandlingStrategy.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/GetHandlingStrategy.java index d4244eecc..8bc934d9d 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/GetHandlingStrategy.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/GetHandlingStrategy.java @@ -1,19 +1,36 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy.admin; import io.github.azagniotov.stubby4j.handlers.AdminPortalHandler; import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.utils.HandlerUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; -import org.eclipse.jetty.http.HttpStatus; - +import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; +import org.eclipse.jetty.http.HttpStatus; public class GetHandlingStrategy implements AdminResponseHandlingStrategy { @Override - public void handle(final HttpServletRequest request, final HttpServletResponse response, final StubRepository stubRepository) throws IOException { + public void handle( + final HttpServletRequest request, final HttpServletResponse response, final StubRepository stubRepository) + throws IOException { final StringBuilder yamlAppender = new StringBuilder(); @@ -32,16 +49,19 @@ public void handle(final HttpServletRequest request, final HttpServletResponse r final int targetHttpStubCycleIndex = Integer.parseInt(lastUriPathSegment); if (!stubRepository.canMatchStubByIndex(targetHttpStubCycleIndex)) { - final String errorMessage = String.format("Stub request index#%s does not exist, cannot display", targetHttpStubCycleIndex); + final String errorMessage = String.format( + "Stub request index#%s does not exist, cannot display", targetHttpStubCycleIndex); HandlerUtils.configureErrorResponse(response, HttpStatus.BAD_REQUEST_400, errorMessage); return; } yamlAppender.append(stubRepository.getStubYamlByIndex(targetHttpStubCycleIndex)); } else { - // We attempt to get a stub by uuid as a fallback, e.g.: GET localhost:8889/9136d8b7-f7a7-478d-97a5-53292484aaf6 + // We attempt to get a stub by uuid as a fallback, e.g.: GET + // localhost:8889/9136d8b7-f7a7-478d-97a5-53292484aaf6 if (!stubRepository.canMatchStubByUuid(lastUriPathSegment)) { - final String errorMessage = String.format("Stub request uuid#%s does not exist, cannot display", lastUriPathSegment); + final String errorMessage = + String.format("Stub request uuid#%s does not exist, cannot display", lastUriPathSegment); HandlerUtils.configureErrorResponse(response, HttpStatus.BAD_REQUEST_400, errorMessage); return; } @@ -57,9 +77,11 @@ public void handle(final HttpServletRequest request, final HttpServletResponse r if (REGEX_PROXY_CONFIG.matcher(maybeProxyConfig).matches()) { final String proxyConfigUuid = uriFragments[uriFragments.length - 1]; - // We attempt to get a proxy config by uuid, e.g.: GET localhost:8889/proxy-config/9136d8b7-f7a7-478d-97a5-53292484aaf6 + // We attempt to get a proxy config by uuid, e.g.: GET + // localhost:8889/proxy-config/9136d8b7-f7a7-478d-97a5-53292484aaf6 if (!stubRepository.canMatchProxyConfigByUuid(proxyConfigUuid)) { - final String errorMessage = String.format("Proxy config uuid#%s does not exist, cannot display", proxyConfigUuid); + final String errorMessage = + String.format("Proxy config uuid#%s does not exist, cannot display", proxyConfigUuid); HandlerUtils.configureErrorResponse(response, HttpStatus.BAD_REQUEST_400, errorMessage); return; } diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/HttpVerbsEnum.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/HttpVerbsEnum.java index 9c4f162a8..56ccf65e4 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/HttpVerbsEnum.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/HttpVerbsEnum.java @@ -1,7 +1,22 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy.admin; public enum HttpVerbsEnum { - GET, PUT, POST, diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/NullHandlingStrategy.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/NullHandlingStrategy.java index 7c19b3b63..a2cced505 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/NullHandlingStrategy.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/NullHandlingStrategy.java @@ -1,18 +1,36 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy.admin; import io.github.azagniotov.stubby4j.stubs.StubRepository; -import org.eclipse.jetty.http.HttpStatus; - +import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; +import org.eclipse.jetty.http.HttpStatus; public class NullHandlingStrategy implements AdminResponseHandlingStrategy { @Override - public void handle(final HttpServletRequest request, final HttpServletResponse response, final StubRepository stubRepository) throws IOException { + public void handle( + final HttpServletRequest request, final HttpServletResponse response, final StubRepository stubRepository) + throws IOException { response.setStatus(HttpStatus.NOT_IMPLEMENTED_501); - response.getWriter().println(String.format("Method %s is not implemented on URI %s", request.getMethod(), request.getRequestURI())); - + response.getWriter() + .println(String.format( + "Method %s is not implemented on URI %s", request.getMethod(), request.getRequestURI())); } } diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/PostHandlingStrategy.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/PostHandlingStrategy.java index 6ed848713..c5de0c70d 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/PostHandlingStrategy.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/PostHandlingStrategy.java @@ -1,23 +1,40 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy.admin; import io.github.azagniotov.stubby4j.handlers.AdminPortalHandler; import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.utils.HandlerUtils; import io.github.azagniotov.stubby4j.yaml.YamlParser; -import org.eclipse.jetty.http.HttpHeader; -import org.eclipse.jetty.http.HttpStatus; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Optional; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.eclipse.jetty.http.HttpHeader; +import org.eclipse.jetty.http.HttpStatus; public class PostHandlingStrategy implements AdminResponseHandlingStrategy { private static final int NUM_OF_STUBS_THRESHOLD = 1; @Override - public void handle(final HttpServletRequest request, final HttpServletResponse response, final StubRepository stubRepository) throws Exception { + public void handle( + final HttpServletRequest request, final HttpServletResponse response, final StubRepository stubRepository) + throws Exception { if (!request.getRequestURI().equals(AdminPortalHandler.ADMIN_ROOT)) { response.setStatus(HttpStatus.METHOD_NOT_ALLOWED_405); diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/PutHandlingStrategy.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/PutHandlingStrategy.java index 918b0138e..a2b60adbe 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/PutHandlingStrategy.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/admin/PutHandlingStrategy.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy.admin; import io.github.azagniotov.stubby4j.handlers.AdminPortalHandler; @@ -5,16 +21,17 @@ import io.github.azagniotov.stubby4j.utils.HandlerUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; import io.github.azagniotov.stubby4j.yaml.YamlParser; -import org.eclipse.jetty.http.HttpHeader; -import org.eclipse.jetty.http.HttpStatus; - +import java.util.Optional; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.util.Optional; +import org.eclipse.jetty.http.HttpHeader; +import org.eclipse.jetty.http.HttpStatus; public class PutHandlingStrategy implements AdminResponseHandlingStrategy { @Override - public void handle(final HttpServletRequest request, final HttpServletResponse response, final StubRepository stubRepository) throws Exception { + public void handle( + final HttpServletRequest request, final HttpServletResponse response, final StubRepository stubRepository) + throws Exception { if (request.getRequestURI().equals(AdminPortalHandler.ADMIN_ROOT)) { response.setStatus(HttpStatus.METHOD_NOT_ALLOWED_405); @@ -30,33 +47,40 @@ public void handle(final HttpServletRequest request, final HttpServletResponse r final int stubIndexToUpdate = Integer.parseInt(lastUriPathSegment); if (!stubRepository.canMatchStubByIndex(stubIndexToUpdate)) { - final String errorMessage = String.format("Stub request index#%s does not exist, cannot update", stubIndexToUpdate); + final String errorMessage = + String.format("Stub request index#%s does not exist, cannot update", stubIndexToUpdate); HandlerUtils.configureErrorResponse(response, HttpStatus.BAD_REQUEST_400, errorMessage); return; } final Optional payloadOptional = extractRequestBodyWithOptionalError(request, response); if (payloadOptional.isPresent()) { - final String updatedCycleUrl = stubRepository.refreshStubByIndex(new YamlParser(), payloadOptional.get(), stubIndexToUpdate); + final String updatedCycleUrl = stubRepository.refreshStubByIndex( + new YamlParser(), payloadOptional.get(), stubIndexToUpdate); response.setStatus(HttpStatus.CREATED_201); response.addHeader(HttpHeader.LOCATION.asString(), updatedCycleUrl); - final String successfulMessage = String.format("Stub request index#%s updated successfully", stubIndexToUpdate); + final String successfulMessage = + String.format("Stub request index#%s updated successfully", stubIndexToUpdate); response.getWriter().println(successfulMessage); } } else { - // We attempt to update a stub by uuid as a fallback, e.g.: UPDATE localhost:8889/9136d8b7-f7a7-478d-97a5-53292484aaf6 + // We attempt to update a stub by uuid as a fallback, e.g.: UPDATE + // localhost:8889/9136d8b7-f7a7-478d-97a5-53292484aaf6 if (!stubRepository.canMatchStubByUuid(lastUriPathSegment)) { - final String errorMessage = String.format("Stub request uuid#%s does not exist, cannot update", lastUriPathSegment); + final String errorMessage = + String.format("Stub request uuid#%s does not exist, cannot update", lastUriPathSegment); HandlerUtils.configureErrorResponse(response, HttpStatus.BAD_REQUEST_400, errorMessage); return; } final Optional payloadOptional = extractRequestBodyWithOptionalError(request, response); if (payloadOptional.isPresent()) { - final String updatedCycleUrl = stubRepository.refreshStubByUuid(new YamlParser(), payloadOptional.get(), lastUriPathSegment); + final String updatedCycleUrl = stubRepository.refreshStubByUuid( + new YamlParser(), payloadOptional.get(), lastUriPathSegment); response.setStatus(HttpStatus.CREATED_201); response.addHeader(HttpHeader.LOCATION.asString(), updatedCycleUrl); - final String successfulMessage = String.format("Stub request uuid#%s updated successfully", lastUriPathSegment); + final String successfulMessage = + String.format("Stub request uuid#%s updated successfully", lastUriPathSegment); response.getWriter().println(successfulMessage); } } @@ -67,19 +91,23 @@ public void handle(final HttpServletRequest request, final HttpServletResponse r if (REGEX_PROXY_CONFIG.matcher(maybeProxyConfig).matches()) { final String proxyConfigUuid = uriFragments[uriFragments.length - 1]; - // We attempt to update a proxy config by uuid, e.g.: PUT localhost:8889/proxy-config/9136d8b7-f7a7-478d-97a5-53292484aaf6 + // We attempt to update a proxy config by uuid, e.g.: PUT + // localhost:8889/proxy-config/9136d8b7-f7a7-478d-97a5-53292484aaf6 if (!stubRepository.canMatchProxyConfigByUuid(proxyConfigUuid)) { - final String errorMessage = String.format("Proxy config uuid#%s does not exist, cannot update", proxyConfigUuid); + final String errorMessage = + String.format("Proxy config uuid#%s does not exist, cannot update", proxyConfigUuid); HandlerUtils.configureErrorResponse(response, HttpStatus.BAD_REQUEST_400, errorMessage); return; } final Optional payloadOptional = extractRequestBodyWithOptionalError(request, response); if (payloadOptional.isPresent()) { - final String proxyEndpointUrl = stubRepository.refreshProxyConfigByUuid(new YamlParser(), payloadOptional.get(), proxyConfigUuid); + final String proxyEndpointUrl = stubRepository.refreshProxyConfigByUuid( + new YamlParser(), payloadOptional.get(), proxyConfigUuid); response.setStatus(HttpStatus.CREATED_201); response.addHeader(HttpHeader.LOCATION.asString(), proxyEndpointUrl); - final String successfulMessage = String.format("Proxy config uuid#%s updated successfully", proxyConfigUuid); + final String successfulMessage = + String.format("Proxy config uuid#%s updated successfully", proxyConfigUuid); response.getWriter().println(successfulMessage); } diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/DefaultResponseHandlingStrategy.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/DefaultResponseHandlingStrategy.java index 21eeb29cb..1b65af43b 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/DefaultResponseHandlingStrategy.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/DefaultResponseHandlingStrategy.java @@ -1,23 +1,38 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy.stubs; +import static io.github.azagniotov.stubby4j.utils.FileUtils.fileToBytes; +import static io.github.azagniotov.stubby4j.utils.HandlerUtils.setResponseMainHeaders; +import static io.github.azagniotov.stubby4j.utils.StringUtils.getBytesUtf8; +import static io.github.azagniotov.stubby4j.utils.StringUtils.isTokenized; +import static io.github.azagniotov.stubby4j.utils.StringUtils.replaceTokens; +import static io.github.azagniotov.stubby4j.utils.StringUtils.replaceTokensInString; + import io.github.azagniotov.stubby4j.stubs.StubRequest; import io.github.azagniotov.stubby4j.stubs.StubResponse; import io.github.azagniotov.stubby4j.utils.StringUtils; -import org.eclipse.jetty.http.HttpStatus; - -import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.Map; import java.util.concurrent.TimeUnit; - -import static io.github.azagniotov.stubby4j.utils.FileUtils.fileToBytes; -import static io.github.azagniotov.stubby4j.utils.HandlerUtils.setResponseMainHeaders; -import static io.github.azagniotov.stubby4j.utils.StringUtils.getBytesUtf8; -import static io.github.azagniotov.stubby4j.utils.StringUtils.isTokenized; -import static io.github.azagniotov.stubby4j.utils.StringUtils.replaceTokens; -import static io.github.azagniotov.stubby4j.utils.StringUtils.replaceTokensInString; +import javax.servlet.http.HttpServletResponse; +import org.eclipse.jetty.http.HttpStatus; public final class DefaultResponseHandlingStrategy implements StubResponseHandlingStrategy { @@ -56,8 +71,12 @@ public void handle(final HttpServletResponse response, final StubRequest asserti } } - private void setResponseStubbedHeaders(final HttpServletResponse response, final StubResponse stubResponse, final Map regexGroups) { - for (final Map.Entry headerPair : stubResponse.getHeaders().entrySet()) { + private void setResponseStubbedHeaders( + final HttpServletResponse response, + final StubResponse stubResponse, + final Map regexGroups) { + for (final Map.Entry headerPair : + stubResponse.getHeaders().entrySet()) { String responseHeaderValue = headerPair.getValue(); if (isTokenized(responseHeaderValue)) { responseHeaderValue = replaceTokensInString(headerPair.getValue(), regexGroups); diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/NotFoundResponseHandlingStrategy.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/NotFoundResponseHandlingStrategy.java index d3a8f81e5..fbe32c96c 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/NotFoundResponseHandlingStrategy.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/NotFoundResponseHandlingStrategy.java @@ -1,24 +1,39 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy.stubs; import io.github.azagniotov.stubby4j.stubs.StubRequest; import io.github.azagniotov.stubby4j.utils.HandlerUtils; +import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpStatus; import org.json.JSONObject; -import javax.servlet.http.HttpServletResponse; - public final class NotFoundResponseHandlingStrategy implements StubResponseHandlingStrategy { - NotFoundResponseHandlingStrategy() { - - } + NotFoundResponseHandlingStrategy() {} @Override public void handle(final HttpServletResponse response, final StubRequest assertionStubRequest) throws Exception { HandlerUtils.setResponseMainHeaders(response); - final String reason = String.format("(404) Nothing found for %s request at URI %s", assertionStubRequest.getMethod().get(0), assertionStubRequest.getUrl()); + final String reason = String.format( + "(404) Nothing found for %s request at URI %s", + assertionStubRequest.getMethod().get(0), assertionStubRequest.getUrl()); final JSONObject json404Response = new JSONObject(); json404Response.put("reason", reason); diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/RedirectResponseHandlingStrategy.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/RedirectResponseHandlingStrategy.java index ca0263a18..d18b8dca8 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/RedirectResponseHandlingStrategy.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/RedirectResponseHandlingStrategy.java @@ -1,17 +1,32 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy.stubs; +import static io.github.azagniotov.stubby4j.utils.StringUtils.isTokenized; +import static io.github.azagniotov.stubby4j.utils.StringUtils.replaceTokensInString; + import io.github.azagniotov.stubby4j.stubs.StubRequest; import io.github.azagniotov.stubby4j.stubs.StubResponse; import io.github.azagniotov.stubby4j.utils.HandlerUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; -import org.eclipse.jetty.http.HttpHeader; - -import javax.servlet.http.HttpServletResponse; import java.util.Map; import java.util.concurrent.TimeUnit; - -import static io.github.azagniotov.stubby4j.utils.StringUtils.isTokenized; -import static io.github.azagniotov.stubby4j.utils.StringUtils.replaceTokensInString; +import javax.servlet.http.HttpServletResponse; +import org.eclipse.jetty.http.HttpHeader; public class RedirectResponseHandlingStrategy implements StubResponseHandlingStrategy { diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/StubResponseHandlingStrategy.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/StubResponseHandlingStrategy.java index 225ac7b06..90f31ec80 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/StubResponseHandlingStrategy.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/StubResponseHandlingStrategy.java @@ -1,7 +1,22 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy.stubs; import io.github.azagniotov.stubby4j.stubs.StubRequest; - import javax.servlet.http.HttpServletResponse; public interface StubResponseHandlingStrategy { diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/StubsResponseHandlingStrategyFactory.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/StubsResponseHandlingStrategyFactory.java index f238a3ef0..3cc993375 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/StubsResponseHandlingStrategyFactory.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/StubsResponseHandlingStrategyFactory.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy.stubs; import io.github.azagniotov.stubby4j.stubs.StubResponse; @@ -5,9 +21,7 @@ public final class StubsResponseHandlingStrategyFactory { - private StubsResponseHandlingStrategyFactory() { - - } + private StubsResponseHandlingStrategyFactory() {} public static StubResponseHandlingStrategy getStrategy(final StubResponse foundStubResponse) { @@ -23,22 +37,22 @@ public static StubResponseHandlingStrategy getStrategy(final StubResponse foundS case MOVED_PERMANENTLY: /* - This is an example of industry practice contradicting the standard. - The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect - (the original describing phrase was "Moved Temporarily"), but popular browsers implemented 302 with - the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 to - distinguish between the two behaviours. However, some Web applications and frameworks use the 302 - status code as if it were the 303. - */ + This is an example of industry practice contradicting the standard. + The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect + (the original describing phrase was "Moved Temporarily"), but popular browsers implemented 302 with + the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 to + distinguish between the two behaviours. However, some Web applications and frameworks use the 302 + status code as if it were the 303. + */ case FOUND: case MOVED_TEMPORARILY: case SEE_OTHER: case TEMPORARY_REDIRECT: /* - The request and all future requests should be repeated using another URI. 307 and 308 parallel the - behaviors of 302 and 301, but do not allow the HTTP method to change. So, for example, submitting a - form to a permanently redirected resource may continue smoothly. - */ + The request and all future requests should be repeated using another URI. 307 and 308 parallel the + behaviors of 302 and 301, but do not allow the HTTP method to change. So, for example, submitting a + form to a permanently redirected resource may continue smoothly. + */ case PERMANENT_REDIRECT: return new RedirectResponseHandlingStrategy(foundStubResponse); } diff --git a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/UnauthorizedResponseHandlingStrategy.java b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/UnauthorizedResponseHandlingStrategy.java index 2da2337cf..b2867e166 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/UnauthorizedResponseHandlingStrategy.java +++ b/src/main/java/io/github/azagniotov/stubby4j/handlers/strategy/stubs/UnauthorizedResponseHandlingStrategy.java @@ -1,24 +1,39 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy.stubs; import io.github.azagniotov.stubby4j.annotations.VisibleForTesting; import io.github.azagniotov.stubby4j.stubs.StubRequest; import io.github.azagniotov.stubby4j.utils.HandlerUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; -import org.eclipse.jetty.http.HttpStatus; - import javax.servlet.http.HttpServletResponse; - +import org.eclipse.jetty.http.HttpStatus; public final class UnauthorizedResponseHandlingStrategy implements StubResponseHandlingStrategy { @VisibleForTesting - public static final String NO_AUTHORIZATION_HEADER = "You are not authorized to view this page without supplied 'Authorization' HTTP header"; - @VisibleForTesting - public static final String WRONG_AUTHORIZATION_HEADER_TEMPLATE = "Unauthorized with supplied 'authorized' header value: '%s'"; + public static final String NO_AUTHORIZATION_HEADER = + "You are not authorized to view this page without supplied 'Authorization' HTTP header"; - UnauthorizedResponseHandlingStrategy() { + @VisibleForTesting + public static final String WRONG_AUTHORIZATION_HEADER_TEMPLATE = + "Unauthorized with supplied 'authorized' header value: '%s'"; - } + UnauthorizedResponseHandlingStrategy() {} @Override public void handle(final HttpServletResponse response, final StubRequest assertionStubRequest) throws Exception { @@ -29,6 +44,9 @@ public void handle(final HttpServletResponse response, final StubRequest asserti return; } - HandlerUtils.configureErrorResponse(response, HttpStatus.UNAUTHORIZED_401, String.format(WRONG_AUTHORIZATION_HEADER_TEMPLATE, authorizationHeader)); + HandlerUtils.configureErrorResponse( + response, + HttpStatus.UNAUTHORIZED_401, + String.format(WRONG_AUTHORIZATION_HEADER_TEMPLATE, authorizationHeader)); } } diff --git a/src/main/java/io/github/azagniotov/stubby4j/http/HttpMethodExtended.java b/src/main/java/io/github/azagniotov/stubby4j/http/HttpMethodExtended.java index e8d289c52..1866425b6 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/http/HttpMethodExtended.java +++ b/src/main/java/io/github/azagniotov/stubby4j/http/HttpMethodExtended.java @@ -1,12 +1,25 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.http; public enum HttpMethodExtended { - PATCH; - HttpMethodExtended() { - - } + HttpMethodExtended() {} public String asString() { return toString(); diff --git a/src/main/java/io/github/azagniotov/stubby4j/http/StubbyHttpTransport.java b/src/main/java/io/github/azagniotov/stubby4j/http/StubbyHttpTransport.java index 2b229c108..022522152 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/http/StubbyHttpTransport.java +++ b/src/main/java/io/github/azagniotov/stubby4j/http/StubbyHttpTransport.java @@ -1,17 +1,37 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.http; +import static io.github.azagniotov.stubby4j.common.Common.POSTING_METHODS; +import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.SSL_SOCKET_FACTORY; +import static io.github.azagniotov.stubby4j.utils.StringUtils.charsetUTF8; +import static io.github.azagniotov.stubby4j.utils.StringUtils.inputStreamToString; +import static java.lang.String.valueOf; +import static java.util.Map.Entry; +import static org.eclipse.jetty.http.HttpHeader.CONTENT_ENCODING; +import static org.eclipse.jetty.http.HttpHeader.CONTENT_LANGUAGE; +import static org.eclipse.jetty.http.HttpHeader.CONTENT_LENGTH; +import static org.eclipse.jetty.http.HttpHeader.CONTENT_TYPE; + import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.client.StubbyResponse; import io.github.azagniotov.stubby4j.stubs.StubRequest; import io.github.azagniotov.stubby4j.utils.ConsoleUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; -import org.eclipse.jetty.http.HttpMethod; -import org.eclipse.jetty.http.HttpScheme; -import org.eclipse.jetty.http.HttpStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.net.ssl.HttpsURLConnection; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; @@ -23,59 +43,60 @@ import java.util.List; import java.util.Map; import java.util.Set; - -import static io.github.azagniotov.stubby4j.common.Common.POSTING_METHODS; -import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.SSL_SOCKET_FACTORY; -import static io.github.azagniotov.stubby4j.utils.StringUtils.charsetUTF8; -import static io.github.azagniotov.stubby4j.utils.StringUtils.inputStreamToString; -import static java.lang.String.valueOf; -import static java.util.Map.Entry; -import static org.eclipse.jetty.http.HttpHeader.CONTENT_ENCODING; -import static org.eclipse.jetty.http.HttpHeader.CONTENT_LANGUAGE; -import static org.eclipse.jetty.http.HttpHeader.CONTENT_LENGTH; -import static org.eclipse.jetty.http.HttpHeader.CONTENT_TYPE; - +import javax.net.ssl.HttpsURLConnection; +import org.eclipse.jetty.http.HttpMethod; +import org.eclipse.jetty.http.HttpScheme; +import org.eclipse.jetty.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class StubbyHttpTransport { private static final Logger LOGGER = LoggerFactory.getLogger(StubbyHttpTransport.class); - private static final Set SUPPORTED_METHODS = new HashSet() {{ - add(HttpMethod.GET.asString()); - add(HttpMethod.HEAD.asString()); - add(HttpMethod.TRACE.asString()); - add(HttpMethod.OPTIONS.asString()); - add(HttpMethod.DELETE.asString()); - add(HttpMethod.POST.asString()); - add(HttpMethod.PUT.asString()); - add(HttpMethodExtended.PATCH.asString()); - }}; - - public StubbyHttpTransport() { + private static final Set SUPPORTED_METHODS = new HashSet() { + { + add(HttpMethod.GET.asString()); + add(HttpMethod.HEAD.asString()); + add(HttpMethod.TRACE.asString()); + add(HttpMethod.OPTIONS.asString()); + add(HttpMethod.DELETE.asString()); + add(HttpMethod.POST.asString()); + add(HttpMethod.PUT.asString()); + add(HttpMethodExtended.PATCH.asString()); + } + }; - } + public StubbyHttpTransport() {} - public StubbyResponse httpRequestFromStub(final StubRequest request, final String recordingSource) throws Exception { + public StubbyResponse httpRequestFromStub(final StubRequest request, final String recordingSource) + throws Exception { final String method = request.getMethod().get(0); if (!ANSITerminal.isMute()) { - final String logMessage = String.format("[%s] -> Making %s HTTP request from stub metadata to: [%s]", ConsoleUtils.getLocalDateTime(), method, recordingSource); + final String logMessage = String.format( + "[%s] -> Making %s HTTP request from stub metadata to: [%s]", + ConsoleUtils.getLocalDateTime(), method, recordingSource); ANSITerminal.incoming(logMessage); } LOGGER.debug("Making {} HTTP request from stub metadata to: [{}].", method, recordingSource); - return request(method, + return request( + method, recordingSource, request.getPostBody(), request.getHeaders(), StringUtils.calculateStringLength(request.getPostBody())); } - public StubbyResponse request(final String method, - final String fullUrl, - final String post, - final Map headers, - final int postLength) throws Exception { + public StubbyResponse request( + final String method, + final String fullUrl, + final String post, + final Map headers, + final int postLength) + throws Exception { if (!SUPPORTED_METHODS.contains(method)) { - throw new UnsupportedOperationException(String.format("HTTP method '%s' not supported when contacting stubby4j", method)); + throw new UnsupportedOperationException( + String.format("HTTP method '%s' not supported when contacting stubby4j", method)); } final HttpURLConnection connection = getHttpURLConnection(fullUrl); @@ -125,7 +146,8 @@ private StubbyResponse buildStubbyResponse(final HttpURLConnection connection) t } } - private void setRequestHeaders(final HttpURLConnection connection, final Map headers, final int postLength) { + private void setRequestHeaders( + final HttpURLConnection connection, final Map headers, final int postLength) { connection.setRequestProperty("User-Agent", StringUtils.constructUserAgentName()); final String requestMethod = connection.getRequestMethod(); if (POSTING_METHODS.contains(StringUtils.toUpper(requestMethod))) { @@ -148,8 +170,9 @@ private void setRequestHeaders(final HttpURLConnection connection, final Map - { - // Configure default max size - nativeWebSocketConfiguration.getPolicy().setMaxTextMessageBufferSize(65535); - - // Add websockets - nativeWebSocketConfiguration.addMapping("/*", new StubsWebSocketCreator(stubRepository)); - }); + NativeWebSocketServletContainerInitializer.configure( + servletContextHandler, (servletContext, nativeWebSocketConfiguration) -> { + // Configure default max size + nativeWebSocketConfiguration.getPolicy().setMaxTextMessageBufferSize(65535); + // Add websockets + nativeWebSocketConfiguration.addMapping("/*", new StubsWebSocketCreator(stubRepository)); + }); // Add generic filter that will accept WebSocket upgrade. WebSocketUpgradeFilter.configure(servletContextHandler); @@ -130,30 +146,34 @@ Server construct() throws IOException, ServletException { private ContextHandlerCollection constructHandlers() { - final JettyContext jettyContext = new JettyContext(currentHost, currentStubsPort, currentStubsSslPort, currentAdminPort); + final JettyContext jettyContext = + new JettyContext(currentHost, currentStubsPort, currentStubsSslPort, currentAdminPort); final ContextHandlerCollection handlers = new ContextHandlerCollection(); - handlers.setHandlers(new Handler[] - { - constructHandler(STUBS_CONNECTOR_NAME, "/favicon.ico", gzipHandler(new FaviconHandler())), - constructHandler(STUBS_CONNECTOR_NAME, ROOT_PATH_INFO, gzipHandler(new StubsPortalHandler(stubRepository))), - - constructHandler(SSL_CONNECTOR_NAME, "/favicon.ico", gzipHandler(new FaviconHandler())), - constructHandler(SSL_CONNECTOR_NAME, ROOT_PATH_INFO, gzipHandler(new StubsPortalHandler(stubRepository))), - - constructHandler(ADMIN_CONNECTOR_NAME, "/status", gzipHandler(new StatusPageHandler(jettyContext, stubRepository))), - constructHandler(ADMIN_CONNECTOR_NAME, "/refresh", new StubDataRefreshActionHandler(stubRepository)), - constructHandler(ADMIN_CONNECTOR_NAME, "/js/highlight", gzipHandler(staticResourceHandler("ui/js/highlight/"))), - constructHandler(ADMIN_CONNECTOR_NAME, "/js/minified", gzipHandler(staticResourceHandler("ui/js/minified/"))), - constructHandler(ADMIN_CONNECTOR_NAME, "/js/d3", gzipHandler(staticResourceHandler("ui/js/d3/"))), - constructHandler(ADMIN_CONNECTOR_NAME, "/js", gzipHandler(staticResourceHandler("ui/js/"))), - constructHandler(ADMIN_CONNECTOR_NAME, "/css", gzipHandler(staticResourceHandler("ui/css/"))), - constructHandler(ADMIN_CONNECTOR_NAME, "/images", gzipHandler(staticResourceHandler("ui/images/"))), - constructHandler(ADMIN_CONNECTOR_NAME, "/ajax/resource", gzipHandler(new AjaxResourceContentHandler(stubRepository))), - constructHandler(ADMIN_CONNECTOR_NAME, "/ajax/stats", gzipHandler(new AjaxEndpointStatsHandler(stubRepository))), - constructHandler(ADMIN_CONNECTOR_NAME, "/favicon.ico", gzipHandler(new FaviconHandler())), - constructHandler(ADMIN_CONNECTOR_NAME, ROOT_PATH_INFO, gzipHandler(new AdminPortalHandler(stubRepository))) - } - ); + handlers.setHandlers(new Handler[] { + constructHandler(STUBS_CONNECTOR_NAME, "/favicon.ico", gzipHandler(new FaviconHandler())), + constructHandler(STUBS_CONNECTOR_NAME, ROOT_PATH_INFO, gzipHandler(new StubsPortalHandler(stubRepository))), + constructHandler(SSL_CONNECTOR_NAME, "/favicon.ico", gzipHandler(new FaviconHandler())), + constructHandler(SSL_CONNECTOR_NAME, ROOT_PATH_INFO, gzipHandler(new StubsPortalHandler(stubRepository))), + constructHandler( + ADMIN_CONNECTOR_NAME, "/status", gzipHandler(new StatusPageHandler(jettyContext, stubRepository))), + constructHandler(ADMIN_CONNECTOR_NAME, "/refresh", new StubDataRefreshActionHandler(stubRepository)), + constructHandler( + ADMIN_CONNECTOR_NAME, "/js/highlight", gzipHandler(staticResourceHandler("ui/js/highlight/"))), + constructHandler( + ADMIN_CONNECTOR_NAME, "/js/minified", gzipHandler(staticResourceHandler("ui/js/minified/"))), + constructHandler(ADMIN_CONNECTOR_NAME, "/js/d3", gzipHandler(staticResourceHandler("ui/js/d3/"))), + constructHandler(ADMIN_CONNECTOR_NAME, "/js", gzipHandler(staticResourceHandler("ui/js/"))), + constructHandler(ADMIN_CONNECTOR_NAME, "/css", gzipHandler(staticResourceHandler("ui/css/"))), + constructHandler(ADMIN_CONNECTOR_NAME, "/images", gzipHandler(staticResourceHandler("ui/images/"))), + constructHandler( + ADMIN_CONNECTOR_NAME, + "/ajax/resource", + gzipHandler(new AjaxResourceContentHandler(stubRepository))), + constructHandler( + ADMIN_CONNECTOR_NAME, "/ajax/stats", gzipHandler(new AjaxEndpointStatsHandler(stubRepository))), + constructHandler(ADMIN_CONNECTOR_NAME, "/favicon.ico", gzipHandler(new FaviconHandler())), + constructHandler(ADMIN_CONNECTOR_NAME, ROOT_PATH_INFO, gzipHandler(new AdminPortalHandler(stubRepository))) + }); return handlers; } @@ -196,7 +216,7 @@ private ContextHandler constructHandler(final String connectorName, final String contextHandler.setContextPath(pathInfo); contextHandler.setAllowNullPathInfo(true); // We prefix the name with an '@' because this is the way Jetty v9 finds a named connector - contextHandler.setVirtualHosts(new String[]{"@" + connectorName}); + contextHandler.setVirtualHosts(new String[] {"@" + connectorName}); contextHandler.addLocaleEncoding(Locale.US.getDisplayName(), StringUtils.UTF_8); contextHandler.setHandler(handler); @@ -242,12 +262,12 @@ private ServerConnector buildAdminConnector(final Server server) { statusBuilder.append("Admin portal:\n"); statusBuilder.append(DASHED_STATUS_LINE); - final String configured = String.format(" > http://%s:%s\t\tAdmin portal\n", - adminChannel.getHost(), adminChannel.getPort()); + final String configured = + String.format(" > http://%s:%s\t\tAdmin portal\n", adminChannel.getHost(), adminChannel.getPort()); statusBuilder.append(configured); - final String status = String.format(" > http://%s:%s/status\t\tAdmin portal status\n", - adminChannel.getHost(), adminChannel.getPort()); + final String status = String.format( + " > http://%s:%s/status\t\tAdmin portal status\n", adminChannel.getHost(), adminChannel.getPort()); statusBuilder.append(status); statusBuilder.append("\n"); @@ -259,11 +279,12 @@ private ServerConnector buildAdminConnector(final Server server) { private ServerConnector buildStubsConnector(final Server server) { - final boolean enableAlpnAndHttp2 = commandLineArgs.containsKey(CommandLineInterpreter.OPTION_ENABLE_TLS_WITH_ALPN_AND_HTTP_2); + final boolean enableAlpnAndHttp2 = + commandLineArgs.containsKey(CommandLineInterpreter.OPTION_ENABLE_TLS_WITH_ALPN_AND_HTTP_2); final HttpConfiguration httpConfiguration = constructHttpConfiguration(); - final ServerConnector stubsChannel = enableAlpnAndHttp2 ? - buildStubsConnectorWithHttp20(server, httpConfiguration) : - buildStubsConnectorWithHttp11(server, httpConfiguration); + final ServerConnector stubsChannel = enableAlpnAndHttp2 + ? buildStubsConnectorWithHttp20(server, httpConfiguration) + : buildStubsConnectorWithHttp11(server, httpConfiguration); stubsChannel.setPort(getStubsPort(commandLineArgs)); stubsChannel.setName(STUBS_CONNECTOR_NAME); @@ -278,17 +299,19 @@ private ServerConnector buildStubsConnector(final Server server) { statusBuilder.append("Available insecure endpoints:\n"); statusBuilder.append(DASHED_STATUS_LINE); - final String statusHttp = String.format(" > http://%s:%s\t\tHTTP/1.1 stubs portal\n", - stubsChannel.getHost(), stubsChannel.getPort()); + final String statusHttp = String.format( + " > http://%s:%s\t\tHTTP/1.1 stubs portal\n", stubsChannel.getHost(), stubsChannel.getPort()); statusBuilder.append(statusHttp); if (enableAlpnAndHttp2) { - final String tlsPortalStatus = String.format(" > http://%s:%s\t\tHTTP/2 over TCP (h2c) stubs portal\n", + final String tlsPortalStatus = String.format( + " > http://%s:%s\t\tHTTP/2 over TCP (h2c) stubs portal\n", stubsChannel.getHost(), stubsChannel.getPort()); statusBuilder.append(tlsPortalStatus); } - final String statusWs = String.format(" > ws://%s:%s/ws\t\tHTTP/1.1 WebSockets stubs portal\n", + final String statusWs = String.format( + " > ws://%s:%s/ws\t\tHTTP/1.1 WebSockets stubs portal\n", stubsChannel.getHost(), stubsChannel.getPort()); statusBuilder.append(statusWs); statusBuilder.append("\n"); @@ -299,7 +322,8 @@ private ServerConnector buildStubsConnector(final Server server) { } private ServerConnector buildStubsSslConnector(final Server server) throws IOException { - final boolean enableAlpnAndHttp2 = commandLineArgs.containsKey(CommandLineInterpreter.OPTION_ENABLE_TLS_WITH_ALPN_AND_HTTP_2); + final boolean enableAlpnAndHttp2 = + commandLineArgs.containsKey(CommandLineInterpreter.OPTION_ENABLE_TLS_WITH_ALPN_AND_HTTP_2); if (enableAlpnAndHttp2) { // See SslUtils static { ... } System.setProperty("overrideDisabledAlgorithms", "false"); @@ -310,9 +334,10 @@ private ServerConnector buildStubsSslConnector(final Server server) throws IOExc final String keystorePath = commandLineArgs.getOrDefault(CommandLineInterpreter.OPTION_KEYSTORE, null); final String keystorePassword = commandLineArgs.getOrDefault(CommandLineInterpreter.OPTION_KEYPASS, null); - if ((ObjectUtils.isNull(keystorePath) && ObjectUtils.isNotNull(keystorePassword)) || - (ObjectUtils.isNotNull(keystorePath) && ObjectUtils.isNull(keystorePassword))) { - final String misConfigMsg = String.format("When provided, both flags must be set, got: %s=%s and %s=%s", + if ((ObjectUtils.isNull(keystorePath) && ObjectUtils.isNotNull(keystorePassword)) + || (ObjectUtils.isNotNull(keystorePath) && ObjectUtils.isNull(keystorePassword))) { + final String misConfigMsg = String.format( + "When provided, both flags must be set, got: %s=%s and %s=%s", CommandLineInterpreter.OPTION_KEYSTORE, keystorePath, CommandLineInterpreter.OPTION_KEYPASS, @@ -327,9 +352,9 @@ private ServerConnector buildStubsSslConnector(final Server server) throws IOExc httpConfiguration.addCustomizer(new SecureRequestCustomizer()); final SslContextFactory sslContextFactory = constructSslContextFactory(keystorePassword, keystorePath); - final ServerConnector sslConnector = enableAlpnAndHttp2 ? - buildSslConnectorWithHttp2Alpn(server, httpConfiguration, sslContextFactory) : - buildSslConnectorWithHttp11(server, httpConfiguration, sslContextFactory); + final ServerConnector sslConnector = enableAlpnAndHttp2 + ? buildSslConnectorWithHttp2Alpn(server, httpConfiguration, sslContextFactory) + : buildSslConnectorWithHttp11(server, httpConfiguration, sslContextFactory); sslConnector.setPort(getStubsSslPort(commandLineArgs)); sslConnector.setHost(DEFAULT_HOST); @@ -340,7 +365,8 @@ private ServerConnector buildStubsSslConnector(final Server server) throws IOExc sslConnector.setHost(commandLineArgs.get(CommandLineInterpreter.OPTION_ADDRESS)); } - final HashSet supportedTlsProtocols = new HashSet<>(Arrays.asList(sslContextFactory.getIncludeProtocols())); + final HashSet supportedTlsProtocols = + new HashSet<>(Arrays.asList(sslContextFactory.getIncludeProtocols())); statusBuilder.append("\n"); @@ -349,13 +375,14 @@ private ServerConnector buildStubsSslConnector(final Server server) throws IOExc final String tlsStatus = String.format(" > Supported TLS protocol versions: %s", supportedTlsProtocols); statusBuilder.append(tlsStatus).append(enableAlpnAndHttp2 ? " with ALPN extension on HTTP/2\n" : "\n"); if (!new HashSet<>(asList(SslUtils.enabledProtocols())).contains(TLS_v1_3)) { - final String noTls13Msg = String.format(" > TLSv1.3 is not supported in JDK v%s, %s\n", - System.getProperty("java.runtime.version"), - System.getProperty("java.vendor")); + final String noTls13Msg = String.format( + " > TLSv1.3 is not supported in JDK v%s, %s\n", + System.getProperty("java.runtime.version"), System.getProperty("java.vendor")); statusBuilder.append(noTls13Msg).append("\n"); } - final String keystoreStatus = " > TLS layer configured using " + (ObjectUtils.isNull(keystorePath) ? "internal self-signed certificate" : "provided " + keystorePath); + final String keystoreStatus = " > TLS layer configured using " + + (ObjectUtils.isNull(keystorePath) ? "internal self-signed certificate" : "provided " + keystorePath); statusBuilder.append(keystoreStatus).append("\n"); statusBuilder.append("\n"); @@ -363,12 +390,13 @@ private ServerConnector buildStubsSslConnector(final Server server) throws IOExc statusBuilder.append("Available secure endpoints:\n"); statusBuilder.append(DASHED_STATUS_LINE); - final String protocol = enableAlpnAndHttp2 ? "HTTP/2 over TLS (h2) stubs portal" : "HTTP/1.1 over TLS stubs portal"; - final String tlsPortalStatus = String.format(" > https://%s:%s\t\t%s\n", - sslConnector.getHost(), sslConnector.getPort(), protocol); + final String protocol = + enableAlpnAndHttp2 ? "HTTP/2 over TLS (h2) stubs portal" : "HTTP/1.1 over TLS stubs portal"; + final String tlsPortalStatus = + String.format(" > https://%s:%s\t\t%s\n", sslConnector.getHost(), sslConnector.getPort(), protocol); statusBuilder.append(tlsPortalStatus); - //TODO Move to jetty v11: https://webtide.com/jetty-10-and-11-have-arrived/ + // TODO Move to jetty v11: https://webtide.com/jetty-10-and-11-have-arrived/ // final String wssPortalStatus = String.format(" > wss://%s:%s/ws\t\t%s WebSockets on TLS stubs portal\n", // sslConnector.getHost(), sslConnector.getPort(), protocol); // statusBuilder.append(wssPortalStatus); @@ -378,7 +406,8 @@ private ServerConnector buildStubsSslConnector(final Server server) throws IOExc return sslConnector; } - private SslContextFactory constructSslContextFactory(final String keystorePassword, final String keystorePath) throws IOException { + private SslContextFactory constructSslContextFactory(final String keystorePassword, final String keystorePath) + throws IOException { // https://www.eclipse.org/jetty/documentation/jetty-9/index.html#configuring-ssl @@ -429,44 +458,44 @@ private HttpConfiguration constructHttpConfiguration() { return httpConfiguration; } - private ServerConnector buildStubsConnectorWithHttp11(final Server server, - final HttpConfiguration httpConfiguration) { - return new ServerConnector(server, - new HttpConnectionFactory(httpConfiguration)); + private ServerConnector buildStubsConnectorWithHttp11( + final Server server, final HttpConfiguration httpConfiguration) { + return new ServerConnector(server, new HttpConnectionFactory(httpConfiguration)); } - private ServerConnector buildStubsConnectorWithHttp20(final Server server, - final HttpConfiguration httpConfiguration) { + private ServerConnector buildStubsConnectorWithHttp20( + final Server server, final HttpConfiguration httpConfiguration) { // Annoying cURL notice in response: Connection state changed (MAX_CONCURRENT_STREAMS == N)! // https://github.com/curl/curl/blob/63c76681827b5ae9017f6c981003cd75e5f127de/lib/http2.h#L32 - final HTTP2CServerConnectionFactory http2CServerConnectionFactory = new HTTP2CServerConnectionFactory(httpConfiguration); + final HTTP2CServerConnectionFactory http2CServerConnectionFactory = + new HTTP2CServerConnectionFactory(httpConfiguration); http2CServerConnectionFactory.setMaxConcurrentStreams(100); - return new ServerConnector(server, - new HttpConnectionFactory(httpConfiguration), - http2CServerConnectionFactory); + return new ServerConnector(server, new HttpConnectionFactory(httpConfiguration), http2CServerConnectionFactory); } - private ServerConnector buildSslConnectorWithHttp11(final Server server, - final HttpConfiguration httpConfiguration, - final SslContextFactory sslContextFactory) { - final SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(sslContextFactory, PROTOCOL_HTTP_1_1); + private ServerConnector buildSslConnectorWithHttp11( + final Server server, final HttpConfiguration httpConfiguration, final SslContextFactory sslContextFactory) { + final SslConnectionFactory sslConnectionFactory = + new SslConnectionFactory(sslContextFactory, PROTOCOL_HTTP_1_1); return new ServerConnector(server, sslConnectionFactory, new HttpConnectionFactory(httpConfiguration)); } - private ServerConnector buildSslConnectorWithHttp2Alpn(final Server server, - final HttpConfiguration httpConfiguration, - final SslContextFactory sslContextFactory) { + private ServerConnector buildSslConnectorWithHttp2Alpn( + final Server server, final HttpConfiguration httpConfiguration, final SslContextFactory sslContextFactory) { // https://www.eclipse.org/jetty/documentation/jetty-9/index.html#alpn-chapter sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR); - final ALPNServerConnectionFactory alpnServerConnectionFactory = new ALPNServerConnectionFactory(PROTOCOL_HTTP_2); + final ALPNServerConnectionFactory alpnServerConnectionFactory = + new ALPNServerConnectionFactory(PROTOCOL_HTTP_2); - final HTTP2ServerConnectionFactory http2ServerConnectionFactory = new HTTP2ServerConnectionFactory(httpConfiguration); + final HTTP2ServerConnectionFactory http2ServerConnectionFactory = + new HTTP2ServerConnectionFactory(httpConfiguration); // Annoying cURL notice in response: Connection state changed (MAX_CONCURRENT_STREAMS == N)! // https://github.com/curl/curl/blob/63c76681827b5ae9017f6c981003cd75e5f127de/lib/http2.h#L32 http2ServerConnectionFactory.setMaxConcurrentStreams(100); - return new ServerConnector(server, + return new ServerConnector( + server, new SslConnectionFactory(sslContextFactory, alpnServerConnectionFactory.getProtocol()), alpnServerConnectionFactory, http2ServerConnectionFactory); diff --git a/src/main/java/io/github/azagniotov/stubby4j/server/StubbyManager.java b/src/main/java/io/github/azagniotov/stubby4j/server/StubbyManager.java index d14c62fa4..c149c7dd3 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/server/StubbyManager.java +++ b/src/main/java/io/github/azagniotov/stubby4j/server/StubbyManager.java @@ -1,5 +1,20 @@ -package io.github.azagniotov.stubby4j.server; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.azagniotov.stubby4j.server; import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; import io.github.azagniotov.stubby4j.cli.ANSITerminal; @@ -9,12 +24,11 @@ import io.github.azagniotov.stubby4j.filesystem.MainYamlScanner; import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.utils.ObjectUtils; +import java.util.Map; import org.eclipse.jetty.server.Server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Map; - @GeneratedCodeClassCoverageExclusion public final class StubbyManager { private static final Logger LOGGER = LoggerFactory.getLogger(StubbyManager.class); @@ -24,7 +38,11 @@ public final class StubbyManager { private final JettyFactory jettyFactory; private final StubRepository stubRepository; - StubbyManager(final Map commandLineArgs, final Server server, final JettyFactory jettyFactory, final StubRepository stubRepository) { + StubbyManager( + final Map commandLineArgs, + final Server server, + final JettyFactory jettyFactory, + final StubRepository stubRepository) { this.commandLineArgs = commandLineArgs; this.server = server; this.jettyFactory = jettyFactory; @@ -100,7 +118,8 @@ private void watchDataStore(final StubRepository stubRepository, final long slee final ExternalFilesScanner externalFilesScanner = new ExternalFilesScanner(stubRepository, sleepTime + 25); new Thread(externalFilesScanner, ExternalFilesScanner.class.getCanonicalName()).start(); - final MainIncludedYamlScanner mainIncludedYamlScanner = new MainIncludedYamlScanner(stubRepository, sleepTime + 50); + final MainIncludedYamlScanner mainIncludedYamlScanner = + new MainIncludedYamlScanner(stubRepository, sleepTime + 50); new Thread(mainIncludedYamlScanner, MainIncludedYamlScanner.class.getCanonicalName()).start(); } -} \ No newline at end of file +} diff --git a/src/main/java/io/github/azagniotov/stubby4j/server/StubbyManagerFactory.java b/src/main/java/io/github/azagniotov/stubby4j/server/StubbyManagerFactory.java index bdb31d90e..b78c1c795 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/server/StubbyManagerFactory.java +++ b/src/main/java/io/github/azagniotov/stubby4j/server/StubbyManagerFactory.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.server; import io.github.azagniotov.stubby4j.caching.Cache; @@ -8,38 +24,39 @@ import io.github.azagniotov.stubby4j.stubs.StubHttpLifecycle; import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.yaml.YamlParseResultSet; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.util.log.Log; - import java.io.File; import java.util.Map; import java.util.concurrent.CompletableFuture; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.util.log.Log; public class StubbyManagerFactory { - public StubbyManagerFactory() { - - } + public StubbyManagerFactory() {} - public synchronized StubbyManager construct(final File configFile, - final Map commandLineArgs, - final CompletableFuture stubLoadComputation) throws Exception { + public synchronized StubbyManager construct( + final File configFile, + final Map commandLineArgs, + final CompletableFuture stubLoadComputation) + throws Exception { final String enableJettyDebug = System.getProperty("enableJettyDebug"); if (enableJettyDebug == null) { Log.setLog(new EmptyLogger()); } - //TODO BUG: When stubs are cached, upon finding the previously cached match by hashCode, + // TODO BUG: When stubs are cached, upon finding the previously cached match by hashCode, // if stubbed response has template tokens for dynamic token replacement, the tokens are // not replaced with values from the incoming request because the cached stub is not going // through the same matching process like upon the first match. Either fix this bug or just // deprecate the stub caching all together, as it is causing more headaches than not. // Also, deprecate the --disable_stub_caching command line flag if the caching has retired. - final boolean shouldDisableStubCache = commandLineArgs.containsKey(CommandLineInterpreter.OPTION_DISABLE_STUB_CACHING); + final boolean shouldDisableStubCache = + commandLineArgs.containsKey(CommandLineInterpreter.OPTION_DISABLE_STUB_CACHING); final Cache stubCache = Cache.stubHttpLifecycleCache(true); - final StubRepository stubRepository = new StubRepository(configFile, stubCache, stubLoadComputation, new StubbyHttpTransport()); + final StubRepository stubRepository = + new StubRepository(configFile, stubCache, stubLoadComputation, new StubbyHttpTransport()); final JettyFactory jettyFactory = new JettyFactory(commandLineArgs, stubRepository); final Server server = jettyFactory.construct(); diff --git a/src/main/java/io/github/azagniotov/stubby4j/server/ssl/CustomHostnameVerifier.java b/src/main/java/io/github/azagniotov/stubby4j/server/ssl/CustomHostnameVerifier.java index acfb7fcf0..f5b23a33a 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/server/ssl/CustomHostnameVerifier.java +++ b/src/main/java/io/github/azagniotov/stubby4j/server/ssl/CustomHostnameVerifier.java @@ -1,7 +1,22 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.server.ssl; import io.github.azagniotov.stubby4j.annotations.GeneratedCodeMethodCoverageExclusion; - import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.Collection; diff --git a/src/main/java/io/github/azagniotov/stubby4j/server/ssl/DefaultExtendedX509TrustManager.java b/src/main/java/io/github/azagniotov/stubby4j/server/ssl/DefaultExtendedX509TrustManager.java index a86177e37..59605eb46 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/server/ssl/DefaultExtendedX509TrustManager.java +++ b/src/main/java/io/github/azagniotov/stubby4j/server/ssl/DefaultExtendedX509TrustManager.java @@ -1,16 +1,31 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.server.ssl; -import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; +import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.keyStoreAsX509Certificates; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; +import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; import java.security.KeyStore; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Set; - -import static io.github.azagniotov.stubby4j.server.ssl.SslUtils.keyStoreAsX509Certificates; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; /** * This class is a wrapper around default X.509 trust manager initialized through {@link TrustManagerFactory} with the @@ -28,13 +43,12 @@ public final class DefaultExtendedX509TrustManager implements X509TrustManager { DEFAULT_TRUST_MANAGER = loadDefaultX509TrustManager(); } - public DefaultExtendedX509TrustManager() { - - } + public DefaultExtendedX509TrustManager() {} private static X509TrustManager loadDefaultX509TrustManager() { try { - final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + final TrustManagerFactory trustManagerFactory = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // Using null here initialises the TrustManagerFactory with the default trust store. trustManagerFactory.init((KeyStore) null); @@ -72,12 +86,12 @@ private boolean isSelfSignedCertificate(final X509Certificate[] chain) { if (chain.length == 1) { final X509Certificate x509Certificate = chain[0]; final CustomHostnameVerifier customHostnameVerifier = new CustomHostnameVerifier(x509Certificate); - return STUBBY_SELF_SIGNED_CERT.contains(x509Certificate) || - customHostnameVerifier.isX500PrincipalNameLocalhost() || - customHostnameVerifier.isSubjectAltNamesContain("localhost") || - customHostnameVerifier.isSubjectAltNamesContain("127.0.0.1") || - customHostnameVerifier.isSubjectAltNamesContain("::1") || - customHostnameVerifier.isSubjectAltNamesContainPrivateIp(); + return STUBBY_SELF_SIGNED_CERT.contains(x509Certificate) + || customHostnameVerifier.isX500PrincipalNameLocalhost() + || customHostnameVerifier.isSubjectAltNamesContain("localhost") + || customHostnameVerifier.isSubjectAltNamesContain("127.0.0.1") + || customHostnameVerifier.isSubjectAltNamesContain("::1") + || customHostnameVerifier.isSubjectAltNamesContainPrivateIp(); } return false; diff --git a/src/main/java/io/github/azagniotov/stubby4j/server/ssl/LanIPv4Validator.java b/src/main/java/io/github/azagniotov/stubby4j/server/ssl/LanIPv4Validator.java index ad81f7398..2a9f9b7de 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/server/ssl/LanIPv4Validator.java +++ b/src/main/java/io/github/azagniotov/stubby4j/server/ssl/LanIPv4Validator.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.server.ssl; import java.util.regex.Pattern; @@ -10,12 +26,12 @@ public final class LanIPv4Validator { * 172.16.0.0 – 172. 31.255.255 172.16.0.0 /12 * 192.168.0.0 – 192.168.255.255 192.168.0.0 /16 */ - private static final String LAN_IPV4_PATTERN = "(^192\\.168\\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^172\\.([1][6-9]|[2][0-9]|[3][0-1])\\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^10\\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)"; - private static final Pattern PATTERN = Pattern.compile(LAN_IPV4_PATTERN); + private static final String LAN_IPV4_PATTERN = + "(^192\\.168\\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^172\\.([1][6-9]|[2][0-9]|[3][0-1])\\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^10\\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)"; - private LanIPv4Validator() { + private static final Pattern PATTERN = Pattern.compile(LAN_IPV4_PATTERN); - } + private LanIPv4Validator() {} static boolean isPrivateIp(final String privateIp) { return PATTERN.matcher(privateIp).matches(); diff --git a/src/main/java/io/github/azagniotov/stubby4j/server/ssl/SslUtils.java b/src/main/java/io/github/azagniotov/stubby4j/server/ssl/SslUtils.java index 6893aab9b..6d8222d99 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/server/ssl/SslUtils.java +++ b/src/main/java/io/github/azagniotov/stubby4j/server/ssl/SslUtils.java @@ -1,15 +1,28 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.server.ssl; +import static java.util.Collections.singletonList; +import static java.util.stream.Collectors.toSet; +import static java.util.stream.Stream.concat; + import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.utils.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; import java.io.InputStream; import java.security.KeyStore; import java.security.KeyStoreException; @@ -22,10 +35,12 @@ import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; - -import static java.util.Collections.singletonList; -import static java.util.stream.Collectors.toSet; -import static java.util.stream.Stream.concat; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Some of code in the current file has been adopted from the Netty project: @@ -49,13 +64,12 @@ public final class SslUtils { private static final String TLS = "TLS"; private static final Logger LOGGER = LoggerFactory.getLogger(SslUtils.class); // See https://tools.ietf.org/html/rfc8446#appendix-B.4 - private static final Set TLS_v13_CIPHERS = Collections.unmodifiableSet(new LinkedHashSet<>( - Arrays.asList( - "TLS_AES_256_GCM_SHA384", - "TLS_CHACHA20_POLY1305_SHA256", - "TLS_AES_128_GCM_SHA256", - "TLS_AES_128_CCM_8_SHA256", - "TLS_AES_128_CCM_SHA256"))); + private static final Set TLS_v13_CIPHERS = Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.asList( + "TLS_AES_256_GCM_SHA384", + "TLS_CHACHA20_POLY1305_SHA256", + "TLS_AES_128_GCM_SHA256", + "TLS_AES_128_CCM_8_SHA256", + "TLS_AES_128_CCM_SHA256"))); private static final Set DEFAULT_ENABLED_TLS_VERSIONS; private static final boolean TLS_v1_3_JDK_SUPPORTED; private static final Set ALL_ENABLED_TLS_VERSIONS; @@ -64,22 +78,22 @@ public final class SslUtils { private static final Set SUPPORT_CIPHERS; static { - String overrideDisabledAlgorithms = System.getProperty("overrideDisabledAlgorithms"); if (overrideDisabledAlgorithms != null && overrideDisabledAlgorithms.equalsIgnoreCase("true")) { - final String overrideRequest = "Removing SSLv3, TLSv1 and TLSv1.1 from the JDK's 'jdk.tls.disabledAlgorithms' property.."; + final String overrideRequest = + "Removing SSLv3, TLSv1 and TLSv1.1 from the JDK's 'jdk.tls.disabledAlgorithms' property.."; ANSITerminal.warn(overrideRequest); LOGGER.warn(overrideRequest); // https://stackoverflow.com/questions/52115699/relaxing-ssl-algorithm-constrains-programmatically // Removed SSLv3, TLSv1 and TLSv1.1 removeFromSecurityProperty("jdk.tls.disabledAlgorithms", "SSLv3", "TLSv1", "TLSv1.1"); - } SELF_SIGNED_CERTIFICATE_TRUST_STORE = loadStubby4jSelfSignedTrustStore(); TLS_v1_3_JDK_SUPPORTED = isTLSv13SupportedByCurrentJDK(); DEFAULT_SSL_CONTEXT = initAndSetDefaultSSLContext(); - DEFAULT_ENABLED_TLS_VERSIONS = new HashSet<>(Arrays.asList(DEFAULT_SSL_CONTEXT.getDefaultSSLParameters().getProtocols())); + DEFAULT_ENABLED_TLS_VERSIONS = new HashSet<>( + Arrays.asList(DEFAULT_SSL_CONTEXT.getDefaultSSLParameters().getProtocols())); ALL_ENABLED_TLS_VERSIONS = narrowDownEnabledProtocols(); DEFAULT_SSL_ENGINE = DEFAULT_SSL_CONTEXT.createSSLEngine(); DEFAULT_SSL_ENGINE.setEnabledProtocols(enabledProtocols()); @@ -87,9 +101,7 @@ public final class SslUtils { SUPPORT_CIPHERS = supportedCiphers(); } - private SslUtils() { - - } + private SslUtils() {} public static void initStatic() { // init static { ... } @@ -122,7 +134,7 @@ private static SSLContext initAndSetDefaultSSLContext() { // // Basically, some how somewhere someone needs to be able to validate self-signed certificate. // https://github.com/azagniotov/stubby4j#client-side-tls-configuration - defaultCandidate.init(null, new TrustManager[]{new DefaultExtendedX509TrustManager()}, null); + defaultCandidate.init(null, new TrustManager[] {new DefaultExtendedX509TrustManager()}, null); SSLContext.setDefault(defaultCandidate); return defaultCandidate; @@ -132,9 +144,10 @@ private static SSLContext initAndSetDefaultSSLContext() { } private static Set narrowDownEnabledProtocols() { - return TLS_v1_3_JDK_SUPPORTED ? - concat(new HashSet<>(singletonList(TLS_v1_3)).stream(), DEFAULT_ENABLED_TLS_VERSIONS.stream()) - .collect(toSet()) : DEFAULT_ENABLED_TLS_VERSIONS; + return TLS_v1_3_JDK_SUPPORTED + ? concat(new HashSet<>(singletonList(TLS_v1_3)).stream(), DEFAULT_ENABLED_TLS_VERSIONS.stream()) + .collect(toSet()) + : DEFAULT_ENABLED_TLS_VERSIONS; } public static String[] includedCipherSuites() { @@ -148,7 +161,8 @@ public static String[] enabledProtocols() { private static KeyStore loadStubby4jSelfSignedTrustStore() { try { // - // 1. Download and save the remote self-signed certificate from the stubby4j server with TLS at localhost:7443 + // 1. Download and save the remote self-signed certificate from the stubby4j server with TLS at + // localhost:7443 // This opens an SSL connection to the specified hostname and port and prints the SSL certificate. // --------------------------------------------------------------------------------- // $ echo quit | openssl s_client -showcerts -servername localhost -connect "localhost":7443 > FILE_NAME.pem @@ -169,10 +183,13 @@ private static KeyStore loadStubby4jSelfSignedTrustStore() { final String selfSignedTrustStorePath = getSelfSignedTrustStorePath(); final InputStream inputStream = SslUtils.class.getResourceAsStream(selfSignedTrustStorePath); if (inputStream == null) { - throw new IllegalStateException(String.format("Could not get resource %s as stream", selfSignedTrustStorePath)); + throw new IllegalStateException( + String.format("Could not get resource %s as stream", selfSignedTrustStorePath)); } final KeyStore trustStore = KeyStore.getInstance("PKCS12"); - trustStore.load(inputStream, "stubby4j".toCharArray()); // this is the password entered during the 'keytool -import ... ' command + trustStore.load( + inputStream, + "stubby4j".toCharArray()); // this is the password entered during the 'keytool -import ... ' command return trustStore; } catch (Exception e) { @@ -231,15 +248,16 @@ private static Set supportedCiphers() { // prefix instead of the "TLS_" prefix (as defined in the JSSE cipher suite names [1]). According to IBM's // documentation [2] the "SSL_" prefix is "interchangeable" with the "TLS_" prefix. // See the IBM forum discussion [3] and issue on IBM's JVM [4] for more details. - //[1] https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#ciphersuites - //[2] https://www.ibm.com/support/knowledgecenter/en/SSYKE2_8.0.0/com.ibm.java.security.component.80.doc/ + // [1] https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#ciphersuites + // [2] https://www.ibm.com/support/knowledgecenter/en/SSYKE2_8.0.0/com.ibm.java.security.component.80.doc/ // security-component/jsse2Docs/ciphersuites.html - //[3] https://www.ibm.com/developerworks/community/forums/html/topic?id=9b5a56a9-fa46-4031-b33b-df91e28d77c2 - //[4] https://www.ibm.com/developerworks/rfe/execute?use_case=viewRfe&CR_ID=71770 + // [3] + // https://www.ibm.com/developerworks/community/forums/html/topic?id=9b5a56a9-fa46-4031-b33b-df91e28d77c2 + // [4] https://www.ibm.com/developerworks/rfe/execute?use_case=viewRfe&CR_ID=71770 if (supportedCipher.startsWith("SSL_")) { final String tlsPrefixedCipherName = "TLS_" + supportedCipher.substring("SSL_".length()); try { - DEFAULT_SSL_ENGINE.setEnabledCipherSuites(new String[]{tlsPrefixedCipherName}); + DEFAULT_SSL_ENGINE.setEnabledCipherSuites(new String[] {tlsPrefixedCipherName}); supportedCiphersSet.add(tlsPrefixedCipherName); } catch (IllegalArgumentException ignored) { // The cipher is not supported ... move on to the next cipher. @@ -247,9 +265,9 @@ private static Set supportedCiphers() { } } - return TLS_v1_3_JDK_SUPPORTED ? - concat(TLS_v13_CIPHERS.stream(), supportedCiphersSet.stream()).collect(toSet()) : - supportedCiphersSet; + return TLS_v1_3_JDK_SUPPORTED + ? concat(TLS_v13_CIPHERS.stream(), supportedCiphersSet.stream()).collect(toSet()) + : supportedCiphersSet; } private static boolean isContainsTLSv13(final String[] values) { diff --git a/src/main/java/io/github/azagniotov/stubby4j/server/websocket/StubsServerWebSocket.java b/src/main/java/io/github/azagniotov/stubby4j/server/websocket/StubsServerWebSocket.java index c38c8c8ce..5ffde702b 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/server/websocket/StubsServerWebSocket.java +++ b/src/main/java/io/github/azagniotov/stubby4j/server/websocket/StubsServerWebSocket.java @@ -1,5 +1,30 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.server.websocket; +import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketMessageType.TEXT; +import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponsePolicy.DISCONNECT; +import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponsePolicy.FRAGMENTATION; +import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponsePolicy.ONCE; +import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponsePolicy.PING; +import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponsePolicy.PUSH; +import static io.github.azagniotov.stubby4j.utils.CollectionUtils.chunkifyByteArrayAndQueue; +import static io.github.azagniotov.stubby4j.utils.ConsoleUtils.getLocalDateTime; + import io.github.azagniotov.stubby4j.annotations.GeneratedCodeMethodCoverageExclusion; import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketClientRequest; @@ -7,6 +32,14 @@ import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketOnMessageLifeCycle; import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponse; import io.github.azagniotov.stubby4j.utils.ConsoleUtils; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import org.eclipse.jetty.websocket.api.RemoteEndpoint; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.StatusCode; @@ -19,24 +52,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketMessageType.TEXT; -import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponsePolicy.DISCONNECT; -import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponsePolicy.FRAGMENTATION; -import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponsePolicy.ONCE; -import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponsePolicy.PING; -import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponsePolicy.PUSH; -import static io.github.azagniotov.stubby4j.utils.CollectionUtils.chunkifyByteArrayAndQueue; -import static io.github.azagniotov.stubby4j.utils.ConsoleUtils.getLocalDateTime; - @WebSocket public class StubsServerWebSocket { @@ -51,8 +66,8 @@ public class StubsServerWebSocket { private volatile Session session; private RemoteEndpoint remote; - public StubsServerWebSocket(final StubWebSocketConfig stubWebSocketConfig, - final ScheduledExecutorService scheduledExecutorService) { + public StubsServerWebSocket( + final StubWebSocketConfig stubWebSocketConfig, final ScheduledExecutorService scheduledExecutorService) { this.stubWebSocketConfig = stubWebSocketConfig; this.scheduledExecutorService = scheduledExecutorService; } @@ -115,11 +130,11 @@ public void onWebSocketText(final String message) { @OnWebSocketClose public void onWebSocketClose(final int statusCode, final String reason) { - final String logMessage = String.format("[%s] <= %s %s\n", + final String logMessage = String.format( + "[%s] <= %s %s\n", getLocalDateTime(), statusCode, - String.format("Socket closed by client: [%s] %s", statusCode, reason.trim()) - ); + String.format("Socket closed by client: [%s] %s", statusCode, reason.trim())); ANSITerminal.ok(logMessage); LOGGER.info(logMessage); @@ -128,11 +143,7 @@ public void onWebSocketClose(final int statusCode, final String reason) { @OnWebSocketError @GeneratedCodeMethodCoverageExclusion public void onWebSocketError(Throwable cause) { - final String logMessage = String.format("[%s] <= %s %s\n", - getLocalDateTime(), - 500, - cause.getMessage() - ); + final String logMessage = String.format("[%s] <= %s %s\n", getLocalDateTime(), 500, cause.getMessage()); ANSITerminal.error(logMessage); LOGGER.error(logMessage); @@ -142,70 +153,87 @@ private void dispatchServerResponse(final StubWebSocketServerResponse serverResp final long delay = serverResponse.getDelay(); if (serverResponse.getPolicy() == ONCE || serverResponse.getPolicy() == DISCONNECT) { - scheduledExecutorService.schedule(() -> { - if (serverResponse.getMessageType() == TEXT) { - // Send response in a UTF-8 text form as a whole - this.remote.sendStringByFuture(serverResponse.getBodyAsString()); - } else { - // Send response in a binary form as a whole blob - this.remote.sendBytesByFuture(ByteBuffer.wrap(serverResponse.getBodyAsBytes())); - } - - }, delay, TimeUnit.MILLISECONDS); + scheduledExecutorService.schedule( + () -> { + if (serverResponse.getMessageType() == TEXT) { + // Send response in a UTF-8 text form as a whole + this.remote.sendStringByFuture(serverResponse.getBodyAsString()); + } else { + // Send response in a binary form as a whole blob + this.remote.sendBytesByFuture(ByteBuffer.wrap(serverResponse.getBodyAsBytes())); + } + }, + delay, + TimeUnit.MILLISECONDS); } if (serverResponse.getPolicy() == FRAGMENTATION) { - final BlockingQueue queue = chunkifyByteArrayAndQueue(serverResponse.getBodyAsBytes(), FRAGMENTATION_FRAMES); - scheduledExecutorService.schedule(() -> { - while (!queue.isEmpty()) { - try { - final ByteBuffer byteBufferChunk = queue.poll(); - if (byteBufferChunk != null) { - final boolean isLast = queue.isEmpty(); - // Send response in a binary form as sequential fragmented frames one after another in - // a blocking manner. This must be a blocking call, i.e.: we cannot send each chunk - // in an async manner using a Future, as this can produce un-deterministic behavior. - this.remote.sendPartialBytes(byteBufferChunk, isLast); - Thread.sleep(delay); + final BlockingQueue queue = + chunkifyByteArrayAndQueue(serverResponse.getBodyAsBytes(), FRAGMENTATION_FRAMES); + scheduledExecutorService.schedule( + () -> { + while (!queue.isEmpty()) { + try { + final ByteBuffer byteBufferChunk = queue.poll(); + if (byteBufferChunk != null) { + final boolean isLast = queue.isEmpty(); + // Send response in a binary form as sequential fragmented frames one after another + // in + // a blocking manner. This must be a blocking call, i.e.: we cannot send each chunk + // in an async manner using a Future, as this can produce un-deterministic behavior. + this.remote.sendPartialBytes(byteBufferChunk, isLast); + Thread.sleep(delay); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } } - } catch (IOException e) { - throw new UncheckedIOException(e); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - }, delay, TimeUnit.MILLISECONDS); + }, + delay, + TimeUnit.MILLISECONDS); } if (serverResponse.getPolicy() == PUSH) { // Send response to the client in periodic pushes one after another. The content will be sent as a whole - scheduledExecutorService.scheduleAtFixedRate(() -> { - if (serverResponse.getMessageType() == TEXT) { - this.remote.sendStringByFuture(serverResponse.getBodyAsString()); - } else { - this.remote.sendBytesByFuture(ByteBuffer.wrap(serverResponse.getBodyAsBytes())); - } - }, delay, delay, TimeUnit.MILLISECONDS); + scheduledExecutorService.scheduleAtFixedRate( + () -> { + if (serverResponse.getMessageType() == TEXT) { + this.remote.sendStringByFuture(serverResponse.getBodyAsString()); + } else { + this.remote.sendBytesByFuture(ByteBuffer.wrap(serverResponse.getBodyAsBytes())); + } + }, + delay, + delay, + TimeUnit.MILLISECONDS); } if (serverResponse.getPolicy() == PING) { // Send Ping (without application data) to the connected // client upon on-open or on-message config in periodic manner. // WebSocket Ping spec: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 - scheduledExecutorService.scheduleAtFixedRate(() -> { - try { - this.remote.sendPing(EMPTY_BYTE_BUFFER); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }, delay, delay, TimeUnit.MILLISECONDS); + scheduledExecutorService.scheduleAtFixedRate( + () -> { + try { + this.remote.sendPing(EMPTY_BYTE_BUFFER); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }, + delay, + delay, + TimeUnit.MILLISECONDS); } if (serverResponse.getPolicy() == DISCONNECT) { - scheduledExecutorService.schedule(() -> { - this.session.close(StatusCode.NORMAL, NORMAL_CLOSE_REASON); - }, delay, TimeUnit.MILLISECONDS); + scheduledExecutorService.schedule( + () -> { + this.session.close(StatusCode.NORMAL, NORMAL_CLOSE_REASON); + }, + delay, + TimeUnit.MILLISECONDS); } } } - diff --git a/src/main/java/io/github/azagniotov/stubby4j/server/websocket/StubsWebSocketCreator.java b/src/main/java/io/github/azagniotov/stubby4j/server/websocket/StubsWebSocketCreator.java index 11964cc64..4afc2429c 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/server/websocket/StubsWebSocketCreator.java +++ b/src/main/java/io/github/azagniotov/stubby4j/server/websocket/StubsWebSocketCreator.java @@ -1,18 +1,33 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.server.websocket; import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketConfig; import io.github.azagniotov.stubby4j.utils.ConsoleUtils; -import org.eclipse.jetty.http.HttpStatus; -import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest; -import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse; -import org.eclipse.jetty.websocket.servlet.WebSocketCreator; - import java.io.IOException; import java.io.UncheckedIOException; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Executors; +import org.eclipse.jetty.http.HttpStatus; +import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest; +import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse; +import org.eclipse.jetty.websocket.servlet.WebSocketCreator; public class StubsWebSocketCreator implements WebSocketCreator { @@ -23,10 +38,11 @@ public StubsWebSocketCreator(final StubRepository stubRepository) { } @Override - public Object createWebSocket(final ServletUpgradeRequest servletUpgradeRequest, - final ServletUpgradeResponse servletUpgradeResponse) { + public Object createWebSocket( + final ServletUpgradeRequest servletUpgradeRequest, final ServletUpgradeResponse servletUpgradeResponse) { - final StubWebSocketConfig stubWebSocketConfig = this.stubRepository.matchWebSocketConfigByUrl(servletUpgradeRequest.getRequestPath()); + final StubWebSocketConfig stubWebSocketConfig = + this.stubRepository.matchWebSocketConfigByUrl(servletUpgradeRequest.getRequestPath()); // Renders HTTP error response if client requested an invalid URL checkAndHandleNotFound(stubWebSocketConfig, servletUpgradeRequest, servletUpgradeResponse); @@ -36,7 +52,10 @@ public Object createWebSocket(final ServletUpgradeRequest servletUpgradeRequest, return new StubsServerWebSocket(stubWebSocketConfig, Executors.newScheduledThreadPool(10)); } - private void checkAndHandleNotFound(final StubWebSocketConfig stubWebSocketConfig, ServletUpgradeRequest servletUpgradeRequest, ServletUpgradeResponse servletUpgradeResponse) { + private void checkAndHandleNotFound( + final StubWebSocketConfig stubWebSocketConfig, + ServletUpgradeRequest servletUpgradeRequest, + ServletUpgradeResponse servletUpgradeResponse) { // The client made request to a non-existent URL if (stubWebSocketConfig == null) { try { @@ -50,9 +69,10 @@ private void checkAndHandleNotFound(final StubWebSocketConfig stubWebSocketConfi } } - private void checkAndSetAcceptedProtocols(final StubWebSocketConfig stubWebSocketConfig, - final ServletUpgradeRequest servletUpgradeRequest, - final ServletUpgradeResponse servletUpgradeResponse) { + private void checkAndSetAcceptedProtocols( + final StubWebSocketConfig stubWebSocketConfig, + final ServletUpgradeRequest servletUpgradeRequest, + final ServletUpgradeResponse servletUpgradeResponse) { // We have configured sub-protocols, so the client must conform to contract if (!stubWebSocketConfig.getSubProtocols().isEmpty()) { diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/AbstractBuilder.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/AbstractBuilder.java index 8246dd092..befa11528 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/AbstractBuilder.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/AbstractBuilder.java @@ -1,14 +1,28 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs; +import static io.github.azagniotov.generics.TypeSafeConverter.as; import io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty; - import java.util.HashMap; import java.util.Map; import java.util.Optional; -import static io.github.azagniotov.generics.TypeSafeConverter.as; - public abstract class AbstractBuilder { protected final Map fieldNameAndValues; diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/ReflectableStub.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/ReflectableStub.java index 7722e8674..ae1a14a61 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/ReflectableStub.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/ReflectableStub.java @@ -1,8 +1,22 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs; /** * Marker interface */ -public interface ReflectableStub { - -} +public interface ReflectableStub {} diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/RegexParser.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/RegexParser.java index 0d9fd9b3e..0911a8ff2 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/RegexParser.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/RegexParser.java @@ -1,19 +1,32 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs; +import static io.github.azagniotov.stubby4j.utils.StringUtils.buildToken; import io.github.azagniotov.stubby4j.annotations.VisibleForTesting; import io.github.azagniotov.stubby4j.caching.Cache; - import java.util.Map; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; -import static io.github.azagniotov.stubby4j.utils.StringUtils.buildToken; - enum RegexParser { - INSTANCE; // Pattern.MULTILINE changes the behavior of '^' and '$' characters by telling Java to accept the @@ -24,7 +37,7 @@ enum RegexParser { // // You need to make sure that you regex pattern covers both \r (carriage return) and \n (linefeed). // It is achievable by using symbol '\s+', which covers both \r (carriage return) and \n (linefeed). - static final int[] REGEX_FLAGS = new int[]{Pattern.MULTILINE, Pattern.DOTALL}; + static final int[] REGEX_FLAGS = new int[] {Pattern.MULTILINE, Pattern.DOTALL}; /** * ASCII character decimal values * '$' - 36 @@ -42,12 +55,13 @@ enum RegexParser { * '|' - 124 * '}' - 125 */ - @VisibleForTesting - static final char[] REGEX_CHARS = new char[]{'$', '(', ')', '*', '+', '.', '?', '[', ']', '\\', '^', '{', '|', '}'}; + static final char[] REGEX_CHARS = + new char[] {'$', '(', ')', '*', '+', '.', '?', '[', ']', '\\', '^', '{', '|', '}'}; @VisibleForTesting static final Cache REGEX_PATTERN_CACHE = Cache.regexPatternCache(); + private static final boolean[] SPECIAL_CHARS; private static final int REGEX_CHAR_LENGTH_THRESHOLD = 2; @@ -123,7 +137,11 @@ private void compilePatternAndCache(final String value, final int flags) { } } - boolean match(final String patternCandidate, final String subject, final String templateTokenName, final Map regexGroups) { + boolean match( + final String patternCandidate, + final String subject, + final String templateTokenName, + final Map regexGroups) { int currentFlags = 0; for (int flag : REGEX_FLAGS) { if (match(patternCandidate, subject, templateTokenName, regexGroups, currentFlags |= flag)) { @@ -133,7 +151,12 @@ boolean match(final String patternCandidate, final String subject, final String return false; } - private boolean match(final String patternCandidate, final String subject, final String templateTokenName, final Map regexGroups, final int flags) { + private boolean match( + final String patternCandidate, + final String subject, + final String templateTokenName, + final Map regexGroups, + final int flags) { try { final Pattern computedPattern = getCachedPatternOrCacheNewCompiled(patternCandidate, flags); final Matcher matcher = computedPattern.matcher(subject); @@ -142,8 +165,10 @@ private boolean match(final String patternCandidate, final String subject, final // group(0) holds the full regex matchStubByIndex regexGroups.put(buildToken(templateTokenName, 0), matcher.group(0)); - //Matcher.groupCount() returns the number of explicitly defined capturing groups in the pattern regardless - // of whether the capturing groups actually participated in the matchStubByIndex. It does not include matcher.group(0) + // Matcher.groupCount() returns the number of explicitly defined capturing groups in the pattern + // regardless + // of whether the capturing groups actually participated in the matchStubByIndex. It does not include + // matcher.group(0) final int groupCount = matcher.groupCount(); if (groupCount > 0) { for (int idx = 1; idx <= groupCount; idx++) { diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/StubHttpLifecycle.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/StubHttpLifecycle.java index 626e624d9..c5e46f6fd 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/StubHttpLifecycle.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/StubHttpLifecycle.java @@ -1,20 +1,33 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs; +import static io.github.azagniotov.generics.TypeSafeConverter.asCheckedLinkedList; +import static io.github.azagniotov.stubby4j.stubs.StubResponse.okResponse; import io.github.azagniotov.stubby4j.annotations.VisibleForTesting; import io.github.azagniotov.stubby4j.utils.ReflectionUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; - import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -import static io.github.azagniotov.generics.TypeSafeConverter.asCheckedLinkedList; -import static io.github.azagniotov.stubby4j.stubs.StubResponse.okResponse; - - public class StubHttpLifecycle implements ReflectableStub { private final AtomicInteger responseSequencedIdCounter = new AtomicInteger(0); @@ -163,13 +176,11 @@ public String getAjaxResponseContent(final String propertyName, final int sequen } @Override - public int hashCode() { return this.request.hashCode(); } @Override - public boolean equals(final Object o) { if (this == o) { return true; @@ -256,15 +267,8 @@ public Builder withUUID(final String uuid) { } public StubHttpLifecycle build() { - final StubHttpLifecycle stubHttpLifecycle = - new StubHttpLifecycle( - request, - response, - requestAsYAML, - responseAsYAML, - completeYAML, - description, - uuid); + final StubHttpLifecycle stubHttpLifecycle = new StubHttpLifecycle( + request, response, requestAsYAML, responseAsYAML, completeYAML, description, uuid); this.request = null; this.response = okResponse(); diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/StubMatcher.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/StubMatcher.java index 17bc981f5..64eb14400 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/StubMatcher.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/StubMatcher.java @@ -1,10 +1,39 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs; +import static io.github.azagniotov.stubby4j.utils.StringUtils.escapeSpecialRegexCharacters; +import static io.github.azagniotov.stubby4j.utils.StringUtils.getBytesUtf8; +import static io.github.azagniotov.stubby4j.utils.StringUtils.isNotSet; +import static io.github.azagniotov.stubby4j.utils.StringUtils.isSet; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.HEADERS; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.QUERY; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.URL; +import static org.xmlunit.builder.Input.fromByteArray; import io.github.azagniotov.stubby4j.annotations.VisibleForTesting; import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.stubs.matching.Stubby4jMatchesRegexPlaceholderHandler; import io.github.azagniotov.stubby4j.stubs.matching.Stubby4jXmlUnitPlaceholderDifferenceEvaluator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.json.JSONException; import org.skyscreamer.jsonassert.JSONCompare; import org.skyscreamer.jsonassert.JSONCompareMode; @@ -19,24 +48,10 @@ import org.xmlunit.diff.DifferenceEvaluators; import org.xmlunit.diff.ElementSelectors; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static io.github.azagniotov.stubby4j.utils.StringUtils.escapeSpecialRegexCharacters; -import static io.github.azagniotov.stubby4j.utils.StringUtils.getBytesUtf8; -import static io.github.azagniotov.stubby4j.utils.StringUtils.isNotSet; -import static io.github.azagniotov.stubby4j.utils.StringUtils.isSet; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.HEADERS; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.QUERY; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.URL; -import static org.xmlunit.builder.Input.fromByteArray; - class StubMatcher { private static final Logger LOGGER = LoggerFactory.getLogger(StubMatcher.class); - private static final DefaultNodeMatcher NODE_MATCHER_BY_NAME_AND_ALL_ATTRIBUTES = new DefaultNodeMatcher(ElementSelectors.byNameAndAllAttributes); + private static final DefaultNodeMatcher NODE_MATCHER_BY_NAME_AND_ALL_ATTRIBUTES = + new DefaultNodeMatcher(ElementSelectors.byNameAndAllAttributes); private static final Pattern SUB_TYPE_PATTERN = Pattern.compile("/(?:.*\\+)?(\\w*);?"); private static final String FAILED_TO_MATCH_ON_STUBBED = "Failed to match on stubbed"; @@ -58,24 +73,36 @@ class StubMatcher { boolean matches(final StubRequest stubbedRequest, final StubRequest assertingRequest) { // Match stubbed request URI path if (!urlsMatch(stubbedRequest.getUri(), assertingRequest.getUri())) { - final String urlMatchFailed = String.format(FAILED_TO_MATCH_ON_STUBBED + MSG_FIELD_URL + MSG_FIELDS_TEMPLATE, stubbedRequest.getUri(), assertingRequest.getUri()); + final String urlMatchFailed = String.format( + FAILED_TO_MATCH_ON_STUBBED + MSG_FIELD_URL + MSG_FIELDS_TEMPLATE, + stubbedRequest.getUri(), + assertingRequest.getUri()); ANSITerminal.error(urlMatchFailed); LOGGER.error(urlMatchFailed); return false; } - final String urlMatchSuccess = String.format(MATCHED_ON_STUBBED + MSG_FIELD_URL + MSG_FIELDS_TEMPLATE, stubbedRequest.getUri(), assertingRequest.getUri()); + final String urlMatchSuccess = String.format( + MATCHED_ON_STUBBED + MSG_FIELD_URL + MSG_FIELDS_TEMPLATE, + stubbedRequest.getUri(), + assertingRequest.getUri()); ANSITerminal.info(urlMatchSuccess); LOGGER.info(urlMatchSuccess); // Match stubbed request HTTP method(s) if (!stubbedRequest.getMethod().isEmpty()) { if (!listsIntersect(stubbedRequest.getMethod(), assertingRequest.getMethod())) { - final String methodMatchFailed = String.format(FAILED_TO_MATCH_ON_STUBBED + MSG_FIELD_METHOD + MSG_FIELDS_TEMPLATE, stubbedRequest.getMethod(), assertingRequest.getMethod()); + final String methodMatchFailed = String.format( + FAILED_TO_MATCH_ON_STUBBED + MSG_FIELD_METHOD + MSG_FIELDS_TEMPLATE, + stubbedRequest.getMethod(), + assertingRequest.getMethod()); ANSITerminal.error(methodMatchFailed); LOGGER.error(methodMatchFailed); return false; } - final String methodMatchSuccess = String.format(MATCHED_ON_STUBBED + MSG_FIELD_METHOD + MSG_FIELDS_TEMPLATE, stubbedRequest.getMethod(), assertingRequest.getMethod()); + final String methodMatchSuccess = String.format( + MATCHED_ON_STUBBED + MSG_FIELD_METHOD + MSG_FIELDS_TEMPLATE, + stubbedRequest.getMethod(), + assertingRequest.getMethod()); ANSITerminal.info(methodMatchSuccess); LOGGER.info(methodMatchSuccess); } @@ -83,12 +110,18 @@ boolean matches(final StubRequest stubbedRequest, final StubRequest assertingReq // Match stubbed request body payload (POST, PUT & PATCH) if (stubbedRequest.isRequestBodyStubbed()) { if (!postBodiesMatch(stubbedRequest, assertingRequest)) { - final String bodyMatchFailed = String.format(FAILED_TO_MATCH_ON_STUBBED + MSG_FIELD_POST_BODY + MSG_FIELDS_TEMPLATE, stubbedRequest.getPostBody(), assertingRequest.getPostBody()); + final String bodyMatchFailed = String.format( + FAILED_TO_MATCH_ON_STUBBED + MSG_FIELD_POST_BODY + MSG_FIELDS_TEMPLATE, + stubbedRequest.getPostBody(), + assertingRequest.getPostBody()); ANSITerminal.error(bodyMatchFailed); LOGGER.error(bodyMatchFailed); return false; } - final String bodyMatchSuccess = String.format(MATCHED_ON_STUBBED + MSG_FIELD_POST_BODY + MSG_FIELDS_TEMPLATE, stubbedRequest.getPostBody(), assertingRequest.getPostBody()); + final String bodyMatchSuccess = String.format( + MATCHED_ON_STUBBED + MSG_FIELD_POST_BODY + MSG_FIELDS_TEMPLATE, + stubbedRequest.getPostBody(), + assertingRequest.getPostBody()); ANSITerminal.info(bodyMatchSuccess); LOGGER.info(bodyMatchSuccess); } @@ -96,12 +129,18 @@ boolean matches(final StubRequest stubbedRequest, final StubRequest assertingReq // Match stubbed request headers if (!stubbedRequest.getHeaders().isEmpty()) { if (!headersMatch(stubbedRequest.getHeaders(), assertingRequest.getHeaders())) { - final String headersMatchFailed = String.format(FAILED_TO_MATCH_ON_STUBBED + MSG_FIELD_HEADERS + MSG_FIELDS_TEMPLATE, stubbedRequest.getHeaders(), assertingRequest.getHeaders()); + final String headersMatchFailed = String.format( + FAILED_TO_MATCH_ON_STUBBED + MSG_FIELD_HEADERS + MSG_FIELDS_TEMPLATE, + stubbedRequest.getHeaders(), + assertingRequest.getHeaders()); ANSITerminal.error(headersMatchFailed); LOGGER.error(headersMatchFailed); return false; } - final String headersMatchSuccess = String.format(MATCHED_ON_STUBBED + MSG_FIELD_HEADERS + MSG_FIELDS_TEMPLATE, stubbedRequest.getHeaders(), assertingRequest.getHeaders()); + final String headersMatchSuccess = String.format( + MATCHED_ON_STUBBED + MSG_FIELD_HEADERS + MSG_FIELDS_TEMPLATE, + stubbedRequest.getHeaders(), + assertingRequest.getHeaders()); ANSITerminal.info(headersMatchSuccess); LOGGER.info(headersMatchSuccess); } @@ -109,12 +148,18 @@ boolean matches(final StubRequest stubbedRequest, final StubRequest assertingReq // Match stubbed request query params if (!stubbedRequest.getQuery().isEmpty()) { if (!queriesMatch(stubbedRequest.getQuery(), assertingRequest.getQuery())) { - final String uriQueryMatchFailed = String.format(FAILED_TO_MATCH_ON_STUBBED + MSG_FIELD_QUERY + MSG_FIELDS_TEMPLATE, stubbedRequest.getQuery(), assertingRequest.getQuery()); + final String uriQueryMatchFailed = String.format( + FAILED_TO_MATCH_ON_STUBBED + MSG_FIELD_QUERY + MSG_FIELDS_TEMPLATE, + stubbedRequest.getQuery(), + assertingRequest.getQuery()); ANSITerminal.error(uriQueryMatchFailed); LOGGER.error(uriQueryMatchFailed); return false; } - final String uriQueryMatchSuccess = String.format(MATCHED_ON_STUBBED + MSG_FIELD_QUERY + MSG_FIELDS_TEMPLATE, stubbedRequest.getQuery(), assertingRequest.getQuery()); + final String uriQueryMatchSuccess = String.format( + MATCHED_ON_STUBBED + MSG_FIELD_QUERY + MSG_FIELDS_TEMPLATE, + stubbedRequest.getQuery(), + assertingRequest.getQuery()); ANSITerminal.info(uriQueryMatchSuccess); LOGGER.info(uriQueryMatchSuccess); } @@ -173,7 +218,10 @@ private boolean headersMatch(final Map stubbedHeaders, final Map } @VisibleForTesting - boolean mapsMatch(final Map stubbedMappings, final Map assertingMappings, final String mapName) { + boolean mapsMatch( + final Map stubbedMappings, + final Map assertingMappings, + final String mapName) { if (stubbedMappings.isEmpty()) { return true; } else if (assertingMappings.isEmpty()) { @@ -230,7 +278,8 @@ boolean listsIntersect(final List stubbedArray, final List asser private boolean jsonMatch(final String stubbedJson, final String assertingJson, final String templateTokenName) { try { - final boolean passed = JSONCompare.compareJSON(stubbedJson, assertingJson, JSONCompareMode.NON_EXTENSIBLE).passed(); + final boolean passed = JSONCompare.compareJSON(stubbedJson, assertingJson, JSONCompareMode.NON_EXTENSIBLE) + .passed(); if (passed) { return true; } else { @@ -257,11 +306,9 @@ private boolean xmlMatch(final String stubbedXml, final String assertingXml, fin new Stubby4jMatchesRegexPlaceholderHandler(templateTokenName, this.regexGroups); final DifferenceEvaluator differenceEvaluatorChain = DifferenceEvaluators.chain( DifferenceEvaluators.Default, - new Stubby4jXmlUnitPlaceholderDifferenceEvaluator(matchesRegexPlaceholderHandler) - ); + new Stubby4jXmlUnitPlaceholderDifferenceEvaluator(matchesRegexPlaceholderHandler)); - final DiffBuilder xmlDiffBuilder = DiffBuilder - .compare(control) + final DiffBuilder xmlDiffBuilder = DiffBuilder.compare(control) .withTest(assertion) .withDifferenceEvaluator(differenceEvaluatorChain) .checkForSimilar() diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/StubRepository.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/StubRepository.java index 34a52e3e2..2e829adf8 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/StubRepository.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/StubRepository.java @@ -1,5 +1,37 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs; +import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_CONFIG; +import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_REQUEST; +import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_RESPONSE; +import static io.github.azagniotov.stubby4j.stubs.StubResponse.notFoundResponse; +import static io.github.azagniotov.stubby4j.stubs.StubResponse.unauthorizedResponse; +import static io.github.azagniotov.stubby4j.utils.CollectionUtils.constructParamMap; +import static io.github.azagniotov.stubby4j.utils.ConsoleUtils.logAssertingRequest; +import static io.github.azagniotov.stubby4j.utils.HandlerUtils.extractPostRequestBody; +import static io.github.azagniotov.stubby4j.utils.ObjectUtils.isNotNull; +import static io.github.azagniotov.stubby4j.utils.ReflectionUtils.injectObjectFields; +import static io.github.azagniotov.stubby4j.utils.StringUtils.isSet; +import static io.github.azagniotov.stubby4j.utils.StringUtils.toLower; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.BODY; +import static java.util.Collections.list; +import static org.eclipse.jetty.http.HttpStatus.getCode; + import io.github.azagniotov.stubby4j.caching.Cache; import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.client.StubbyResponse; @@ -11,11 +43,6 @@ import io.github.azagniotov.stubby4j.utils.StringUtils; import io.github.azagniotov.stubby4j.yaml.YamlParseResultSet; import io.github.azagniotov.stubby4j.yaml.YamlParser; -import org.eclipse.jetty.http.HttpStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -32,22 +59,10 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicLong; - -import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_CONFIG; -import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_REQUEST; -import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_RESPONSE; -import static io.github.azagniotov.stubby4j.stubs.StubResponse.notFoundResponse; -import static io.github.azagniotov.stubby4j.stubs.StubResponse.unauthorizedResponse; -import static io.github.azagniotov.stubby4j.utils.CollectionUtils.constructParamMap; -import static io.github.azagniotov.stubby4j.utils.ConsoleUtils.logAssertingRequest; -import static io.github.azagniotov.stubby4j.utils.HandlerUtils.extractPostRequestBody; -import static io.github.azagniotov.stubby4j.utils.ObjectUtils.isNotNull; -import static io.github.azagniotov.stubby4j.utils.ReflectionUtils.injectObjectFields; -import static io.github.azagniotov.stubby4j.utils.StringUtils.isSet; -import static io.github.azagniotov.stubby4j.utils.StringUtils.toLower; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.BODY; -import static java.util.Collections.list; -import static org.eclipse.jetty.http.HttpStatus.getCode; +import javax.servlet.http.HttpServletRequest; +import org.eclipse.jetty.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class StubRepository { private static final Logger LOGGER = LoggerFactory.getLogger(StubRepository.class); @@ -65,10 +80,11 @@ public class StubRepository { private final CompletableFuture stubLoadComputation; private final StubbyHttpTransport stubbyHttpTransport; - public StubRepository(final File configFile, - final Cache stubMatchesCache, - final CompletableFuture stubLoadComputation, - final StubbyHttpTransport stubbyHttpTransport) { + public StubRepository( + final File configFile, + final Cache stubMatchesCache, + final CompletableFuture stubLoadComputation, + final StubbyHttpTransport stubbyHttpTransport) { this.stubs = new ArrayList<>(); this.uuidToStub = new ConcurrentHashMap<>(); this.proxyConfigs = new ConcurrentHashMap<>(); @@ -80,14 +96,13 @@ public StubRepository(final File configFile, this.stubMatchesCache = stubMatchesCache; } - private static void logMatch(final String typeDescription, long elapsed, StubHttpLifecycle matched) { -// StringBuilder message = new StringBuilder() -// .append("Found a match after ") -// .append(elapsed) -// .append(" milliseconds URL [") -// .append(matched.getUrl()) -// .append("]"); + // StringBuilder message = new StringBuilder() + // .append("Found a match after ") + // .append(elapsed) + // .append(" milliseconds URL [") + // .append(matched.getUrl()) + // .append("]"); StringBuilder message = new StringBuilder() .append("Found a ") .append(typeDescription) @@ -95,9 +110,7 @@ private static void logMatch(final String typeDescription, long elapsed, StubHtt .append(elapsed) .append(" milliseconds"); if (isSet(matched.getDescription())) { - message.append(" Description [") - .append(matched.getDescription()) - .append("]"); + message.append(" Description [").append(matched.getDescription()).append("]"); } ANSITerminal.status(message.toString()); @@ -108,7 +121,9 @@ public StubSearchResult search(final HttpServletRequest incomingRequest) throws final StubRequest assertionStubRequest = this.toStubRequest(incomingRequest); logAssertingRequest(assertionStubRequest); - final StubResponse match = findMatch(new StubHttpLifecycle.Builder().withRequest(assertionStubRequest).build()); + final StubResponse match = findMatch(new StubHttpLifecycle.Builder() + .withRequest(assertionStubRequest) + .build()); return new StubSearchResult(assertionStubRequest, match); } @@ -126,7 +141,8 @@ public StubRequest toStubRequest(final HttpServletRequest request) throws IOExce .withMethod(request.getMethod()); final Enumeration headerNamesEnumeration = request.getHeaderNames(); - final List headerNames = isNotNull(headerNamesEnumeration) ? list(request.getHeaderNames()) : new LinkedList<>(); + final List headerNames = + isNotNull(headerNamesEnumeration) ? list(request.getHeaderNames()) : new LinkedList<>(); for (final String headerName : headerNames) { final String headerValue = request.getHeader(headerName); @@ -198,22 +214,24 @@ private synchronized Optional matchStub(final StubHttpLifecyc final String incomingRequestHashCode = String.valueOf(incomingStub.hashCode()); final Optional cachedMatchCandidateOptional = stubMatchesCache.get(incomingRequestHashCode); - //TODO BUG: When stubs are cached, upon finding the previously cached match by hashCode, + // TODO BUG: When stubs are cached, upon finding the previously cached match by hashCode, // if stubbed response has template tokens for dynamic token replacement, the tokens are // not replaced with values from the incoming request because the cached stub is not going // through the same matching process like upon the first match. Either fix this bug or just // deprecate the stub caching all together, as it is causing more headaches than not. // Also, deprecate the --disable_stub_caching command line flag if the caching has retired. - return cachedMatchCandidateOptional.map(cachedMatchCandidate -> { - ANSITerminal.loaded(String.format("Local cache contains a match for hashCode [%s]", incomingRequestHashCode)); - LOGGER.debug("Local cache contains a match for hashCode [{}].", incomingRequestHashCode); + return cachedMatchCandidateOptional + .map(cachedMatchCandidate -> { + ANSITerminal.loaded( + String.format("Local cache contains a match for hashCode [%s]", incomingRequestHashCode)); + LOGGER.debug("Local cache contains a match for hashCode [{}].", incomingRequestHashCode); - final long elapsed = System.currentTimeMillis() - initialStart; - logMatch("stubbed match in cache (i.e.: repeated request)", elapsed, cachedMatchCandidate); + final long elapsed = System.currentTimeMillis() - initialStart; + logMatch("stubbed match in cache (i.e.: repeated request)", elapsed, cachedMatchCandidate); - return Optional.of(cachedMatchCandidate); - - }).orElseGet(() -> matchAll(incomingStub, initialStart)); + return Optional.of(cachedMatchCandidate); + }) + .orElseGet(() -> matchAll(incomingStub, initialStart)); } private StubResponse proxyRequest(final StubHttpLifecycle incomingHttpLifecycle) { @@ -227,13 +245,16 @@ private StubResponse proxyRequest(final StubHttpLifecycle incomingHttpLifecycle) .getOrDefault(HEADER_X_STUBBY_PROXY_CONFIG, StubProxyConfig.Builder.DEFAULT_UUID); if (!proxyConfigs.containsKey(proxyConfigUuidHeader)) { - final String warning = String.format("Could not find proxy config by UUID using header value '%s', falling back to 'default'", proxyConfigUuidHeader); + final String warning = String.format( + "Could not find proxy config by UUID using header value '%s', falling back to 'default'", + proxyConfigUuidHeader); ANSITerminal.warn(warning); LOGGER.warn(warning); } final StubProxyConfig proxyConfig = proxyConfigs.getOrDefault(proxyConfigUuidHeader, catchAllProxyConfig); - final String proxyEndpoint = String.format("%s%s", proxyConfig.getPropertyEndpoint(), incomingHttpLifecycle.getUrl()); + final String proxyEndpoint = + String.format("%s%s", proxyConfig.getPropertyEndpoint(), incomingHttpLifecycle.getUrl()); final String proxyRoundTripUuid = UUID.randomUUID().toString(); final Map proxyResponseFlatHeaders = new HashMap<>(); @@ -244,8 +265,10 @@ private StubResponse proxyRequest(final StubHttpLifecycle incomingHttpLifecycle) handleIfAdditiveProxyStrategy(incomingRequest, proxyConfig); - final StubbyResponse stubbyResponse = stubbyHttpTransport.httpRequestFromStub(incomingRequest, proxyEndpoint); - for (Map.Entry> entry : stubbyResponse.headers().entrySet()) { + final StubbyResponse stubbyResponse = + stubbyHttpTransport.httpRequestFromStub(incomingRequest, proxyEndpoint); + for (Map.Entry> entry : + stubbyResponse.headers().entrySet()) { final String headerName = ObjectUtils.isNull(entry.getKey()) ? "null" : entry.getKey(); if (entry.getValue().size() == 1) { proxyResponseFlatHeaders.put(headerName, entry.getValue().get(0)); @@ -275,17 +298,20 @@ private StubResponse proxyRequest(final StubHttpLifecycle incomingHttpLifecycle) private void handleIfAdditiveProxyStrategy(final StubRequest incomingRequest, final StubProxyConfig proxyConfig) { if (proxyConfig.isAdditiveStrategy()) { if (proxyConfig.hasHeaders()) { - for (final Map.Entry headerEntry : proxyConfig.getHeaders().entrySet()) { + for (final Map.Entry headerEntry : + proxyConfig.getHeaders().entrySet()) { incomingRequest.getHeaders().put(headerEntry.getKey(), headerEntry.getValue()); } } } } - private void recordResponse(StubHttpLifecycle incomingRequest, StubHttpLifecycle matchedStub, StubResponse matchedStubResponse) { + private void recordResponse( + StubHttpLifecycle incomingRequest, StubHttpLifecycle matchedStub, StubResponse matchedStubResponse) { final String recordingSource = String.format("%s%s", matchedStubResponse.getBody(), incomingRequest.getUrl()); try { - final StubbyResponse stubbyResponse = stubbyHttpTransport.httpRequestFromStub(matchedStub.getRequest(), recordingSource); + final StubbyResponse stubbyResponse = + stubbyHttpTransport.httpRequestFromStub(matchedStub.getRequest(), recordingSource); injectObjectFields(matchedStubResponse, BODY.toString(), stubbyResponse.body()); } catch (Exception e) { ANSITerminal.error(String.format("Could not record from %s: %s", recordingSource, e.toString())); @@ -300,7 +326,8 @@ private Optional matchAll(final StubHttpLifecycle incomingStu logMatch("stubbed match", elapsed, stubbed); final String incomingRequestHashCode = String.valueOf(incomingStub.hashCode()); - // ANSITerminal.status(String.format("Caching the found match for hashCode [%s]", incomingRequestHashCode)); + // ANSITerminal.status(String.format("Caching the found match for hashCode [%s]", + // incomingRequestHashCode)); // LOGGER.debug("Caching the found match for hashCode [{}].", incomingRequestHashCode); stubMatchesCache.putIfAbsent(incomingRequestHashCode, stubbed); @@ -351,11 +378,13 @@ public synchronized void refreshStubsFromYamlConfig(final YamlParser yamlParser) resetStubsCache(yamlParser.parse(this.configFile.getParent(), configFile)); } - public synchronized void refreshStubsByPost(final YamlParser yamlParser, final String postPayload) throws Exception { + public synchronized void refreshStubsByPost(final YamlParser yamlParser, final String postPayload) + throws Exception { resetStubsCache(yamlParser.parse(this.configFile.getParent(), postPayload)); } - public synchronized String refreshStubByIndex(final YamlParser yamlParser, final String putPayload, final int index) throws Exception { + public synchronized String refreshStubByIndex(final YamlParser yamlParser, final String putPayload, final int index) + throws Exception { final YamlParseResultSet yamlParseResultSet = yamlParser.parse(this.configFile.getParent(), putPayload); final StubHttpLifecycle newStub = yamlParseResultSet.getStubs().get(0); updateStubByIndex(index, newStub); @@ -363,7 +392,8 @@ public synchronized String refreshStubByIndex(final YamlParser yamlParser, final return newStub.getUrl(); } - public synchronized String refreshStubByUuid(final YamlParser yamlParser, final String putPayload, final String uuid) throws Exception { + public synchronized String refreshStubByUuid( + final YamlParser yamlParser, final String putPayload, final String uuid) throws Exception { final YamlParseResultSet yamlParseResultSet = yamlParser.parse(this.configFile.getParent(), putPayload); final StubHttpLifecycle newStub = yamlParseResultSet.getStubs().get(0); updateStubByUuid(uuid, newStub); @@ -371,9 +401,11 @@ public synchronized String refreshStubByUuid(final YamlParser yamlParser, final return newStub.getUrl(); } - public synchronized String refreshProxyConfigByUuid(final YamlParser yamlParser, final String putPayload, final String uuid) throws Exception { + public synchronized String refreshProxyConfigByUuid( + final YamlParser yamlParser, final String putPayload, final String uuid) throws Exception { final YamlParseResultSet yamlParseResultSet = yamlParser.parse(this.configFile.getParent(), putPayload); - final StubProxyConfig newStubProxyConfig = yamlParseResultSet.getProxyConfigs().get(uuid); + final StubProxyConfig newStubProxyConfig = + yamlParseResultSet.getProxyConfigs().get(uuid); updateProxyConfigByUuid(uuid, newStubProxyConfig); return newStubProxyConfig.getPropertyEndpoint(); @@ -394,7 +426,11 @@ public ConcurrentHashMap getResourceStats() { } public String getResourceStatsAsCsv() { - final String csvNoHeader = resourceStats.toString().replaceAll("\\{|\\}", "").replaceAll(", ", FileUtils.BR).replaceAll("=", ","); + final String csvNoHeader = resourceStats + .toString() + .replaceAll("\\{|\\}", "") + .replaceAll(", ", FileUtils.BR) + .replaceAll("=", ","); return String.format("resourceId,hits%s%s", FileUtils.BR, csvNoHeader); } @@ -428,7 +464,6 @@ private void cacheExternalFile(final Set escrow, final Map e } } - public String getYamlConfigCanonicalPath() { try { return this.configFile.getCanonicalPath(); @@ -442,7 +477,9 @@ public synchronized String dumpCompleteYamlConfig() { if (!proxyConfigs.isEmpty()) { for (final Map.Entry entry : proxyConfigs.entrySet()) { - builder.append(entry.getValue().getProxyConfigAsYAML()).append(FileUtils.BR).append(FileUtils.BR); + builder.append(entry.getValue().getProxyConfigAsYAML()) + .append(FileUtils.BR) + .append(FileUtils.BR); } builder.append(FileUtils.BR); } @@ -480,7 +517,8 @@ public synchronized boolean canMatchProxyConfigByUuid(final String uuid) { synchronized void updateProxyConfigByUuid(final String uuid, final StubProxyConfig newStubProxyConfig) { if (!uuid.equals(newStubProxyConfig.getUUID())) { - final String message = String.format("Provided proxy config UUID '%s' does not match the target UUID '%s'", + final String message = String.format( + "Provided proxy config UUID '%s' does not match the target UUID '%s'", newStubProxyConfig.getUUID(), uuid); throw new IllegalArgumentException(message); } @@ -574,7 +612,8 @@ private void loadProxyConfigsWithOptionalThrow(final YamlParseResultSet yamlPars final Map loadedProxyConfigs = yamlParseResultSet.getProxyConfigs(); if (!loadedProxyConfigs.isEmpty() && !loadedProxyConfigs.containsKey(StubProxyConfig.Builder.DEFAULT_UUID)) { - throw new IllegalStateException("YAML config contains proxy configs, but the 'default' proxy config is not configured, how so?"); + throw new IllegalStateException( + "YAML config contains proxy configs, but the 'default' proxy config is not configured, how so?"); } this.proxyConfigs.putAll(loadedProxyConfigs); diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/StubRequest.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/StubRequest.java index 936f452c8..d38eff0db 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/StubRequest.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/StubRequest.java @@ -1,23 +1,20 @@ -package io.github.azagniotov.stubby4j.stubs; - -import io.github.azagniotov.stubby4j.annotations.VisibleForTesting; -import io.github.azagniotov.stubby4j.common.Common; -import io.github.azagniotov.stubby4j.http.HttpMethodExtended; -import io.github.azagniotov.stubby4j.utils.CollectionUtils; -import io.github.azagniotov.stubby4j.utils.FileUtils; -import io.github.azagniotov.stubby4j.utils.ObjectUtils; -import io.github.azagniotov.stubby4j.utils.StringUtils; -import io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty; -import org.eclipse.jetty.http.HttpMethod; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; +package io.github.azagniotov.stubby4j.stubs; import static io.github.azagniotov.generics.TypeSafeConverter.asCheckedArrayList; import static io.github.azagniotov.generics.TypeSafeConverter.asCheckedLinkedHashMap; @@ -37,6 +34,23 @@ import static java.lang.String.valueOf; import static java.util.stream.Collectors.toCollection; +import io.github.azagniotov.stubby4j.annotations.VisibleForTesting; +import io.github.azagniotov.stubby4j.common.Common; +import io.github.azagniotov.stubby4j.http.HttpMethodExtended; +import io.github.azagniotov.stubby4j.utils.CollectionUtils; +import io.github.azagniotov.stubby4j.utils.FileUtils; +import io.github.azagniotov.stubby4j.utils.ObjectUtils; +import io.github.azagniotov.stubby4j.utils.StringUtils; +import io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import org.eclipse.jetty.http.HttpMethod; public class StubRequest implements ReflectableStub { @@ -51,16 +65,17 @@ public class StubRequest implements ReflectableStub { private final Map query; private final Map regexGroups; - private StubRequest(final String url, - final String post, - final File file, - final List method, - final Map headers, - final Map query) { + private StubRequest( + final String url, + final String post, + final File file, + final List method, + final Map headers, + final Map query) { this.url = url; this.post = post; this.file = file; - this.fileBytes = ObjectUtils.isNull(file) ? new byte[]{} : getFileBytes(); + this.fileBytes = ObjectUtils.isNull(file) ? new byte[] {} : getFileBytes(); this.method = method; this.headers = headers; this.query = query; @@ -94,7 +109,7 @@ private byte[] getFileBytes() { try { return FileUtils.fileToBytes(file); } catch (Exception e) { - return new byte[]{}; + return new byte[] {}; } } @@ -106,7 +121,7 @@ public String getPostBody() { return FileUtils.enforceSystemLineSeparator(utf8FileContent); } - //Used by reflection when populating stubby admin page with stubbed information + // Used by reflection when populating stubby admin page with stubbed information public String getPost() { return post; } @@ -152,9 +167,9 @@ public boolean hasPostBody() { } boolean isSecured() { - return getHeaders().containsKey(BASIC.asYAMLProp()) || - getHeaders().containsKey(BEARER.asYAMLProp()) || - getHeaders().containsKey(CUSTOM.asYAMLProp()); + return getHeaders().containsKey(BASIC.asYAMLProp()) + || getHeaders().containsKey(BEARER.asYAMLProp()) + || getHeaders().containsKey(CUSTOM.asYAMLProp()); } @VisibleForTesting @@ -178,10 +193,10 @@ public String getRawHeaderAuthorization() { @VisibleForTesting boolean isRequestBodyStubbed() { - return isSet(this.getPostBody()) && - (getMethod().contains(HttpMethod.POST.asString()) || - getMethod().contains(HttpMethod.PUT.asString()) || - getMethod().contains(HttpMethodExtended.PATCH.asString())); + return isSet(this.getPostBody()) + && (getMethod().contains(HttpMethod.POST.asString()) + || getMethod().contains(HttpMethod.PUT.asString()) + || getMethod().contains(HttpMethodExtended.PATCH.asString())); } @VisibleForTesting @@ -222,7 +237,6 @@ public boolean equals(final Object that) { } @Override - public int hashCode() { int result = (isNotNull(url) ? url.hashCode() : 0); result = 31 * result + method.hashCode(); @@ -235,7 +249,6 @@ public int hashCode() { } @Override - public final String toString() { final StringBuilder sb = new StringBuilder(); sb.append("StubRequest"); diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/StubResponse.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/StubResponse.java index a50fabdbf..2fb318fc3 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/StubResponse.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/StubResponse.java @@ -1,15 +1,20 @@ -package io.github.azagniotov.stubby4j.stubs; - -import io.github.azagniotov.stubby4j.annotations.VisibleForTesting; -import io.github.azagniotov.stubby4j.common.Common; -import io.github.azagniotov.stubby4j.utils.FileUtils; -import io.github.azagniotov.stubby4j.utils.StringUtils; -import io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty; -import org.eclipse.jetty.http.HttpStatus.Code; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import java.io.File; -import java.util.LinkedHashMap; -import java.util.Map; +package io.github.azagniotov.stubby4j.stubs; import static io.github.azagniotov.generics.TypeSafeConverter.asCheckedLinkedHashMap; import static io.github.azagniotov.stubby4j.utils.FileUtils.fileToBytes; @@ -23,6 +28,15 @@ import static java.lang.Integer.parseInt; import static org.eclipse.jetty.http.HttpStatus.getCode; +import io.github.azagniotov.stubby4j.annotations.VisibleForTesting; +import io.github.azagniotov.stubby4j.common.Common; +import io.github.azagniotov.stubby4j.utils.FileUtils; +import io.github.azagniotov.stubby4j.utils.StringUtils; +import io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty; +import java.io.File; +import java.util.LinkedHashMap; +import java.util.Map; +import org.eclipse.jetty.http.HttpStatus.Code; public class StubResponse implements ReflectableStub { @@ -33,15 +47,16 @@ public class StubResponse implements ReflectableStub { private final String latency; private final Map headers; - private StubResponse(final Code httpStatusCode, - final String body, - final File file, - final String latency, - final Map headers) { + private StubResponse( + final Code httpStatusCode, + final String body, + final File file, + final String latency, + final Map headers) { this.httpStatusCode = httpStatusCode; this.body = body; this.file = file; - this.fileBytes = isNull(file) ? new byte[]{} : getFileBytes(); + this.fileBytes = isNull(file) ? new byte[] {} : getFileBytes(); this.latency = latency; this.headers = isNull(headers) ? new LinkedHashMap<>() : headers; } @@ -117,7 +132,6 @@ public boolean isFilePathContainsTemplateTokens() { } } - private boolean isTemplateFile() { try { return FileUtils.isTemplateFile(file); @@ -126,12 +140,11 @@ private boolean isTemplateFile() { } } - private byte[] getFileBytes() { try { return fileToBytes(file); } catch (Exception e) { - return new byte[]{}; + return new byte[] {}; } } diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/StubSearchResult.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/StubSearchResult.java index 5348b41ae..794c66c74 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/StubSearchResult.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/StubSearchResult.java @@ -1,5 +1,20 @@ -package io.github.azagniotov.stubby4j.stubs; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.azagniotov.stubby4j.stubs; public class StubSearchResult { diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/StubTypes.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/StubTypes.java index 7c963df32..e3ef967d9 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/StubTypes.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/StubTypes.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs; public enum StubTypes { diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/StubbableAuthorizationType.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/StubbableAuthorizationType.java index a5fbe6196..d356c7159 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/StubbableAuthorizationType.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/StubbableAuthorizationType.java @@ -1,9 +1,24 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs; import io.github.azagniotov.stubby4j.utils.StringUtils; public enum StubbableAuthorizationType { - BASIC("Basic"), BEARER("Bearer"), CUSTOM("Custom"); diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/matching/Stubby4jMatchesRegexPlaceholderHandler.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/matching/Stubby4jMatchesRegexPlaceholderHandler.java index 839aa1ded..5270c30eb 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/matching/Stubby4jMatchesRegexPlaceholderHandler.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/matching/Stubby4jMatchesRegexPlaceholderHandler.java @@ -1,32 +1,34 @@ /* - This file is licensed to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ package io.github.azagniotov.stubby4j.stubs.matching; -import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; -import org.xmlunit.XMLUnitException; -import org.xmlunit.diff.ComparisonResult; -import org.xmlunit.placeholder.PlaceholderHandler; +import static io.github.azagniotov.stubby4j.utils.StringUtils.buildToken; +import static org.xmlunit.diff.ComparisonResult.DIFFERENT; +import static org.xmlunit.diff.ComparisonResult.EQUAL; +import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; - -import static io.github.azagniotov.stubby4j.utils.StringUtils.buildToken; -import static org.xmlunit.diff.ComparisonResult.DIFFERENT; -import static org.xmlunit.diff.ComparisonResult.EQUAL; +import org.xmlunit.XMLUnitException; +import org.xmlunit.diff.ComparisonResult; +import org.xmlunit.placeholder.PlaceholderHandler; /** * Handler for the {@code matchesRegex()} placeholder keyword. @@ -40,7 +42,8 @@ public class Stubby4jMatchesRegexPlaceholderHandler implements PlaceholderHandle private final Map stubbedRequestRegexGroups; private AtomicInteger contentRegexGroupCounter; - public Stubby4jMatchesRegexPlaceholderHandler(final String templateTokenName, final Map stubbedRequestRegexGroups) { + public Stubby4jMatchesRegexPlaceholderHandler( + final String templateTokenName, final Map stubbedRequestRegexGroups) { this.templateTokenName = templateTokenName; this.stubbedRequestRegexGroups = stubbedRequestRegexGroups; this.contentRegexGroupCounter = new AtomicInteger(1); diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/matching/Stubby4jXmlUnitPlaceholderDifferenceEvaluator.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/matching/Stubby4jXmlUnitPlaceholderDifferenceEvaluator.java index bd687b95f..ac1f42972 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/matching/Stubby4jXmlUnitPlaceholderDifferenceEvaluator.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/matching/Stubby4jXmlUnitPlaceholderDifferenceEvaluator.java @@ -1,19 +1,27 @@ /* - This file is licensed to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs.matching; import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.xml.namespace.QName; import org.w3c.dom.Node; import org.xmlunit.diff.Comparison; import org.xmlunit.diff.ComparisonResult; @@ -26,12 +34,6 @@ import org.xmlunit.placeholder.PlaceholderHandler; import org.xmlunit.util.Nodes; -import javax.xml.namespace.QName; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - /** * This class has been adopted from the awesome library XMLUnit and tweaked in order * to allow setting a custom {@link MatchesRegexPlaceholderHandler}. @@ -119,8 +121,8 @@ public Stubby4jXmlUnitPlaceholderDifferenceEvaluator(final PlaceholderHandler pl * Stubby4jXmlUnitPlaceholderDifferenceEvaluator#PLACEHOLDER_DEFAULT_CLOSING_DELIMITER_REGEX} * if the parameter is null or blank */ - public Stubby4jXmlUnitPlaceholderDifferenceEvaluator(final String placeholderOpeningDelimiterRegex, - final String placeholderClosingDelimiterRegex) { + public Stubby4jXmlUnitPlaceholderDifferenceEvaluator( + final String placeholderOpeningDelimiterRegex, final String placeholderClosingDelimiterRegex) { this(placeholderOpeningDelimiterRegex, placeholderClosingDelimiterRegex, null, null, null); } @@ -150,11 +152,12 @@ public Stubby4jXmlUnitPlaceholderDifferenceEvaluator(final String placeholderOpe * if the parameter is null or blank * @since 2.7.0 */ - public Stubby4jXmlUnitPlaceholderDifferenceEvaluator(String placeholderOpeningDelimiterRegex, - String placeholderClosingDelimiterRegex, - String placeholderArgsOpeningDelimiterRegex, - String placeholderArgsClosingDelimiterRegex, - String placeholderArgsSeparatorRegex) { + public Stubby4jXmlUnitPlaceholderDifferenceEvaluator( + String placeholderOpeningDelimiterRegex, + String placeholderClosingDelimiterRegex, + String placeholderArgsOpeningDelimiterRegex, + String placeholderArgsClosingDelimiterRegex, + String placeholderArgsSeparatorRegex) { this.placeholderHandlers = new HashMap<>(); @@ -200,8 +203,8 @@ public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome // comparing textual content of elements if (comparison.getType() == ComparisonType.TEXT_VALUE) { - return evaluateConsideringPlaceholders((String) controlDetails.getValue(), - (String) testDetails.getValue(), outcome); + return evaluateConsideringPlaceholders( + (String) controlDetails.getValue(), (String) testDetails.getValue(), outcome); // "test document has no text-like child node but control document has" } else if (isMissingTextNodeDifference(comparison)) { @@ -213,8 +216,8 @@ public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome // comparing textual content of attributes } else if (comparison.getType() == ComparisonType.ATTR_VALUE) { - return evaluateConsideringPlaceholders((String) controlDetails.getValue(), - (String) testDetails.getValue(), outcome); + return evaluateConsideringPlaceholders( + (String) controlDetails.getValue(), (String) testDetails.getValue(), outcome); // "test document has no attribute but control document has" } else if (isMissingAttributeDifference(comparison)) { @@ -227,27 +230,28 @@ public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome } private boolean isMissingTextNodeDifference(Comparison comparison) { - return controlHasOneTextChildAndTestHasNone(comparison) - || cantFindControlTextChildInTest(comparison); + return controlHasOneTextChildAndTestHasNone(comparison) || cantFindControlTextChildInTest(comparison); } private boolean controlHasOneTextChildAndTestHasNone(Comparison comparison) { Comparison.Detail controlDetails = comparison.getControlDetails(); Node controlTarget = controlDetails.getTarget(); Comparison.Detail testDetails = comparison.getTestDetails(); - return comparison.getType() == ComparisonType.CHILD_NODELIST_LENGTH && - Integer.valueOf(1).equals(controlDetails.getValue()) && - Integer.valueOf(0).equals(testDetails.getValue()) && - isTextLikeNode(controlTarget.getFirstChild()); + return comparison.getType() == ComparisonType.CHILD_NODELIST_LENGTH + && Integer.valueOf(1).equals(controlDetails.getValue()) + && Integer.valueOf(0).equals(testDetails.getValue()) + && isTextLikeNode(controlTarget.getFirstChild()); } private boolean cantFindControlTextChildInTest(Comparison comparison) { Node controlTarget = comparison.getControlDetails().getTarget(); return comparison.getType() == ComparisonType.CHILD_LOOKUP - && controlTarget != null && isTextLikeNode(controlTarget); + && controlTarget != null + && isTextLikeNode(controlTarget); } - private ComparisonResult evaluateMissingTextNodeConsideringPlaceholders(Comparison comparison, ComparisonResult outcome) { + private ComparisonResult evaluateMissingTextNodeConsideringPlaceholders( + Comparison comparison, ComparisonResult outcome) { Node controlTarget = comparison.getControlDetails().getTarget(); String value; if (controlHasOneTextChildAndTestHasNone(comparison)) { @@ -272,23 +276,27 @@ private boolean isTextLikeNode(Node node) { private boolean isMissingAttributeDifference(Comparison comparison) { return comparison.getType() == ComparisonType.ELEMENT_NUM_ATTRIBUTES || (comparison.getType() == ComparisonType.ATTR_NAME_LOOKUP - && comparison.getControlDetails().getTarget() != null - && comparison.getControlDetails().getValue() != null); + && comparison.getControlDetails().getTarget() != null + && comparison.getControlDetails().getValue() != null); } - private ComparisonResult evaluateMissingAttributeConsideringPlaceholders(Comparison comparison, ComparisonResult outcome) { + private ComparisonResult evaluateMissingAttributeConsideringPlaceholders( + Comparison comparison, ComparisonResult outcome) { if (comparison.getType() == ComparisonType.ELEMENT_NUM_ATTRIBUTES) { return evaluateAttributeListLengthConsideringPlaceholders(comparison, outcome); } - String controlAttrValue = Nodes.getAttributes(comparison.getControlDetails().getTarget()) + String controlAttrValue = Nodes.getAttributes( + comparison.getControlDetails().getTarget()) .get((QName) comparison.getControlDetails().getValue()); return evaluateConsideringPlaceholders(controlAttrValue, null, outcome); } - private ComparisonResult evaluateAttributeListLengthConsideringPlaceholders(Comparison comparison, - ComparisonResult outcome) { - Map controlAttrs = Nodes.getAttributes(comparison.getControlDetails().getTarget()); - Map testAttrs = Nodes.getAttributes(comparison.getTestDetails().getTarget()); + private ComparisonResult evaluateAttributeListLengthConsideringPlaceholders( + Comparison comparison, ComparisonResult outcome) { + Map controlAttrs = + Nodes.getAttributes(comparison.getControlDetails().getTarget()); + Map testAttrs = + Nodes.getAttributes(comparison.getTestDetails().getTarget()); int cAttrsMatched = 0; for (Map.Entry cAttr : controlAttrs.entrySet()) { @@ -309,8 +317,8 @@ private ComparisonResult evaluateAttributeListLengthConsideringPlaceholders(Comp return ComparisonResult.EQUAL; } - private ComparisonResult evaluateConsideringPlaceholders(String controlText, String testText, - ComparisonResult outcome) { + private ComparisonResult evaluateConsideringPlaceholders( + String controlText, String testText, ComparisonResult outcome) { final Matcher placeholderMatcher = placeholderRegex.matcher(controlText); if (placeholderMatcher.find()) { final String content = placeholderMatcher.group(2).trim(); diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/proxy/StubProxyConfig.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/proxy/StubProxyConfig.java index a2f93dfd4..262fa5920 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/proxy/StubProxyConfig.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/proxy/StubProxyConfig.java @@ -1,23 +1,38 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs.proxy; +import static io.github.azagniotov.generics.TypeSafeConverter.asCheckedLinkedHashMap; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.DESCRIPTION; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.ENDPOINT; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.HEADERS; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.PROPERTIES; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.STRATEGY; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.UUID; + import io.github.azagniotov.stubby4j.stubs.AbstractBuilder; import io.github.azagniotov.stubby4j.stubs.ReflectableStub; import io.github.azagniotov.stubby4j.utils.ReflectionUtils; import io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty; - import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; -import static io.github.azagniotov.generics.TypeSafeConverter.asCheckedLinkedHashMap; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.DESCRIPTION; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.ENDPOINT; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.HEADERS; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.PROPERTIES; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.STRATEGY; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.UUID; - public class StubProxyConfig implements ReflectableStub { private final String description; @@ -27,12 +42,13 @@ public class StubProxyConfig implements ReflectableStub { private final Map properties; private final String proxyConfigAsYAML; - private StubProxyConfig(final String description, - final String uuid, - final StubProxyStrategy strategy, - final Map headers, - final Map properties, - final String proxyConfigAsYAML) { + private StubProxyConfig( + final String description, + final String uuid, + final StubProxyStrategy strategy, + final Map headers, + final Map properties, + final String proxyConfigAsYAML) { this.description = description; this.uuid = uuid; this.strategy = strategy; @@ -86,10 +102,10 @@ public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof StubProxyConfig)) return false; StubProxyConfig that = (StubProxyConfig) o; - return Objects.equals(uuid, that.uuid) && - strategy == that.strategy && - headers.equals(that.headers) && - properties.equals(that.properties); + return Objects.equals(uuid, that.uuid) + && strategy == that.strategy + && headers.equals(that.headers) + && properties.equals(that.properties); } @Override @@ -166,15 +182,11 @@ public StubProxyConfig build() { this.uuid = getStaged(String.class, UUID, uuid); this.strategy = getStaged(StubProxyStrategy.class, STRATEGY, strategy); this.headers = asCheckedLinkedHashMap(getStaged(Map.class, HEADERS, headers), String.class, String.class); - this.properties = asCheckedLinkedHashMap(getStaged(Map.class, PROPERTIES, properties), String.class, String.class); - - final StubProxyConfig stubProxyConfig = new StubProxyConfig( - description, - uuid, - strategy, - headers, - properties, - proxyConfigAsYAML); + this.properties = + asCheckedLinkedHashMap(getStaged(Map.class, PROPERTIES, properties), String.class, String.class); + + final StubProxyConfig stubProxyConfig = + new StubProxyConfig(description, uuid, strategy, headers, properties, proxyConfigAsYAML); reset(); diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/proxy/StubProxyStrategy.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/proxy/StubProxyStrategy.java index 128ef8b7b..bad2b5dfb 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/proxy/StubProxyStrategy.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/proxy/StubProxyStrategy.java @@ -1,12 +1,28 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs.proxy; +import static io.github.azagniotov.stubby4j.utils.StringUtils.toLower; + import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Optional; -import static io.github.azagniotov.stubby4j.utils.StringUtils.toLower; - public enum StubProxyStrategy { /** * No changes/modifications will be applied to the request before proxying it. diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketClientRequest.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketClientRequest.java index fe04b6c62..e70a00ada 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketClientRequest.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketClientRequest.java @@ -1,5 +1,26 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs.websocket; +import static io.github.azagniotov.stubby4j.utils.StringUtils.newStringUtf8; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.BODY; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.FILE; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.MESSAGE_TYPE; + import io.github.azagniotov.stubby4j.annotations.GeneratedCodeMethodCoverageExclusion; import io.github.azagniotov.stubby4j.stubs.AbstractBuilder; import io.github.azagniotov.stubby4j.stubs.ReflectableStub; @@ -7,16 +28,10 @@ import io.github.azagniotov.stubby4j.utils.ObjectUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; import io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty; - import java.io.File; import java.util.Arrays; import java.util.Objects; -import static io.github.azagniotov.stubby4j.utils.StringUtils.newStringUtf8; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.BODY; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.FILE; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.MESSAGE_TYPE; - public class StubWebSocketClientRequest implements ReflectableStub { private final StubWebSocketMessageType messageType; @@ -25,14 +40,15 @@ public class StubWebSocketClientRequest implements ReflectableStub { private final byte[] fileBytes; private final String webSocketClientRequestAsYAML; - private StubWebSocketClientRequest(final StubWebSocketMessageType messageType, - final String body, - final File file, - final String webSocketClientRequestAsYAML) { + private StubWebSocketClientRequest( + final StubWebSocketMessageType messageType, + final String body, + final File file, + final String webSocketClientRequestAsYAML) { this.messageType = messageType; this.body = body; this.file = file; - this.fileBytes = ObjectUtils.isNull(file) ? new byte[]{} : getFileBytes(); + this.fileBytes = ObjectUtils.isNull(file) ? new byte[] {} : getFileBytes(); this.webSocketClientRequestAsYAML = webSocketClientRequestAsYAML; } @@ -67,7 +83,7 @@ private byte[] getFileBytes() { try { return FileUtils.fileToBytes(file); } catch (Exception e) { - return new byte[]{}; + return new byte[] {}; } } @@ -77,10 +93,10 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StubWebSocketClientRequest that = (StubWebSocketClientRequest) o; - return messageType == that.messageType && - body.equals(that.body) && - file.equals(that.file) && - Arrays.equals(fileBytes, that.fileBytes); + return messageType == that.messageType + && body.equals(that.body) + && file.equals(that.file) + && Arrays.equals(fileBytes, that.fileBytes); } @Override @@ -140,11 +156,8 @@ public StubWebSocketClientRequest build() { this.file = getStaged(File.class, FILE, file); this.messageType = getStaged(StubWebSocketMessageType.class, MESSAGE_TYPE, messageType); - final StubWebSocketClientRequest webSocketClientRequest = new StubWebSocketClientRequest( - messageType, - body, - file, - webSocketClientRequestAsYAML); + final StubWebSocketClientRequest webSocketClientRequest = + new StubWebSocketClientRequest(messageType, body, file, webSocketClientRequestAsYAML); reset(); diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketConfig.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketConfig.java index 692b9c514..b9e7e2ed2 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketConfig.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketConfig.java @@ -1,24 +1,39 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs.websocket; +import static io.github.azagniotov.stubby4j.utils.StringUtils.splitCsv; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.DESCRIPTION; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.ON_OPEN_SERVER_RESPONSE; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.SUB_PROTOCOLS; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.URL; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.UUID; + import io.github.azagniotov.stubby4j.annotations.GeneratedCodeMethodCoverageExclusion; import io.github.azagniotov.stubby4j.stubs.AbstractBuilder; import io.github.azagniotov.stubby4j.stubs.ReflectableStub; import io.github.azagniotov.stubby4j.utils.ReflectionUtils; import io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty; - import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; -import static io.github.azagniotov.stubby4j.utils.StringUtils.splitCsv; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.DESCRIPTION; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.ON_OPEN_SERVER_RESPONSE; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.SUB_PROTOCOLS; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.URL; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.UUID; - public class StubWebSocketConfig implements ReflectableStub { private final String uuid; @@ -29,13 +44,14 @@ public class StubWebSocketConfig implements ReflectableStub { private final List onMessageLifeCycles; private final String webSocketConfigAsYAML; - private StubWebSocketConfig(final String uuid, - final String description, - final String url, - final Set subProtocols, - final StubWebSocketServerResponse onOpenServerResponse, - final List onMessageLifeCycles, - final String webSocketConfigAsYAML) { + private StubWebSocketConfig( + final String uuid, + final String description, + final String url, + final Set subProtocols, + final StubWebSocketServerResponse onOpenServerResponse, + final List onMessageLifeCycles, + final String webSocketConfigAsYAML) { this.uuid = uuid; this.description = description; this.url = url; @@ -83,12 +99,12 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StubWebSocketConfig that = (StubWebSocketConfig) o; - return uuid.equals(that.uuid) && - description.equals(that.description) && - subProtocols.equals(that.subProtocols) && - url.equals(that.url) && - onOpenServerResponse.equals(that.onOpenServerResponse) && - onMessageLifeCycles.equals(that.onMessageLifeCycles); + return uuid.equals(that.uuid) + && description.equals(that.description) + && subProtocols.equals(that.subProtocols) + && url.equals(that.url) + && onOpenServerResponse.equals(that.onOpenServerResponse) + && onMessageLifeCycles.equals(that.onMessageLifeCycles); } @Override @@ -165,7 +181,8 @@ public StubWebSocketConfig build() { this.uuid = getStaged(String.class, UUID, uuid); this.url = getStaged(String.class, URL, url); this.subProtocols = getStaged(String.class, SUB_PROTOCOLS, subProtocols); - this.onOpenServerResponse = getStaged(StubWebSocketServerResponse.class, ON_OPEN_SERVER_RESPONSE, onOpenServerResponse); + this.onOpenServerResponse = + getStaged(StubWebSocketServerResponse.class, ON_OPEN_SERVER_RESPONSE, onOpenServerResponse); final StubWebSocketConfig stubWebSocketConfig = new StubWebSocketConfig( uuid, diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketMessageType.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketMessageType.java index 5f139eb3d..c3f9871f2 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketMessageType.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketMessageType.java @@ -1,14 +1,29 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs.websocket; +import static io.github.azagniotov.stubby4j.utils.StringUtils.toLower; + import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Optional; -import static io.github.azagniotov.stubby4j.utils.StringUtils.toLower; - public enum StubWebSocketMessageType { - TEXT("text"), BINARY("binary"); diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketOnMessageLifeCycle.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketOnMessageLifeCycle.java index 288a83b1b..0d6a0a54a 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketOnMessageLifeCycle.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketOnMessageLifeCycle.java @@ -1,8 +1,23 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs.websocket; import io.github.azagniotov.stubby4j.annotations.GeneratedCodeMethodCoverageExclusion; import io.github.azagniotov.stubby4j.stubs.ReflectableStub; - import java.util.Objects; public class StubWebSocketOnMessageLifeCycle implements ReflectableStub { diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketServerResponse.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketServerResponse.java index e4cd45037..668835e79 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketServerResponse.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketServerResponse.java @@ -1,5 +1,30 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs.websocket; +import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketMessageType.TEXT; +import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponsePolicy.ONCE; +import static io.github.azagniotov.stubby4j.utils.StringUtils.newStringUtf8; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.BODY; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.DELAY; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.FILE; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.MESSAGE_TYPE; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.SERVER_RESPONSE_POLICY; + import io.github.azagniotov.stubby4j.annotations.GeneratedCodeMethodCoverageExclusion; import io.github.azagniotov.stubby4j.stubs.AbstractBuilder; import io.github.azagniotov.stubby4j.stubs.ReflectableStub; @@ -7,20 +32,10 @@ import io.github.azagniotov.stubby4j.utils.ObjectUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; import io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty; - import java.io.File; import java.util.Arrays; import java.util.Objects; -import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketMessageType.TEXT; -import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponsePolicy.ONCE; -import static io.github.azagniotov.stubby4j.utils.StringUtils.newStringUtf8; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.BODY; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.DELAY; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.FILE; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.MESSAGE_TYPE; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.SERVER_RESPONSE_POLICY; - public class StubWebSocketServerResponse implements ReflectableStub { private final StubWebSocketMessageType messageType; @@ -43,7 +58,7 @@ private StubWebSocketServerResponse( this.body = body; this.file = file; this.delay = delay; - this.fileBytes = ObjectUtils.isNull(file) ? new byte[]{} : getFileBytes(); + this.fileBytes = ObjectUtils.isNull(file) ? new byte[] {} : getFileBytes(); this.webSocketServerResponseAsYAML = webSocketServerResponseAsYAML; } @@ -82,7 +97,7 @@ private byte[] getFileBytes() { try { return FileUtils.fileToBytes(file); } catch (Exception e) { - return new byte[]{}; + return new byte[] {}; } } @@ -96,12 +111,12 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StubWebSocketServerResponse that = (StubWebSocketServerResponse) o; - return delay == that.delay && - messageType == that.messageType && - policy == that.policy && - body.equals(that.body) && - file.equals(that.file) && - Arrays.equals(fileBytes, that.fileBytes); + return delay == that.delay + && messageType == that.messageType + && policy == that.policy + && body.equals(that.body) + && file.equals(that.file) + && Arrays.equals(fileBytes, that.fileBytes); } @Override @@ -179,12 +194,7 @@ public StubWebSocketServerResponse build() { final long delayAsLong = this.delay.trim().equals("") ? 0 : Long.parseLong(this.delay); final StubWebSocketServerResponse webSocketServerResponse = new StubWebSocketServerResponse( - messageType, - strategy, - body, - file, - delayAsLong, - webSocketServerResponseAsYAML); + messageType, strategy, body, file, delayAsLong, webSocketServerResponseAsYAML); reset(); diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketServerResponsePolicy.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketServerResponsePolicy.java index e33d70ade..9b92abad4 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketServerResponsePolicy.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketServerResponsePolicy.java @@ -1,14 +1,29 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs.websocket; +import static io.github.azagniotov.stubby4j.utils.StringUtils.toLower; + import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Optional; -import static io.github.azagniotov.stubby4j.utils.StringUtils.toLower; - public enum StubWebSocketServerResponsePolicy { - ONCE("once"), PUSH("push"), FRAGMENTATION("fragmentation"), @@ -19,7 +34,8 @@ public enum StubWebSocketServerResponsePolicy { static { PROPERTY_NAME_TO_ENUM_MEMBER = new HashMap<>(); - for (final StubWebSocketServerResponsePolicy enumMember : EnumSet.allOf(StubWebSocketServerResponsePolicy.class)) { + for (final StubWebSocketServerResponsePolicy enumMember : + EnumSet.allOf(StubWebSocketServerResponsePolicy.class)) { PROPERTY_NAME_TO_ENUM_MEMBER.put(enumMember.toString(), enumMember); } } diff --git a/src/main/java/io/github/azagniotov/stubby4j/utils/CollectionUtils.java b/src/main/java/io/github/azagniotov/stubby4j/utils/CollectionUtils.java index b2c64396d..49c06902a 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/utils/CollectionUtils.java +++ b/src/main/java/io/github/azagniotov/stubby4j/utils/CollectionUtils.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.utils; import java.nio.ByteBuffer; @@ -9,12 +25,9 @@ import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; - public final class CollectionUtils { - private CollectionUtils() { - - } + private CollectionUtils() {} public static Map constructParamMap(final String requestQueryString) { if (!StringUtils.isSet(requestQueryString)) { @@ -30,8 +43,10 @@ public static Map constructParamMap(final String requestQueryStr String splittedPairValue = splittedPair.length > 1 ? splittedPair[1] : ""; if (StringUtils.isWithinSquareBrackets(splittedPairValue)) { - final String cleansedValue = StringUtils.decodeUrlEncodedQuotes(StringUtils.removeSquareBrackets(splittedPairValue)); - final String bracketedQueryValueAsCSV = Arrays.asList(cleansedValue.split(",")).toString(); + final String cleansedValue = + StringUtils.decodeUrlEncodedQuotes(StringUtils.removeSquareBrackets(splittedPairValue)); + final String bracketedQueryValueAsCSV = + Arrays.asList(cleansedValue.split(",")).toString(); splittedPairValue = StringUtils.trimSpacesBetweenCSVElements(bracketedQueryValueAsCSV); } @@ -52,7 +67,6 @@ public static String constructQueryString(final Map query) { if (iterator.hasNext()) { queryStringBuilder.append('&'); } - } return queryStringBuilder.toString(); } diff --git a/src/main/java/io/github/azagniotov/stubby4j/utils/ConsoleUtils.java b/src/main/java/io/github/azagniotov/stubby4j/utils/ConsoleUtils.java index 67e771e75..8db2a8ef4 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/utils/ConsoleUtils.java +++ b/src/main/java/io/github/azagniotov/stubby4j/utils/ConsoleUtils.java @@ -1,60 +1,72 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.utils; +import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; +import static io.github.azagniotov.stubby4j.utils.StringUtils.isSet; + import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.stubs.StubHttpLifecycle; import io.github.azagniotov.stubby4j.stubs.StubRequest; import io.github.azagniotov.stubby4j.stubs.proxy.StubProxyConfig; import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketConfig; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.LinkedList; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest; import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.LinkedList; -import java.util.List; - -import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; -import static io.github.azagniotov.stubby4j.utils.StringUtils.isSet; - @GeneratedCodeClassCoverageExclusion public final class ConsoleUtils { private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleUtils.class); - private static final String DEBUG_INCOMING_ASSERTING_HTTP_REQUEST_DUMP = " ***** [DEBUG INCOMING ASSERTING HTTP REQUEST DUMP] ***** "; - private static final String DEBUG_INCOMING_ASSERTING_HTTP_REQUEST_DUMP_END = " ***** [/DEBUG INCOMING ASSERTING HTTP REQUEST DUMP] ***** "; + private static final String DEBUG_INCOMING_ASSERTING_HTTP_REQUEST_DUMP = + " ***** [DEBUG INCOMING ASSERTING HTTP REQUEST DUMP] ***** "; + private static final String DEBUG_INCOMING_ASSERTING_HTTP_REQUEST_DUMP_END = + " ***** [/DEBUG INCOMING ASSERTING HTTP REQUEST DUMP] ***** "; - private static final String DEBUG_INCOMING_RAW_HTTP_REQUEST_DUMP = " ***** [DEBUG INCOMING RAW HTTP REQUEST DUMP] ***** "; - private static final String DEBUG_INCOMING_RAW_HTTP_REQUEST_DUMP_END = " ***** [/DEBUG INCOMING RAW HTTP REQUEST DUMP] ***** "; + private static final String DEBUG_INCOMING_RAW_HTTP_REQUEST_DUMP = + " ***** [DEBUG INCOMING RAW HTTP REQUEST DUMP] ***** "; + private static final String DEBUG_INCOMING_RAW_HTTP_REQUEST_DUMP_END = + " ***** [/DEBUG INCOMING RAW HTTP REQUEST DUMP] ***** "; private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); private static boolean debug = false; - private ConsoleUtils() { - - } - + private ConsoleUtils() {} - public static void logIncomingRequestError(final HttpServletRequest request, final String source, final String error) { + public static void logIncomingRequestError( + final HttpServletRequest request, final String source, final String error) { - final String logMessage = String.format("[%s] -> %s [%s]%s: %s", - getLocalDateTime(), - request.getMethod(), - source, - request.getRequestURI(), - error - ); + final String logMessage = String.format( + "[%s] -> %s [%s]%s: %s", + getLocalDateTime(), request.getMethod(), source, request.getRequestURI(), error); ANSITerminal.error(logMessage); LOGGER.error(logMessage); } - private static void logRawIncomingRequest(final HttpServletRequest request) { ANSITerminal.warn(DEBUG_INCOMING_RAW_HTTP_REQUEST_DUMP); ANSITerminal.info(HttpRequestUtils.dump(request)); @@ -65,25 +77,26 @@ private static void logRawIncomingRequest(final HttpServletRequest request) { LOGGER.debug(DEBUG_INCOMING_RAW_HTTP_REQUEST_DUMP_END); } - public static void logIncomingRequest(final HttpServletRequest request) { - final String logMessage = String.format("[%s] => %s %s on [%s]", + final String logMessage = String.format( + "[%s] => %s %s on [%s]", getLocalDateTime(), StringUtils.toUpper(request.getScheme()), request.getMethod(), - request.getRequestURI() - ); + request.getRequestURI()); ANSITerminal.incoming(logMessage); LOGGER.info(logMessage); if (debug) { - final List skipUriPrefix = new LinkedList() {{ - add("/ajax"); - add("/status"); - add("/favicon"); - }}; + final List skipUriPrefix = new LinkedList() { + { + add("/ajax"); + add("/status"); + add("/favicon"); + } + }; for (final String prefix : skipUriPrefix) { if (request.getRequestURI().startsWith(prefix)) { @@ -97,18 +110,17 @@ public static void logIncomingRequest(final HttpServletRequest request) { public static void logIncomingWebSocketTextRequest(final ServletUpgradeRequest request, final String message) { - final String logMessage = String.format("[%s] => %s %s on [%s]: %s", + final String logMessage = String.format( + "[%s] => %s %s on [%s]: %s", getLocalDateTime(), StringUtils.toUpper(request.isSecure() ? "wss" : "ws"), request.getMethod(), request.getRequestURI(), - message - ); + message); ANSITerminal.incoming(logMessage); LOGGER.info(logMessage); } - public static void logAssertingRequest(final StubRequest assertingStubRequest) { if (debug) { ANSITerminal.warn(DEBUG_INCOMING_ASSERTING_HTTP_REQUEST_DUMP); @@ -130,8 +142,8 @@ public static void logOutgoingResponse(final String url, final HttpServletRespon } public static void logUnmarshalledWebSocketConfig(final StubWebSocketConfig stubWebSocketConfig) { - final StringBuilder loadedMsgBuilder = new StringBuilder("Loaded web socket config metadata: ") - .append(stubWebSocketConfig.getUrl()); + final StringBuilder loadedMsgBuilder = + new StringBuilder("Loaded web socket config metadata: ").append(stubWebSocketConfig.getUrl()); if (!stubWebSocketConfig.getSubProtocols().isEmpty()) { loadedMsgBuilder.append(String.format(" %s", stubWebSocketConfig.getSubProtocols())); } @@ -148,8 +160,8 @@ public static void logUnmarshalledWebSocketConfig(final StubWebSocketConfig stub } public static void logUnmarshalledProxyConfig(final StubProxyConfig stubProxyConfig) { - final StringBuilder loadedMsgBuilder = new StringBuilder("Loaded proxy config metadata: ") - .append(stubProxyConfig.getUUID()); + final StringBuilder loadedMsgBuilder = + new StringBuilder("Loaded proxy config metadata: ").append(stubProxyConfig.getUUID()); if (isSet(stubProxyConfig.getDescription())) { loadedMsgBuilder.append(String.format(" [%s]", stubProxyConfig.getDescription())); } @@ -184,18 +196,13 @@ public static String getLocalDateTime() { * * @param isDebug if true, the incoming raw HTTP request will be dumped to console */ - public static void enableDebug(final boolean isDebug) { debug = isDebug; } - private static void lorFormattedResponse(int status) { - final String logMessage = String.format("[%s] <= %s %s\n", - getLocalDateTime(), - status, - HttpStatus.getMessage(status) - ); + final String logMessage = + String.format("[%s] <= %s %s\n", getLocalDateTime(), status, HttpStatus.getMessage(status)); if (HttpStatus.isServerError(status) || HttpStatus.isClientError(status)) { ANSITerminal.error(logMessage); diff --git a/src/main/java/io/github/azagniotov/stubby4j/utils/DateTimeUtils.java b/src/main/java/io/github/azagniotov/stubby4j/utils/DateTimeUtils.java index c47fecd56..f0bb3829e 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/utils/DateTimeUtils.java +++ b/src/main/java/io/github/azagniotov/stubby4j/utils/DateTimeUtils.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.utils; import java.time.Instant; @@ -6,9 +22,8 @@ public class DateTimeUtils { - private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter - .ofPattern("yyyy-MM-dd HH:mm:ssZ") - .withZone(ZoneOffset.systemDefault()); + private static final DateTimeFormatter DATE_TIME_FORMATTER = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssZ").withZone(ZoneOffset.systemDefault()); public static String systemDefault() { return DATE_TIME_FORMATTER.format(Instant.now()); diff --git a/src/main/java/io/github/azagniotov/stubby4j/utils/FileUtils.java b/src/main/java/io/github/azagniotov/stubby4j/utils/FileUtils.java index 49f31254e..540491460 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/utils/FileUtils.java +++ b/src/main/java/io/github/azagniotov/stubby4j/utils/FileUtils.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.utils; import java.io.BufferedInputStream; @@ -14,37 +30,125 @@ import java.util.HashSet; import java.util.Set; - @SuppressWarnings("serial") public final class FileUtils { public static final String BR = System.lineSeparator(); - private static final Set ASCII_TYPES = Collections.unmodifiableSet( - new HashSet<>( - Arrays.asList( - ".ajx", ".am", ".asa", ".asc", ".asp", ".aspx", ".awk", ".bat", - ".c", ".cdf", ".cf", ".cfg", ".cfm", ".cgi", ".cnf", ".conf", ".cpp", - ".css", ".csv", ".ctl", ".dat", ".dhtml", ".diz", ".file", ".forward", - ".grp", ".h", ".hpp", ".hqx", ".hta", ".htaccess", ".htc", ".htm", ".html", - ".htpasswd", ".htt", ".htx", ".in", ".inc", ".info", ".ini", ".ink", ".java", - ".js", ".json", ".jsp", ".log", ".logfile", ".m3u", ".m4", ".m4a", ".mak", - ".map", ".model", ".msg", ".nfo", ".nsi", ".info", ".old", ".pas", ".patch", - ".perl", ".php", ".php2", ".php3", ".php4", ".php5", ".php6", ".phtml", ".pix", - ".pl", ".pm", ".po", ".pwd", ".py", ".qmail", ".rb", ".rbl", ".rbw", ".readme", - ".reg", ".rss", ".rtf", ".ruby", ".session", ".setup", ".sh", ".shtm", ".shtml", - ".sql", ".ssh", ".stm", ".style", ".svg", ".tcl", ".text", ".threads", ".tmpl", - ".tpl", ".txt", ".ubb", ".vbs", ".xhtml", ".xml", ".xrc", ".xsl", ".yaml", ".yml" - ) - ) - ); + private static final Set ASCII_TYPES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + ".ajx", + ".am", + ".asa", + ".asc", + ".asp", + ".aspx", + ".awk", + ".bat", + ".c", + ".cdf", + ".cf", + ".cfg", + ".cfm", + ".cgi", + ".cnf", + ".conf", + ".cpp", + ".css", + ".csv", + ".ctl", + ".dat", + ".dhtml", + ".diz", + ".file", + ".forward", + ".grp", + ".h", + ".hpp", + ".hqx", + ".hta", + ".htaccess", + ".htc", + ".htm", + ".html", + ".htpasswd", + ".htt", + ".htx", + ".in", + ".inc", + ".info", + ".ini", + ".ink", + ".java", + ".js", + ".json", + ".jsp", + ".log", + ".logfile", + ".m3u", + ".m4", + ".m4a", + ".mak", + ".map", + ".model", + ".msg", + ".nfo", + ".nsi", + ".info", + ".old", + ".pas", + ".patch", + ".perl", + ".php", + ".php2", + ".php3", + ".php4", + ".php5", + ".php6", + ".phtml", + ".pix", + ".pl", + ".pm", + ".po", + ".pwd", + ".py", + ".qmail", + ".rb", + ".rbl", + ".rbw", + ".readme", + ".reg", + ".rss", + ".rtf", + ".ruby", + ".session", + ".setup", + ".sh", + ".shtm", + ".shtml", + ".sql", + ".ssh", + ".stm", + ".style", + ".svg", + ".tcl", + ".text", + ".threads", + ".tmpl", + ".tpl", + ".txt", + ".ubb", + ".vbs", + ".xhtml", + ".xml", + ".xrc", + ".xsl", + ".yaml", + ".yml"))); private static final String LINE_SEPARATOR_UNIX = "\n"; private static final String LINE_SEPARATOR_MAC_OS_PRE_X = "\r"; private static final String LINE_SEPARATOR_WINDOWS = "\r\n"; private static final String LINE_SEPARATOR_TOKEN = "[_T_O_K_E_N_]"; - private FileUtils() { - - } + private FileUtils() {} public static File uriToFile(final String dataYamlConfigParentDir, final String relativePath) throws IOException { final File contentFile = new File(dataYamlConfigParentDir, relativePath); @@ -66,13 +170,12 @@ public static File uriToFile(final String absolutePath) throws IOException { return contentFile; } - public static File tempFileFromString(final String content) throws IOException { final File temp = File.createTempFile("tmp" + System.currentTimeMillis(), ".txt"); temp.deleteOnExit(); try (final FileWriter fileWriter = new FileWriter(temp); - final BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) { + final BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) { bufferedWriter.write(content); } @@ -94,8 +197,8 @@ public static byte[] fileToBytes(final File file) throws IOException { return binaryFileToBytes(file); } - - static byte[] binaryFileToBytes(final String dataYamlConfigParentDir, final String relativePath) throws IOException { + static byte[] binaryFileToBytes(final String dataYamlConfigParentDir, final String relativePath) + throws IOException { final File contentFile = new File(dataYamlConfigParentDir, relativePath); if (!contentFile.isFile()) { @@ -105,12 +208,10 @@ static byte[] binaryFileToBytes(final String dataYamlConfigParentDir, final Stri return Files.readAllBytes(Paths.get(contentFile.toURI())); } - static byte[] binaryFileToBytes(final File file) throws IOException { return Files.readAllBytes(Paths.get(file.toURI())); } - public static String enforceSystemLineSeparator(final String loadedContent) { if (!StringUtils.isSet(loadedContent)) { return ""; diff --git a/src/main/java/io/github/azagniotov/stubby4j/utils/HandlerUtils.java b/src/main/java/io/github/azagniotov/stubby4j/utils/HandlerUtils.java index 189dceae1..8cae59025 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/utils/HandlerUtils.java +++ b/src/main/java/io/github/azagniotov/stubby4j/utils/HandlerUtils.java @@ -1,16 +1,20 @@ -package io.github.azagniotov.stubby4j.utils; - -import io.github.azagniotov.stubby4j.cli.ANSITerminal; -import io.github.azagniotov.stubby4j.common.Common; -import org.eclipse.jetty.http.HttpHeader; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.InputStream; -import java.util.Locale; +package io.github.azagniotov.stubby4j.utils; import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_HTTP_ERROR_REAL_REASON; import static io.github.azagniotov.stubby4j.utils.StringUtils.pluralize; @@ -19,23 +23,33 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; +import io.github.azagniotov.stubby4j.cli.ANSITerminal; +import io.github.azagniotov.stubby4j.common.Common; +import java.io.IOException; +import java.io.InputStream; +import java.util.Locale; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.eclipse.jetty.http.HttpHeader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @SuppressWarnings("serial") public final class HandlerUtils { private static final Logger LOGGER = LoggerFactory.getLogger(HandlerUtils.class); - private HandlerUtils() { + private HandlerUtils() {} - } - - public static void configureErrorResponse(final HttpServletResponse response, final int httpStatus, final String message) throws IOException { + public static void configureErrorResponse( + final HttpServletResponse response, final int httpStatus, final String message) throws IOException { response.setStatus(httpStatus); // Setting custom error message will no longer work in Jetty versions > 9.4.20, see: // https://github.com/eclipse/jetty.project/issues/4154 // response.sendError(httpStatus, message); // - // using header as a medium to pass an error message to JsonErrorHandler. This is a workaround as a result of the above + // using header as a medium to pass an error message to JsonErrorHandler. This is a workaround as a result of + // the above response.setHeader(HEADER_X_STUBBY_HTTP_ERROR_REAL_REASON, message); response.sendError(httpStatus); response.flushBuffer(); @@ -54,11 +68,10 @@ public static String getHtmlResourceByName(final String templateSuffix) throws I } } - public static String constructHeaderServerName() { final Package pkg = HandlerUtils.class.getPackage(); - final String implementationVersion = StringUtils.isSet(pkg.getImplementationVersion()) ? - pkg.getImplementationVersion() : "x.x.xx"; + final String implementationVersion = + StringUtils.isSet(pkg.getImplementationVersion()) ? pkg.getImplementationVersion() : "x.x.xx"; return String.format("stubby4j/%s (HTTP stub server)", implementationVersion); } @@ -83,7 +96,8 @@ public static String populateHtmlTemplate(final String templateName, final Objec return String.format(getHtmlResourceByName(templateName), params); } - public static String extractPostRequestBody(final HttpServletRequest request, final String source) throws IOException { + public static String extractPostRequestBody(final HttpServletRequest request, final String source) + throws IOException { if (!Common.POSTING_METHODS.contains(request.getMethod().toUpperCase())) { return null; } @@ -91,7 +105,7 @@ public static String extractPostRequestBody(final HttpServletRequest request, fi try { final String requestContent = StringUtils.inputStreamToString(request.getInputStream()); - return requestContent.replaceAll("\\\\/", "/"); //https://code.google.com/p/snakeyaml/issues/detail?id=93 + return requestContent.replaceAll("\\\\/", "/"); // https://code.google.com/p/snakeyaml/issues/detail?id=93 } catch (final Exception ex) { final String err = String.format("Error when extracting POST body: %s, returning null..", ex.toString()); ConsoleUtils.logIncomingRequestError(request, source, err); @@ -105,7 +119,8 @@ public static String calculateStubbyUpTime(final long timestamp) { final long mins = MILLISECONDS.toMinutes(timestamp) - HOURS.toMinutes(MILLISECONDS.toHours(timestamp)); final long secs = MILLISECONDS.toSeconds(timestamp) - MINUTES.toSeconds(MILLISECONDS.toMinutes(timestamp)); - return String.format("%d day%s, %d hour%s, %d min%s, %d sec%s", + return String.format( + "%d day%s, %d hour%s, %d min%s, %d sec%s", days, pluralize(days), hours, pluralize(hours), mins, pluralize(mins), secs, pluralize(secs)); } -} \ No newline at end of file +} diff --git a/src/main/java/io/github/azagniotov/stubby4j/utils/HttpRequestUtils.java b/src/main/java/io/github/azagniotov/stubby4j/utils/HttpRequestUtils.java index 40d161016..3b6203c8f 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/utils/HttpRequestUtils.java +++ b/src/main/java/io/github/azagniotov/stubby4j/utils/HttpRequestUtils.java @@ -1,20 +1,30 @@ /* - * Source: https://raw.githubusercontent.com/sushain97/contestManagement/master/src/util/RequestPrinter.java - * Note: Slight modifications made to fit custom requirements. + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package io.github.azagniotov.stubby4j.utils; -import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; +import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; +import static io.github.azagniotov.stubby4j.utils.ObjectUtils.isNotNull; +import static io.github.azagniotov.stubby4j.utils.ObjectUtils.isNull; -import javax.servlet.http.HttpServletRequest; +import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; - -import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; -import static io.github.azagniotov.stubby4j.utils.ObjectUtils.isNotNull; -import static io.github.azagniotov.stubby4j.utils.ObjectUtils.isNull; +import javax.servlet.http.HttpServletRequest; @GeneratedCodeClassCoverageExclusion final class HttpRequestUtils { @@ -28,17 +38,17 @@ final class HttpRequestUtils { private static final String EMPTY_BRACES = LEFT_CURLY_BRACE + RIGHT_CURLY_BRACE; private static final int AT_LEAST_ONE_HEADER = 1; - private HttpRequestUtils() { - - } - + private HttpRequestUtils() {} - private static String debugStringHeader(final String indentString, final String headerName, final List headerValues) { + private static String debugStringHeader( + final String indentString, final String headerName, final List headerValues) { final StringBuilder stringBuilder = new StringBuilder(); - stringBuilder. - append(indentString). - append(INDENT_UNIT). - append("'").append(headerName).append("': "); + stringBuilder + .append(indentString) + .append(INDENT_UNIT) + .append("'") + .append(headerName) + .append("': "); if (isNull(headerValues) || headerValues.size() == 0) { stringBuilder.append("None"); } else { @@ -54,7 +64,6 @@ private static String debugStringHeader(final String indentString, final String return stringBuilder.toString(); } - private static String debugStringHeaders(final HttpServletRequest request, final int indent) { final Enumeration headerNames = request.getHeaderNames(); if (isNull(headerNames) || !headerNames.hasMoreElements()) { @@ -70,9 +79,10 @@ private static String debugStringHeaders(final HttpServletRequest request, final while (isNotNull(headerValues) && headerValues.hasMoreElements()) { headerValuesList.add(headerValues.nextElement()); } - stringBuilder. - append(HttpRequestUtils.debugStringHeader(indentString, headerName, headerValuesList)). - append(COMMA).append(BR); + stringBuilder + .append(HttpRequestUtils.debugStringHeader(indentString, headerName, headerValuesList)) + .append(COMMA) + .append(BR); } stringBuilder.append(indentString).append(RIGHT_CURLY_BRACE); return stringBuilder.toString(); @@ -84,21 +94,53 @@ private static String debugStringHeaders(final HttpServletRequest request, final * @param request Request parameter. * @return A string with debug information on Request's header */ - static String dump(final HttpServletRequest request) { final StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(INDENT_UNIT + "PROTOCOL: ").append(request.getProtocol()).append(BR); - stringBuilder.append(INDENT_UNIT + "METHOD: ").append(request.getMethod()).append(BR); - stringBuilder.append(INDENT_UNIT + "CONTEXT PATH: ").append(request.getContextPath()).append(BR); - stringBuilder.append(INDENT_UNIT + "SERVLET PATH: ").append(request.getServletPath()).append(BR); - stringBuilder.append(INDENT_UNIT + "AUTH TYPE: ").append(request.getAuthType()).append(BR); - stringBuilder.append(INDENT_UNIT + "REMOTE USER: ").append(request.getRemoteUser()).append(BR); - stringBuilder.append(INDENT_UNIT + "REQUEST URI: ").append(request.getRequestURI()).append(BR); - stringBuilder.append(INDENT_UNIT + "REQUEST URL: ").append(request.getRequestURL()).append(BR); - stringBuilder.append(INDENT_UNIT + "QUERY STRING: ").append(request.getQueryString()).append(BR); - stringBuilder.append(INDENT_UNIT + "PATH INFO: ").append(request.getPathInfo()).append(BR); - stringBuilder.append(INDENT_UNIT + "PATH TRANSLATED: ").append(request.getPathTranslated()).append(BR); + stringBuilder + .append(INDENT_UNIT + "PROTOCOL: ") + .append(request.getProtocol()) + .append(BR); + stringBuilder + .append(INDENT_UNIT + "METHOD: ") + .append(request.getMethod()) + .append(BR); + stringBuilder + .append(INDENT_UNIT + "CONTEXT PATH: ") + .append(request.getContextPath()) + .append(BR); + stringBuilder + .append(INDENT_UNIT + "SERVLET PATH: ") + .append(request.getServletPath()) + .append(BR); + stringBuilder + .append(INDENT_UNIT + "AUTH TYPE: ") + .append(request.getAuthType()) + .append(BR); + stringBuilder + .append(INDENT_UNIT + "REMOTE USER: ") + .append(request.getRemoteUser()) + .append(BR); + stringBuilder + .append(INDENT_UNIT + "REQUEST URI: ") + .append(request.getRequestURI()) + .append(BR); + stringBuilder + .append(INDENT_UNIT + "REQUEST URL: ") + .append(request.getRequestURL()) + .append(BR); + stringBuilder + .append(INDENT_UNIT + "QUERY STRING: ") + .append(request.getQueryString()) + .append(BR); + stringBuilder + .append(INDENT_UNIT + "PATH INFO: ") + .append(request.getPathInfo()) + .append(BR); + stringBuilder + .append(INDENT_UNIT + "PATH TRANSLATED: ") + .append(request.getPathTranslated()) + .append(BR); stringBuilder.append(INDENT_UNIT + "HEADERS: ").append(HttpRequestUtils.debugStringHeaders(request, 1)); return stringBuilder.toString(); diff --git a/src/main/java/io/github/azagniotov/stubby4j/utils/JarUtils.java b/src/main/java/io/github/azagniotov/stubby4j/utils/JarUtils.java index da28458f5..ddf9db857 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/utils/JarUtils.java +++ b/src/main/java/io/github/azagniotov/stubby4j/utils/JarUtils.java @@ -1,7 +1,22 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.utils; import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; - import java.io.IOException; import java.io.InputStream; import java.util.jar.Manifest; @@ -9,9 +24,7 @@ @GeneratedCodeClassCoverageExclusion public final class JarUtils { - private JarUtils() { - - } + private JarUtils() {} public static String readManifestImplementationVersion() { try { @@ -23,7 +36,6 @@ public static String readManifestImplementationVersion() { } } - public static String readManifestBuiltDate() { try { final Manifest manifest = getManifest(); @@ -41,9 +53,8 @@ public static String readManifestBuiltDate() { private static Manifest getManifest() throws IOException { - final InputStream inputStream = Thread.currentThread() - .getContextClassLoader() - .getResourceAsStream("META-INF/MANIFEST.MF"); + final InputStream inputStream = + Thread.currentThread().getContextClassLoader().getResourceAsStream("META-INF/MANIFEST.MF"); return new Manifest(inputStream); } diff --git a/src/main/java/io/github/azagniotov/stubby4j/utils/NetworkPortUtils.java b/src/main/java/io/github/azagniotov/stubby4j/utils/NetworkPortUtils.java index 557e76fa1..acbd56dfd 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/utils/NetworkPortUtils.java +++ b/src/main/java/io/github/azagniotov/stubby4j/utils/NetworkPortUtils.java @@ -1,17 +1,30 @@ -package io.github.azagniotov.stubby4j.utils; - +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; +package io.github.azagniotov.stubby4j.utils; import static io.github.azagniotov.stubby4j.utils.SpringSocketUtils.PORT_RANGE_MAX; import static io.github.azagniotov.stubby4j.utils.SpringSocketUtils.PORT_RANGE_MIN; +import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; + @GeneratedCodeClassCoverageExclusion public final class NetworkPortUtils { - private NetworkPortUtils() { - - } + private NetworkPortUtils() {} public static int findAvailableTcpPort() { return SpringSocketUtils.findAvailableTcpPort(PORT_RANGE_MIN, PORT_RANGE_MAX); diff --git a/src/main/java/io/github/azagniotov/stubby4j/utils/ObjectUtils.java b/src/main/java/io/github/azagniotov/stubby4j/utils/ObjectUtils.java index f9c128ae3..68b882ab2 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/utils/ObjectUtils.java +++ b/src/main/java/io/github/azagniotov/stubby4j/utils/ObjectUtils.java @@ -1,11 +1,24 @@ -package io.github.azagniotov.stubby4j.utils; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.azagniotov.stubby4j.utils; public final class ObjectUtils { - private ObjectUtils() { - - } + private ObjectUtils() {} public static boolean isNull(final Object instance) { return instance == null; diff --git a/src/main/java/io/github/azagniotov/stubby4j/utils/ReflectionUtils.java b/src/main/java/io/github/azagniotov/stubby4j/utils/ReflectionUtils.java index a3e002c3e..d302e4eae 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/utils/ReflectionUtils.java +++ b/src/main/java/io/github/azagniotov/stubby4j/utils/ReflectionUtils.java @@ -1,7 +1,22 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.utils; import io.github.azagniotov.stubby4j.stubs.ReflectableStub; - import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; @@ -15,19 +30,17 @@ import java.util.Locale; import java.util.Map; - public final class ReflectionUtils { // These fields are defined in various Stub* classes, e.g.: StubRequest or StubProxyConfig - private static List reflectionSkippableProperties = - Collections.unmodifiableList(Arrays.asList("proxyConfigAsYAML", "webSocketConfigAsYAML", "regexGroups", "fileBytes")); + private static List reflectionSkippableProperties = Collections.unmodifiableList( + Arrays.asList("proxyConfigAsYAML", "webSocketConfigAsYAML", "regexGroups", "fileBytes")); - private ReflectionUtils() { - - } + private ReflectionUtils() {} @SuppressWarnings("deprecation") - public static Map getProperties(final T reflectable) throws IllegalAccessException, InvocationTargetException, UnsupportedEncodingException { + public static Map getProperties(final T reflectable) + throws IllegalAccessException, InvocationTargetException, UnsupportedEncodingException { final Map properties = new HashMap<>(); for (final Field field : reflectable.getClass().getDeclaredFields()) { @@ -54,14 +67,18 @@ public static Map getProperties(fina return properties; } - public static void injectObjectFields(final T reflectable, final String fieldName, final Object value) throws InvocationTargetException, IllegalAccessException { + public static void injectObjectFields( + final T reflectable, final String fieldName, final Object value) + throws InvocationTargetException, IllegalAccessException { final Map fieldAndValue = new HashMap<>(); fieldAndValue.put(fieldName.toLowerCase(Locale.US), value); injectObjectFields(reflectable, fieldAndValue); } @SuppressWarnings("deprecation") - public static void injectObjectFields(final T reflectable, final Map fieldsAndValues) throws InvocationTargetException, IllegalAccessException { + public static void injectObjectFields( + final T reflectable, final Map fieldsAndValues) + throws InvocationTargetException, IllegalAccessException { for (final Field field : reflectable.getClass().getDeclaredFields()) { final String fieldName = field.getName().toLowerCase(Locale.US); @@ -78,7 +95,8 @@ public static void injectObjectFields(final T reflec } } - public static Object getPropertyValue(final Object object, final String fieldName) throws InvocationTargetException, IllegalAccessException { + public static Object getPropertyValue(final Object object, final String fieldName) + throws InvocationTargetException, IllegalAccessException { for (final Method method : object.getClass().getDeclaredMethods()) { // e.g.: "responseAsYAML" => StubHttpLifecycle.getResponseAsYAML if (method.getName().equalsIgnoreCase("get" + fieldName)) { diff --git a/src/main/java/io/github/azagniotov/stubby4j/utils/SpringSocketUtils.java b/src/main/java/io/github/azagniotov/stubby4j/utils/SpringSocketUtils.java index c02c5ab20..a622a7b93 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/utils/SpringSocketUtils.java +++ b/src/main/java/io/github/azagniotov/stubby4j/utils/SpringSocketUtils.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.utils; /* @@ -19,12 +35,11 @@ */ import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; - -import javax.net.ServerSocketFactory; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.ServerSocket; import java.util.Random; +import javax.net.ServerSocketFactory; /** * Simple utility methods for working with network sockets — for example, @@ -55,10 +70,8 @@ class SpringSocketUtils { */ static final int PORT_RANGE_MAX = 65535; - private static final Random random = new Random(System.nanoTime()); - /** * Although {@code SocketUtils} consists solely of static utility methods, * this constructor is intentionally {@code public}. @@ -75,8 +88,7 @@ class SpringSocketUtils { * <bean id="bean1" ... p:port="#{socketUtils.findAvailableTcpPort(12000)}" /> * <bean id="bean2" ... p:port="#{socketUtils.findAvailableTcpPort(30000)}" /> */ - private SpringSocketUtils() { - } + private SpringSocketUtils() {} /** * Find an available TCP port randomly selected from the range @@ -92,13 +104,12 @@ static int findAvailableTcpPort(int minPort, int maxPort) { } private enum SocketType { - TCP { @Override protected boolean isPortAvailable(int port) { try { - ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket( - port, 1, InetAddress.getByName("localhost")); + ServerSocket serverSocket = ServerSocketFactory.getDefault() + .createServerSocket(port, 1, InetAddress.getByName("localhost")); serverSocket.close(); return true; } catch (Exception ex) { @@ -147,11 +158,9 @@ int findAvailablePort(int minPort, int maxPort) { } candidatePort = findRandomPort(minPort, maxPort); searchCounter++; - } - while (!isPortAvailable(candidatePort)); + } while (!isPortAvailable(candidatePort)); return candidatePort; } } - } diff --git a/src/main/java/io/github/azagniotov/stubby4j/utils/StringUtils.java b/src/main/java/io/github/azagniotov/stubby4j/utils/StringUtils.java index 31e19b59a..75cba5811 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/utils/StringUtils.java +++ b/src/main/java/io/github/azagniotov/stubby4j/utils/StringUtils.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.utils; import java.io.BufferedInputStream; @@ -16,13 +32,13 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; - public final class StringUtils { public static final String UTF_8 = "UTF-8"; static final String NOT_PROVIDED = "Not provided"; - static final String FAILED = "Failed to retrieveLoadedStubs response content using relative path specified in 'file' during YAML parse time. Check terminal for warnings, and that response content exists in relative path specified in 'file'"; + static final String FAILED = + "Failed to retrieveLoadedStubs response content using relative path specified in 'file' during YAML parse time. Check terminal for warnings, and that response content exists in relative path specified in 'file'"; private static final CharsetEncoder US_ASCII_ENCODER = StandardCharsets.US_ASCII.newEncoder(); @@ -30,9 +46,7 @@ public final class StringUtils { private static final String TEMPLATE_TOKEN_RIGHT = "%>"; private static final Base64.Encoder BASE_64_ENCODER = Base64.getEncoder(); - private StringUtils() { - - } + private StringUtils() {} public static boolean isSet(final String toTest) { return ObjectUtils.isNotNull(toTest) && isNotBlank(toTest); @@ -79,10 +93,16 @@ public static String inputStreamToString(final InputStream inputStream) { // Regex \A matches the beginning of input. This effectively tells Scanner to tokenize // the entire stream, from beginning to (illogical) next beginning. if (inputStream instanceof BufferedInputStream) { - return new Scanner(inputStream, StringUtils.UTF_8).useDelimiter("\\A").next().trim(); + return new Scanner(inputStream, StringUtils.UTF_8) + .useDelimiter("\\A") + .next() + .trim(); } - return new Scanner(FileUtils.makeBuffered(inputStream), StringUtils.UTF_8).useDelimiter("\\A").next().trim(); + return new Scanner(FileUtils.makeBuffered(inputStream), StringUtils.UTF_8) + .useDelimiter("\\A") + .next() + .trim(); } public static String buildToken(final String propertyName, final int capturingGroupIdx) { @@ -95,7 +115,8 @@ public static String replaceTokens(final byte[] stringBytes, final Map tokensAndValues) { for (final Map.Entry entry : tokensAndValues.entrySet()) { - final String regexifiedKey = String.format("%s\\s{0,}%s\\s{0,}%s", TEMPLATE_TOKEN_LEFT, entry.getKey(), TEMPLATE_TOKEN_RIGHT); + final String regexifiedKey = + String.format("%s\\s{0,}%s\\s{0,}%s", TEMPLATE_TOKEN_LEFT, entry.getKey(), TEMPLATE_TOKEN_RIGHT); template = template.replaceAll(regexifiedKey, entry.getValue()); } return template; @@ -125,11 +146,10 @@ public static String escapeSpecialRegexCharacters(final String toEscape) { .replaceAll(Pattern.quote("]"), "\\\\]"); } - public static String constructUserAgentName() { final Package pkg = StringUtils.class.getPackage(); - final String implementationVersion = StringUtils.isSet(pkg.getImplementationVersion()) ? - pkg.getImplementationVersion() : "x.x.xx"; + final String implementationVersion = + StringUtils.isSet(pkg.getImplementationVersion()) ? pkg.getImplementationVersion() : "x.x.xx"; return String.format("stubby4j/%s (HTTP stub client request)", implementationVersion); } @@ -157,9 +177,7 @@ public static Set splitCsv(final String value) { return new HashSet<>(); } final String delimiter = ","; - return Arrays.stream(value.split(delimiter)) - .map(String::trim) - .collect(Collectors.toSet()); + return Arrays.stream(value.split(delimiter)).map(String::trim).collect(Collectors.toSet()); } public static String encodeBase64(final String toEncode) { diff --git a/src/main/java/io/github/azagniotov/stubby4j/yaml/ConfigurableYAMLProperty.java b/src/main/java/io/github/azagniotov/stubby4j/yaml/ConfigurableYAMLProperty.java index 79aab87e4..abae5b7e0 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/yaml/ConfigurableYAMLProperty.java +++ b/src/main/java/io/github/azagniotov/stubby4j/yaml/ConfigurableYAMLProperty.java @@ -1,5 +1,23 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.yaml; +import static io.github.azagniotov.stubby4j.utils.StringUtils.toLower; + import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; @@ -7,8 +25,6 @@ import java.util.Map; import java.util.Set; -import static io.github.azagniotov.stubby4j.utils.StringUtils.toLower; - public enum ConfigurableYAMLProperty { // allows for YAML sub-configs @@ -54,7 +70,6 @@ public enum ConfigurableYAMLProperty { FILE("file"), // request, response, web-socket properties HEADERS("headers"); // request, response, proxy-config properties - private static final Map PROPERTY_NAME_TO_ENUM_MEMBER; private static final Map> PROPERTY_NAME_TO_FAMILY; diff --git a/src/main/java/io/github/azagniotov/stubby4j/yaml/SnakeYaml.java b/src/main/java/io/github/azagniotov/stubby4j/yaml/SnakeYaml.java index 7bd68c422..5ce398bd0 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/yaml/SnakeYaml.java +++ b/src/main/java/io/github/azagniotov/stubby4j/yaml/SnakeYaml.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.yaml; import org.yaml.snakeyaml.DumperOptions; @@ -8,20 +24,22 @@ import org.yaml.snakeyaml.resolver.Resolver; public enum SnakeYaml { - INSTANCE; private final Yaml snakeYaml; SnakeYaml() { - snakeYaml = new Yaml(new Constructor(new LoaderOptions()), new Representer(new DumperOptions()), new DumperOptions(), new YamlParserResolver()); + snakeYaml = new Yaml( + new Constructor(new LoaderOptions()), + new Representer(new DumperOptions()), + new DumperOptions(), + new YamlParserResolver()); } public Yaml getSnakeYaml() { return snakeYaml; } - private static final class YamlParserResolver extends Resolver { YamlParserResolver() { super(); diff --git a/src/main/java/io/github/azagniotov/stubby4j/yaml/YamlBuilder.java b/src/main/java/io/github/azagniotov/stubby4j/yaml/YamlBuilder.java index fb7f36c54..2cf93f108 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/yaml/YamlBuilder.java +++ b/src/main/java/io/github/azagniotov/stubby4j/yaml/YamlBuilder.java @@ -1,14 +1,29 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.yaml; import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion; import io.github.azagniotov.stubby4j.stubs.StubbableAuthorizationType; import io.github.azagniotov.stubby4j.stubs.proxy.StubProxyStrategy; import io.github.azagniotov.stubby4j.utils.FileUtils; -import org.eclipse.jetty.http.HttpMethod; - import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; +import org.eclipse.jetty.http.HttpMethod; /** * Please refer to the accompanied unit tests for usage examples. @@ -23,55 +38,61 @@ public final class YamlBuilder { private static final String NINE_SPACE = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, THREE_SPACE); private static final String TWELVE_SPACE = String.format(TWO_TOKENS_TEMPLATE, NINE_SPACE, THREE_SPACE); - private final static String DESCRIPTION_AS_TOP = String.format("-%s%s", TWO_SPACE, "description: "); - private final static String DESCRIPTION = String.format(TWO_TOKENS_TEMPLATE, THREE_SPACE, "description: "); + private static final String DESCRIPTION_AS_TOP = String.format("-%s%s", TWO_SPACE, "description: "); + private static final String DESCRIPTION = String.format(TWO_TOKENS_TEMPLATE, THREE_SPACE, "description: "); - private final static String UUID_AS_TOP = String.format("-%s%s", TWO_SPACE, "uuid: "); - private final static String UUID = String.format(TWO_TOKENS_TEMPLATE, THREE_SPACE, "uuid: "); + private static final String UUID_AS_TOP = String.format("-%s%s", TWO_SPACE, "uuid: "); + private static final String UUID = String.format(TWO_TOKENS_TEMPLATE, THREE_SPACE, "uuid: "); - private final static String PROXY_CONFIG_AS_TOP = String.format("-%s%s", TWO_SPACE, "proxy-config:"); - private final static String REQUEST_AS_TOP = String.format("-%s%s", TWO_SPACE, "request:"); - private final static String REQUEST = String.format(TWO_TOKENS_TEMPLATE, THREE_SPACE, "request:"); - private final static String RESPONSE = String.format(TWO_TOKENS_TEMPLATE, THREE_SPACE, "response:"); + private static final String PROXY_CONFIG_AS_TOP = String.format("-%s%s", TWO_SPACE, "proxy-config:"); + private static final String REQUEST_AS_TOP = String.format("-%s%s", TWO_SPACE, "request:"); + private static final String REQUEST = String.format(TWO_TOKENS_TEMPLATE, THREE_SPACE, "request:"); + private static final String RESPONSE = String.format(TWO_TOKENS_TEMPLATE, THREE_SPACE, "response:"); - private final static String HEADERS = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "headers:"); - private final static String PROXY_HEADERS = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "headers:"); - private final static String PROXY_PROPERTIES = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "properties:"); - private final static String PROXY_STRATEGY = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "strategy: "); - private final static String PROXY_UUID = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "uuid: "); - private final static String PROXY_CONFIG_DESCRIPTION = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "description: "); - private final static String SEQUENCE_RESPONSE_HEADERS = String.format(TWO_TOKENS_TEMPLATE, NINE_SPACE, "headers: "); + private static final String HEADERS = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "headers:"); + private static final String PROXY_HEADERS = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "headers:"); + private static final String PROXY_PROPERTIES = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "properties:"); + private static final String PROXY_STRATEGY = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "strategy: "); + private static final String PROXY_UUID = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "uuid: "); + private static final String PROXY_CONFIG_DESCRIPTION = + String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "description: "); + private static final String SEQUENCE_RESPONSE_HEADERS = String.format(TWO_TOKENS_TEMPLATE, NINE_SPACE, "headers: "); - private final static String QUERY = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "query:"); - private final static String METHOD = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "method: "); - private final static String TEMP_METHOD_PLACEHOLDER_TOKEN = "METHOD_TOKEN"; + private static final String QUERY = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "query:"); + private static final String METHOD = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "method: "); + private static final String TEMP_METHOD_PLACEHOLDER_TOKEN = "METHOD_TOKEN"; - private final static String STATUS = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "status: "); - private final static String SEQUENCE_RESPONSE_STATUS = String.format("%s-%s%s", SIX_SPACE, TWO_SPACE, "status: "); + private static final String STATUS = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "status: "); + private static final String SEQUENCE_RESPONSE_STATUS = String.format("%s-%s%s", SIX_SPACE, TWO_SPACE, "status: "); - private final static String FILE = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "file: "); - private final static String SEQUENCE_RESPONSE_FILE = String.format(TWO_TOKENS_TEMPLATE, NINE_SPACE, "file: "); + private static final String FILE = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "file: "); + private static final String SEQUENCE_RESPONSE_FILE = String.format(TWO_TOKENS_TEMPLATE, NINE_SPACE, "file: "); - private final static String URL = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "url: "); + private static final String URL = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "url: "); - private final static String ONELINEPOST = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "post: "); - private final static String MULTILINEPOST = String.format("%s%s%s", SIX_SPACE, "post: >", FileUtils.BR); + private static final String ONELINEPOST = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "post: "); + private static final String MULTILINEPOST = String.format("%s%s%s", SIX_SPACE, "post: >", FileUtils.BR); - private final static String ONELINEBODY = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "body: "); - private final static String SEQUENCE_RESPONSE_ONELINEBODY = String.format(TWO_TOKENS_TEMPLATE, NINE_SPACE, "body: "); + private static final String ONELINEBODY = String.format(TWO_TOKENS_TEMPLATE, SIX_SPACE, "body: "); + private static final String SEQUENCE_RESPONSE_ONELINEBODY = + String.format(TWO_TOKENS_TEMPLATE, NINE_SPACE, "body: "); - private final static String MULTILINEBODY = String.format("%s%s%s", SIX_SPACE, "body: >", FileUtils.BR); - private final static String SEQUENCE_RESPONSE_MULTILINEBODY = String.format("%s%s%s", NINE_SPACE, "body: >", FileUtils.BR); + private static final String MULTILINEBODY = String.format("%s%s%s", SIX_SPACE, "body: >", FileUtils.BR); + private static final String SEQUENCE_RESPONSE_MULTILINEBODY = + String.format("%s%s%s", NINE_SPACE, "body: >", FileUtils.BR); - private final static String NL = FileUtils.BR; + private static final String NL = FileUtils.BR; private static final String TWO_DASHED_TOKENS_TEMPLATE = "%s-%s"; - private final static String PROXY_HEADERS_KEY = String.format(TWO_DASHED_TOKENS_TEMPLATE, PROXY_CONFIG_AS_TOP, PROXY_HEADERS); - private final static String PROXY_PROPERTIES_KEY = String.format(TWO_DASHED_TOKENS_TEMPLATE, PROXY_CONFIG_AS_TOP, PROXY_PROPERTIES); - private final static String REQUEST_HEADERS_KEY = String.format(TWO_DASHED_TOKENS_TEMPLATE, REQUEST_AS_TOP, HEADERS); - private final static String REQUEST_QUERY_KEY = String.format(TWO_DASHED_TOKENS_TEMPLATE, REQUEST_AS_TOP, QUERY); - private final static String RESPONSE_HEADERS_KEY = String.format(TWO_DASHED_TOKENS_TEMPLATE, RESPONSE, HEADERS); - private final static String RESPONSE_QUERY_KEY = String.format(TWO_DASHED_TOKENS_TEMPLATE, RESPONSE, QUERY); + private static final String PROXY_HEADERS_KEY = + String.format(TWO_DASHED_TOKENS_TEMPLATE, PROXY_CONFIG_AS_TOP, PROXY_HEADERS); + private static final String PROXY_PROPERTIES_KEY = + String.format(TWO_DASHED_TOKENS_TEMPLATE, PROXY_CONFIG_AS_TOP, PROXY_PROPERTIES); + private static final String REQUEST_HEADERS_KEY = + String.format(TWO_DASHED_TOKENS_TEMPLATE, REQUEST_AS_TOP, HEADERS); + private static final String REQUEST_QUERY_KEY = String.format(TWO_DASHED_TOKENS_TEMPLATE, REQUEST_AS_TOP, QUERY); + private static final String RESPONSE_HEADERS_KEY = String.format(TWO_DASHED_TOKENS_TEMPLATE, RESPONSE, HEADERS); + private static final String RESPONSE_QUERY_KEY = String.format(TWO_DASHED_TOKENS_TEMPLATE, RESPONSE, QUERY); private static final StringBuilder FEATURE_STRING_BUILDER = new StringBuilder(); private static final StringBuilder PROXY_CONFIG_STRING_BUILDER = new StringBuilder(); @@ -80,18 +101,18 @@ public final class YamlBuilder { private static final String YAML_KEY_SPACE_TEMPLATE = "%s%s: "; private final Set storedStubbedMethods = new LinkedHashSet<>(); - private final Set unusedNodes = new HashSet() {{ - add(PROXY_HEADERS_KEY); - add(PROXY_PROPERTIES_KEY); - add(REQUEST_HEADERS_KEY); - add(REQUEST_QUERY_KEY); - add(RESPONSE_HEADERS_KEY); - add(RESPONSE_QUERY_KEY); - }}; - - public YamlBuilder() { + private final Set unusedNodes = new HashSet() { + { + add(PROXY_HEADERS_KEY); + add(PROXY_PROPERTIES_KEY); + add(REQUEST_HEADERS_KEY); + add(REQUEST_QUERY_KEY); + add(RESPONSE_HEADERS_KEY); + add(RESPONSE_QUERY_KEY); + } + }; - } + public YamlBuilder() {} public Feature newStubbedFeature() { return new Feature(); @@ -132,7 +153,10 @@ private Feature() { public Feature withDescription(final String description) { if (!topLevelSet) { - FEATURE_STRING_BUILDER.append(DESCRIPTION_AS_TOP).append(description).append(NL); + FEATURE_STRING_BUILDER + .append(DESCRIPTION_AS_TOP) + .append(description) + .append(NL); topLevelSet = true; } else { FEATURE_STRING_BUILDER.append(DESCRIPTION).append(description).append(NL); @@ -163,7 +187,10 @@ private ProxyConfig() { } public ProxyConfig withDescription(final String value) { - PROXY_CONFIG_STRING_BUILDER.append(PROXY_CONFIG_DESCRIPTION).append(value).append(NL); + PROXY_CONFIG_STRING_BUILDER + .append(PROXY_CONFIG_DESCRIPTION) + .append(value) + .append(NL); return this; } @@ -175,7 +202,10 @@ public ProxyConfig withUuid(final String value) { } public ProxyConfig withProxyStrategyAsIs() { - PROXY_CONFIG_STRING_BUILDER.append(PROXY_STRATEGY).append(StubProxyStrategy.AS_IS.toString()).append(NL); + PROXY_CONFIG_STRING_BUILDER + .append(PROXY_STRATEGY) + .append(StubProxyStrategy.AS_IS.toString()) + .append(NL); return this; } @@ -204,8 +234,8 @@ public ProxyConfig withPropertyEndpoint(final String value) { checkProxyPropertiesNodeRequired(); - final String tabbedKey = String.format(YAML_KEY_SPACE_TEMPLATE, NINE_SPACE, - ConfigurableYAMLProperty.ENDPOINT.toString()); + final String tabbedKey = + String.format(YAML_KEY_SPACE_TEMPLATE, NINE_SPACE, ConfigurableYAMLProperty.ENDPOINT.toString()); PROXY_CONFIG_STRING_BUILDER.append(tabbedKey).append(value).append(NL); return this; @@ -274,7 +304,10 @@ public Request withUrl(final String value) { private Request appendTemporaryMethodPlaceholderStoreMethod(final String methodName) { if (REQUEST_STRING_BUILDER.indexOf(METHOD) == -1) { - REQUEST_STRING_BUILDER.append(METHOD).append(TEMP_METHOD_PLACEHOLDER_TOKEN).append(NL); + REQUEST_STRING_BUILDER + .append(METHOD) + .append(TEMP_METHOD_PLACEHOLDER_TOKEN) + .append(NL); } storedStubbedMethods.add(methodName); @@ -336,7 +369,8 @@ public Request withHeaderAuthorizationBasic(final String value) { checkHeadersNodeRequired(); - final String tabbedKey = String.format(YAML_KEY_SPACE_TEMPLATE, NINE_SPACE, StubbableAuthorizationType.BASIC.asYAMLProp()); + final String tabbedKey = + String.format(YAML_KEY_SPACE_TEMPLATE, NINE_SPACE, StubbableAuthorizationType.BASIC.asYAMLProp()); REQUEST_STRING_BUILDER.append(tabbedKey).append(value).append(NL); return this; @@ -346,7 +380,8 @@ public Request withHeaderAuthorizationBearer(final String value) { checkHeadersNodeRequired(); - final String tabbedKey = String.format(YAML_KEY_SPACE_TEMPLATE, NINE_SPACE, StubbableAuthorizationType.BEARER.asYAMLProp()); + final String tabbedKey = + String.format(YAML_KEY_SPACE_TEMPLATE, NINE_SPACE, StubbableAuthorizationType.BEARER.asYAMLProp()); REQUEST_STRING_BUILDER.append(tabbedKey).append(value).append(NL); return this; @@ -356,7 +391,8 @@ public Request withHeaderAuthorizationCustom(final String value) { checkHeadersNodeRequired(); - final String tabbedKey = String.format(YAML_KEY_SPACE_TEMPLATE, NINE_SPACE, StubbableAuthorizationType.CUSTOM.asYAMLProp()); + final String tabbedKey = + String.format(YAML_KEY_SPACE_TEMPLATE, NINE_SPACE, StubbableAuthorizationType.CUSTOM.asYAMLProp()); REQUEST_STRING_BUILDER.append(tabbedKey).append(value).append(NL); return this; @@ -417,14 +453,12 @@ private Response() { RESPONSE_STRING_BUILDER.append(RESPONSE).append(NL); } - public Response withLineBreak() { RESPONSE_STRING_BUILDER.append(NL); return this; } - public Response withStatus(final String value) { RESPONSE_STRING_BUILDER.append(STATUS).append(value).append(NL); @@ -432,7 +466,10 @@ public Response withStatus(final String value) { } public Response withSequenceResponseStatus(final String value) { - RESPONSE_STRING_BUILDER.append(SEQUENCE_RESPONSE_STATUS).append(value).append(NL); + RESPONSE_STRING_BUILDER + .append(SEQUENCE_RESPONSE_STATUS) + .append(value) + .append(NL); return this; } @@ -456,7 +493,10 @@ public Response withLiteralBody(final String body) { } public Response withSequenceResponseLiteralBody(final String body) { - RESPONSE_STRING_BUILDER.append(SEQUENCE_RESPONSE_ONELINEBODY).append(body).append(NL); + RESPONSE_STRING_BUILDER + .append(SEQUENCE_RESPONSE_ONELINEBODY) + .append(body) + .append(NL); return this; } @@ -470,7 +510,10 @@ public Response withFoldedBody(final String body) { public Response withSequenceResponseFoldedBody(final String body) { final String tabbedBody = String.format(TWO_TOKENS_TEMPLATE, TWELVE_SPACE, body); - RESPONSE_STRING_BUILDER.append(SEQUENCE_RESPONSE_MULTILINEBODY).append(tabbedBody).append(NL); + RESPONSE_STRING_BUILDER + .append(SEQUENCE_RESPONSE_MULTILINEBODY) + .append(tabbedBody) + .append(NL); return this; } @@ -569,8 +612,12 @@ public String build() { final String rawFeatureString = FEATURE_STRING_BUILDER.toString().trim(); final String rawRequestString = REQUEST_STRING_BUILDER.toString(); // do not trim()! - final String cleansedRequestString = rawRequestString.replaceAll(TEMP_METHOD_PLACEHOLDER_TOKEN, storedStubbedMethods.toString()); - final String yaml = String.format("%s%s%s%s%s", rawFeatureString, NL, cleansedRequestString, NL, RESPONSE_STRING_BUILDER.toString()).trim(); + final String cleansedRequestString = + rawRequestString.replaceAll(TEMP_METHOD_PLACEHOLDER_TOKEN, storedStubbedMethods.toString()); + final String yaml = String.format( + "%s%s%s%s%s", + rawFeatureString, NL, cleansedRequestString, NL, RESPONSE_STRING_BUILDER.toString()) + .trim(); clear(); diff --git a/src/main/java/io/github/azagniotov/stubby4j/yaml/YamlParseResultSet.java b/src/main/java/io/github/azagniotov/stubby4j/yaml/YamlParseResultSet.java index 457c9d5be..774040b73 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/yaml/YamlParseResultSet.java +++ b/src/main/java/io/github/azagniotov/stubby4j/yaml/YamlParseResultSet.java @@ -1,9 +1,24 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.yaml; import io.github.azagniotov.stubby4j.stubs.StubHttpLifecycle; import io.github.azagniotov.stubby4j.stubs.proxy.StubProxyConfig; import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketConfig; - import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; @@ -17,27 +32,28 @@ public class YamlParseResultSet { private final Map proxyConfigs; private final Map webSocketConfigs; - public YamlParseResultSet(final List stubs, - final Map uuidToStubs) { + public YamlParseResultSet(final List stubs, final Map uuidToStubs) { this.stubs = stubs; this.uuidToStubs = uuidToStubs; this.proxyConfigs = new HashMap<>(); this.webSocketConfigs = new LinkedHashMap<>(); } - public YamlParseResultSet(final List stubs, - final Map uuidToStubs, - final Map proxyConfigs) { + public YamlParseResultSet( + final List stubs, + final Map uuidToStubs, + final Map proxyConfigs) { this.stubs = stubs; this.uuidToStubs = uuidToStubs; this.proxyConfigs = proxyConfigs; this.webSocketConfigs = new LinkedHashMap<>(); } - public YamlParseResultSet(final List stubs, - final Map uuidToStubs, - final Map proxyConfigs, - final Map webSocketConfigs) { + public YamlParseResultSet( + final List stubs, + final Map uuidToStubs, + final Map proxyConfigs, + final Map webSocketConfigs) { this.stubs = stubs; this.uuidToStubs = uuidToStubs; this.proxyConfigs = proxyConfigs; diff --git a/src/main/java/io/github/azagniotov/stubby4j/yaml/YamlParser.java b/src/main/java/io/github/azagniotov/stubby4j/yaml/YamlParser.java index 76042b23c..670865b1f 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/yaml/YamlParser.java +++ b/src/main/java/io/github/azagniotov/stubby4j/yaml/YamlParser.java @@ -1,41 +1,20 @@ -package io.github.azagniotov.stubby4j.yaml; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import io.github.azagniotov.stubby4j.cli.ANSITerminal; -import io.github.azagniotov.stubby4j.stubs.AbstractBuilder; -import io.github.azagniotov.stubby4j.stubs.ReflectableStub; -import io.github.azagniotov.stubby4j.stubs.StubHttpLifecycle; -import io.github.azagniotov.stubby4j.stubs.StubRequest; -import io.github.azagniotov.stubby4j.stubs.StubResponse; -import io.github.azagniotov.stubby4j.stubs.proxy.StubProxyConfig; -import io.github.azagniotov.stubby4j.stubs.proxy.StubProxyStrategy; -import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketClientRequest; -import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketConfig; -import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketMessageType; -import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketOnMessageLifeCycle; -import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponse; -import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponsePolicy; -import io.github.azagniotov.stubby4j.utils.ObjectUtils; -import io.github.azagniotov.stubby4j.utils.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.yaml.snakeyaml.Yaml; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.UncheckedIOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; +package io.github.azagniotov.stubby4j.yaml; import static io.github.azagniotov.generics.TypeSafeConverter.asCheckedArrayList; import static io.github.azagniotov.generics.TypeSafeConverter.asCheckedLinkedHashMap; @@ -73,10 +52,47 @@ import static java.util.Optional.ofNullable; import static org.yaml.snakeyaml.DumperOptions.FlowStyle; +import io.github.azagniotov.stubby4j.cli.ANSITerminal; +import io.github.azagniotov.stubby4j.stubs.AbstractBuilder; +import io.github.azagniotov.stubby4j.stubs.ReflectableStub; +import io.github.azagniotov.stubby4j.stubs.StubHttpLifecycle; +import io.github.azagniotov.stubby4j.stubs.StubRequest; +import io.github.azagniotov.stubby4j.stubs.StubResponse; +import io.github.azagniotov.stubby4j.stubs.proxy.StubProxyConfig; +import io.github.azagniotov.stubby4j.stubs.proxy.StubProxyStrategy; +import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketClientRequest; +import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketConfig; +import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketMessageType; +import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketOnMessageLifeCycle; +import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponse; +import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponsePolicy; +import io.github.azagniotov.stubby4j.utils.ObjectUtils; +import io.github.azagniotov.stubby4j.utils.StringUtils; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.Yaml; + public class YamlParser { - static final String FAILED_TO_LOAD_FILE_ERR = "Failed to retrieveLoadedStubs response content using relative path specified in 'file'. Check that response content exists in relative path specified in 'file'"; + static final String FAILED_TO_LOAD_FILE_ERR = + "Failed to retrieveLoadedStubs response content using relative path specified in 'file'. Check that response content exists in relative path specified in 'file'"; private static final Logger LOGGER = LoggerFactory.getLogger(YamlParser.class); - private final static Yaml SNAKE_YAML = SnakeYaml.INSTANCE.getSnakeYaml(); + private static final Yaml SNAKE_YAML = SnakeYaml.INSTANCE.getSnakeYaml(); private final AtomicInteger parsedStubCounter = new AtomicInteger(); private String dataConfigHomeDirectory; @@ -85,11 +101,12 @@ public Object loadRawYamlConfig(final InputStream configAsStream) { } public boolean isMainYamlHasIncludes(final Object loadedYamlConfig) { - return loadedYamlConfig instanceof Map && - ((Map) loadedYamlConfig).containsKey(ConfigurableYAMLProperty.INCLUDES.toString()); + return loadedYamlConfig instanceof Map + && ((Map) loadedYamlConfig).containsKey(ConfigurableYAMLProperty.INCLUDES.toString()); } - public List getYamlIncludes(final String dataConfigHomeDirectory, final Object loadedYamlConfig) throws IOException { + public List getYamlIncludes(final String dataConfigHomeDirectory, final Object loadedYamlConfig) + throws IOException { final Object includePathsObject = ((Map) loadedYamlConfig).get(ConfigurableYAMLProperty.INCLUDES.toString()); final List includePaths = asCheckedArrayList(includePathsObject, String.class); @@ -102,7 +119,8 @@ public List getYamlIncludes(final String dataConfigHomeDirectory, final Ob return yamlIncludes; } - public YamlParseResultSet parse(final String dataConfigHomeDirectory, final String configContent) throws IOException { + public YamlParseResultSet parse(final String dataConfigHomeDirectory, final String configContent) + throws IOException { return parse(dataConfigHomeDirectory, constructInputStream(configContent)); } @@ -110,7 +128,8 @@ public YamlParseResultSet parse(final String dataConfigHomeDirectory, final File return parse(dataConfigHomeDirectory, constructInputStream(configFile)); } - private YamlParseResultSet parse(final String dataConfigHomeDirectory, final InputStream configAsStream) throws IOException { + private YamlParseResultSet parse(final String dataConfigHomeDirectory, final InputStream configAsStream) + throws IOException { this.dataConfigHomeDirectory = dataConfigHomeDirectory; final Object loadedConfig = loadYamlFromInputStream(configAsStream); @@ -123,7 +142,8 @@ private YamlParseResultSet parse(final String dataConfigHomeDirectory, final Inp final List yamlMappings = asCheckedArrayList(loadedConfig, Map.class); for (final Map yamlMapping : yamlMappings) { - final Map yamlMappingProperties = asCheckedLinkedHashMap(yamlMapping, String.class, Object.class); + final Map yamlMappingProperties = + asCheckedLinkedHashMap(yamlMapping, String.class, Object.class); if (isProxyConfigMapping(yamlMapping)) { // the YAML config file contains a top-level: // - proxy-config @@ -138,11 +158,14 @@ private YamlParseResultSet parse(final String dataConfigHomeDirectory, final Inp // - web-socket final StubWebSocketConfig stubWebSocketConfig = parseStubWebSocketConfig(yamlMappingProperties); if (webSocketConfigs.containsKey(stubWebSocketConfig.getUrl())) { - throw new IOException("Web socket config YAML contains duplicate URL: " + stubWebSocketConfig.getUrl()); + throw new IOException( + "Web socket config YAML contains duplicate URL: " + stubWebSocketConfig.getUrl()); } - if (ObjectUtils.isNull(stubWebSocketConfig.getOnOpenServerResponse()) && stubWebSocketConfig.getOnMessage().isEmpty()) { - throw new IOException("Web socket config must have at least one of the two 'on-open' or 'on-message' defined"); + if (ObjectUtils.isNull(stubWebSocketConfig.getOnOpenServerResponse()) + && stubWebSocketConfig.getOnMessage().isEmpty()) { + throw new IOException( + "Web socket config must have at least one of the two 'on-open' or 'on-message' defined"); } webSocketConfigs.put(stubWebSocketConfig.getUrl(), stubWebSocketConfig); @@ -189,7 +212,8 @@ private Object loadYamlFromInputStream(final InputStream configAsStream) throws } if (!(loadedConfig instanceof List)) { - throw new IOException("Loaded YAML root node must be an instance of ArrayList, otherwise something went wrong. Check provided YAML"); + throw new IOException( + "Loaded YAML root node must be an instance of ArrayList, otherwise something went wrong. Check provided YAML"); } return loadedConfig; } @@ -200,7 +224,8 @@ private StubProxyConfig parseStubProxyConfig(final Map yamlMappi for (final Map.Entry stubType : yamlMappingProperties.entrySet()) { final Object stubTypeValue = stubType.getValue(); - final Map stubbedProperties = asCheckedLinkedHashMap(stubTypeValue, String.class, Object.class); + final Map stubbedProperties = + asCheckedLinkedHashMap(stubTypeValue, String.class, Object.class); buildReflectableStub(stubbedProperties, proxyConfigBuilder); proxyConfigBuilder.withProxyConfigAsYAML(toCompleteYamlListString(yamlMappingProperties)); @@ -224,7 +249,8 @@ private StubWebSocketConfig parseStubWebSocketConfig(final Map y } else if (UUID.isA(stubTypeKey)) { webSocketConfigBuilder.withUuid((String) stubType.getValue()); } else if (stubTypeValue instanceof Map) { - final Map webSocketProperties = asCheckedLinkedHashMap(stubTypeValue, String.class, Object.class); + final Map webSocketProperties = + asCheckedLinkedHashMap(stubTypeValue, String.class, Object.class); for (final Map.Entry webSocketPropertyEntries : webSocketProperties.entrySet()) { final String webSocketPropertyKey = webSocketPropertyEntries.getKey(); @@ -232,10 +258,13 @@ private StubWebSocketConfig parseStubWebSocketConfig(final Map y if (ON_OPEN_SERVER_RESPONSE.isA(webSocketPropertyKey)) { - final Map onOpenServerResponseProperties = asCheckedLinkedHashMap(webSocketPropertyValue, String.class, Object.class); + final Map onOpenServerResponseProperties = + asCheckedLinkedHashMap(webSocketPropertyValue, String.class, Object.class); - final StubWebSocketServerResponse.Builder serverResponseStubBuilder = buildReflectableStub(onOpenServerResponseProperties, new StubWebSocketServerResponse.Builder()); - serverResponseStubBuilder.withWebSocketServerResponseAsYAML(toYaml(webSocketProperties, ON_OPEN_SERVER_RESPONSE)); + final StubWebSocketServerResponse.Builder serverResponseStubBuilder = buildReflectableStub( + onOpenServerResponseProperties, new StubWebSocketServerResponse.Builder()); + serverResponseStubBuilder.withWebSocketServerResponseAsYAML( + toYaml(webSocketProperties, ON_OPEN_SERVER_RESPONSE)); webSocketConfigBuilder.withOnOpenServerResponse(serverResponseStubBuilder.build()); } else if (ON_MESSAGE.isA(webSocketPropertyKey)) { @@ -246,27 +275,34 @@ private StubWebSocketConfig parseStubWebSocketConfig(final Map y final List onMessageLifeCycles = asCheckedArrayList(webSocketPropertyValue, Map.class); for (Map onMessageLifeCycle : onMessageLifeCycles) { - final Map onMessageLifeCycleObjects = asCheckedLinkedHashMap(onMessageLifeCycle, String.class, Object.class); + final Map onMessageLifeCycleObjects = + asCheckedLinkedHashMap(onMessageLifeCycle, String.class, Object.class); final Object rawClientRequest = onMessageLifeCycleObjects.get(CLIENT_REQUEST.toString()); final StubWebSocketClientRequest clientRequest = buildReflectableStub( - asCheckedLinkedHashMap(rawClientRequest, String.class, Object.class), - new StubWebSocketClientRequest.Builder()) + asCheckedLinkedHashMap(rawClientRequest, String.class, Object.class), + new StubWebSocketClientRequest.Builder()) .withWebSocketClientRequestAsYAML(toYaml(onMessageLifeCycleObjects, CLIENT_REQUEST)) .build(); - checkAndThrowWhenClientRequestDuplicateBodies(clientRequestBodyTextHashCodeCache, clientRequestBodyBytesHashCodeCache, clientRequest); + checkAndThrowWhenClientRequestDuplicateBodies( + clientRequestBodyTextHashCodeCache, + clientRequestBodyBytesHashCodeCache, + clientRequest); final Object rawServerResponse = onMessageLifeCycleObjects.get(SERVER_RESPONSE.toString()); final StubWebSocketServerResponse serverResponse = buildReflectableStub( - asCheckedLinkedHashMap(rawServerResponse, String.class, Object.class), - new StubWebSocketServerResponse.Builder()) - .withWebSocketServerResponseAsYAML(toYaml(onMessageLifeCycleObjects, SERVER_RESPONSE)) + asCheckedLinkedHashMap(rawServerResponse, String.class, Object.class), + new StubWebSocketServerResponse.Builder()) + .withWebSocketServerResponseAsYAML( + toYaml(onMessageLifeCycleObjects, SERVER_RESPONSE)) .build(); - final String lifeCycleCompleteYAML = toCompleteYamlListString(asCheckedLinkedHashMap(onMessageLifeCycle, String.class, Object.class)); + final String lifeCycleCompleteYAML = toCompleteYamlListString( + asCheckedLinkedHashMap(onMessageLifeCycle, String.class, Object.class)); - lifeCycles.add(new StubWebSocketOnMessageLifeCycle(clientRequest, serverResponse, lifeCycleCompleteYAML)); + lifeCycles.add(new StubWebSocketOnMessageLifeCycle( + clientRequest, serverResponse, lifeCycleCompleteYAML)); } webSocketConfigBuilder.withOnMessage(lifeCycles); @@ -285,20 +321,24 @@ private StubWebSocketConfig parseStubWebSocketConfig(final Map y return stubWebSocketConfig; } - private void checkAndThrowWhenClientRequestDuplicateBodies(final Set clientRequestBodyTextHashCodeCache, - final Set clientRequestBodyBytesHashCodeCache, - final StubWebSocketClientRequest clientRequest) { + private void checkAndThrowWhenClientRequestDuplicateBodies( + final Set clientRequestBodyTextHashCodeCache, + final Set clientRequestBodyBytesHashCodeCache, + final StubWebSocketClientRequest clientRequest) { if (clientRequest.getMessageType() == StubWebSocketMessageType.TEXT) { - final int clientRequestBodyTextHashCode = clientRequest.getBodyAsString().hashCode(); + final int clientRequestBodyTextHashCode = + clientRequest.getBodyAsString().hashCode(); if (clientRequestBodyTextHashCodeCache.contains(clientRequestBodyTextHashCode)) { - throw new UncheckedIOException(new IOException("Web socket on-message contains multiple client-request with the same body text")); + throw new UncheckedIOException(new IOException( + "Web socket on-message contains multiple client-request with the same body text")); } else { clientRequestBodyTextHashCodeCache.add(clientRequestBodyTextHashCode); } } else { final int clientRequestBodyBytesHashCode = Arrays.hashCode(clientRequest.getBodyAsBytes()); if (clientRequestBodyBytesHashCodeCache.contains(clientRequestBodyBytesHashCode)) { - throw new UncheckedIOException(new IOException("Web socket on-message contains multiple client-request with the same body bytes")); + throw new UncheckedIOException(new IOException( + "Web socket on-message contains multiple client-request with the same body bytes")); } else { clientRequestBodyBytesHashCodeCache.add(clientRequestBodyBytesHashCode); } @@ -317,7 +357,8 @@ private StubHttpLifecycle parseStubbedHttpLifecycleConfig(final Map stubbedProperties = asCheckedLinkedHashMap(stubTypeValue, String.class, Object.class); + final Map stubbedProperties = + asCheckedLinkedHashMap(stubTypeValue, String.class, Object.class); if (REQUEST.isA(stubTypeKey)) { parseStubbedRequestConfig(stubBuilder, stubbedProperties); @@ -332,7 +373,8 @@ private StubHttpLifecycle parseStubbedHttpLifecycleConfig(final Map requestProperties) { - final StubRequest.Builder requestStubBuilder = buildReflectableStub(requestProperties, new StubRequest.Builder()); + private void parseStubbedRequestConfig( + final StubHttpLifecycle.Builder stubBuilder, final Map requestProperties) { + final StubRequest.Builder requestStubBuilder = + buildReflectableStub(requestProperties, new StubRequest.Builder()); final StubRequest stubRequest = requestStubBuilder.build(); stubRequest.compileRegexPatternsAndCache(); stubBuilder.withRequest(stubRequest); } - private void parseStubbedResponseConfig(final StubHttpLifecycle.Builder stubBuilder, final Map responseProperties) { - final StubResponse.Builder responseStubBuilder = buildReflectableStub(responseProperties, new StubResponse.Builder()); + private void parseStubbedResponseConfig( + final StubHttpLifecycle.Builder stubBuilder, final Map responseProperties) { + final StubResponse.Builder responseStubBuilder = + buildReflectableStub(responseProperties, new StubResponse.Builder()); stubBuilder.withResponse(responseStubBuilder.build()); } - private > B buildReflectableStub(final Map stubbedProperties, final B stubTypeBuilder) { + private > B buildReflectableStub( + final Map stubbedProperties, final B stubTypeBuilder) { for (final Map.Entry propertyPair : stubbedProperties.entrySet()) { @@ -369,14 +416,16 @@ private > B buildReflect } if (rawFieldNameValue instanceof Map) { - final Map rawHeaders = asCheckedLinkedHashMap(rawFieldNameValue, String.class, String.class); + final Map rawHeaders = + asCheckedLinkedHashMap(rawFieldNameValue, String.class, String.class); final Map headers = configureAuthorizationHeader(rawHeaders); stubTypeBuilder.stage(fromString(stageableFieldName), of(headers)); continue; } if (METHOD.isA(stageableFieldName)) { - final ArrayList methods = new ArrayList<>(Collections.singletonList(objectToString(rawFieldNameValue))); + final ArrayList methods = + new ArrayList<>(Collections.singletonList(objectToString(rawFieldNameValue))); stubTypeBuilder.stage(fromString(stageableFieldName), of(methods)); continue; } @@ -394,8 +443,10 @@ private > B buildReflect throw new IllegalArgumentException(stubbedProperty); } - final Optional stubProxyStrategyOptional = StubProxyStrategy.ofNullableProperty(stubbedProperty); - final Optional stubProxyStrategyObjectOptional = stubProxyStrategyOptional.map(stubProxyStrategy -> stubProxyStrategy); + final Optional stubProxyStrategyOptional = + StubProxyStrategy.ofNullableProperty(stubbedProperty); + final Optional stubProxyStrategyObjectOptional = + stubProxyStrategyOptional.map(stubProxyStrategy -> stubProxyStrategy); stubTypeBuilder.stage(fromString(stageableFieldName), stubProxyStrategyObjectOptional); continue; } @@ -407,8 +458,10 @@ private > B buildReflect throw new IllegalArgumentException(stubbedProperty); } - final Optional stubWebSocketServerResponseStrategy = StubWebSocketServerResponsePolicy.ofNullableProperty(stubbedProperty); - final Optional stubWebSocketServerResponseStrategyOptional = stubWebSocketServerResponseStrategy.map(stubProxyStrategy -> stubProxyStrategy); + final Optional stubWebSocketServerResponseStrategy = + StubWebSocketServerResponsePolicy.ofNullableProperty(stubbedProperty); + final Optional stubWebSocketServerResponseStrategyOptional = + stubWebSocketServerResponseStrategy.map(stubProxyStrategy -> stubProxyStrategy); stubTypeBuilder.stage(fromString(stageableFieldName), stubWebSocketServerResponseStrategyOptional); continue; } @@ -420,8 +473,10 @@ private > B buildReflect throw new IllegalArgumentException(stubbedProperty); } - final Optional stubWebSocketMessageType = StubWebSocketMessageType.ofNullableProperty(stubbedProperty); - final Optional stubWebSocketMessageTypeOptional = stubWebSocketMessageType.map(stubProxyStrategy -> stubProxyStrategy); + final Optional stubWebSocketMessageType = + StubWebSocketMessageType.ofNullableProperty(stubbedProperty); + final Optional stubWebSocketMessageTypeOptional = + stubWebSocketMessageType.map(stubProxyStrategy -> stubProxyStrategy); stubTypeBuilder.stage(fromString(stageableFieldName), stubWebSocketMessageTypeOptional); continue; } @@ -432,17 +487,20 @@ private > B buildReflect return stubTypeBuilder; } - private void parseStubbedResponseListConfig(final StubHttpLifecycle.Builder stubBuilder, final Map.Entry httpTypeConfig) { + private void parseStubbedResponseListConfig( + final StubHttpLifecycle.Builder stubBuilder, final Map.Entry httpTypeConfig) { final List responseProperties = asCheckedArrayList(httpTypeConfig.getValue(), Map.class); stubBuilder.withResponse(buildStubResponseList(responseProperties, new StubResponse.Builder())); } - private List buildStubResponseList(final List responseProperties, final StubResponse.Builder stubResponseBuilder) { + private List buildStubResponseList( + final List responseProperties, final StubResponse.Builder stubResponseBuilder) { final List stubResponses = new LinkedList<>(); for (final Map rawPropertyPairs : responseProperties) { - final Map propertyPairs = asCheckedLinkedHashMap(rawPropertyPairs, String.class, Object.class); + final Map propertyPairs = + asCheckedLinkedHashMap(rawPropertyPairs, String.class, Object.class); for (final Map.Entry propertyPair : propertyPairs.entrySet()) { final String stageableFieldName = propertyPair.getKey(); checkStubbedProperty(stageableFieldName, RESPONSE.toString()); @@ -478,17 +536,21 @@ private Optional loadFileContentFromFileUrl(final Object configPropertyN } private String toCompleteYamlListString(final Map yamlMappingProperties) { - final List> root = new ArrayList>() {{ - add(yamlMappingProperties); - }}; + final List> root = new ArrayList>() { + { + add(yamlMappingProperties); + } + }; return SNAKE_YAML.dumpAs(root, null, FlowStyle.BLOCK); } private String toYaml(final Map yamlMappingProperties, final ConfigurableYAMLProperty stubName) { - final Map httpType = new HashMap() {{ - put(stubName.toString(), yamlMappingProperties.get(stubName.toString())); - }}; + final Map httpType = new HashMap() { + { + put(stubName.toString(), yamlMappingProperties.get(stubName.toString())); + } + }; return SNAKE_YAML.dumpAs(httpType, null, FlowStyle.BLOCK); } @@ -503,7 +565,8 @@ private Map configureAuthorizationHeader(final Map configureAuthorizationHeader(final Map cache = Cache.stubHttpLifecycleCache(true); assertThrows(UnsupportedOperationException.class, cache::cache); } -} \ No newline at end of file +} diff --git a/src/test/java/io/github/azagniotov/stubby4j/cli/CommandLineInterpreterTest.java b/src/test/java/io/github/azagniotov/stubby4j/cli/CommandLineInterpreterTest.java index 0e056d03c..444da746e 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/cli/CommandLineInterpreterTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/cli/CommandLineInterpreterTest.java @@ -1,16 +1,30 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.cli; +import static com.google.common.truth.Truth.assertThat; + +import java.util.Map; import org.apache.commons.cli.MissingArgumentException; import org.apache.commons.cli.ParseException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.util.Map; - -import static com.google.common.truth.Truth.assertThat; - - public class CommandLineInterpreterTest { @Rule @@ -19,7 +33,7 @@ public class CommandLineInterpreterTest { @Test public void testIsHelpWhenShortOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-h"}); + commandLineInterpreter.parseCommandLine(new String[] {"-h"}); final boolean isHelp = commandLineInterpreter.isHelp(); assertThat(isHelp).isTrue(); @@ -28,7 +42,7 @@ public void testIsHelpWhenShortOptionGiven() throws Exception { @Test public void testIsHelpWhenLongOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--help"}); + commandLineInterpreter.parseCommandLine(new String[] {"--help"}); final boolean isHelp = commandLineInterpreter.isHelp(); assertThat(isHelp).isTrue(); @@ -37,7 +51,7 @@ public void testIsHelpWhenLongOptionGiven() throws Exception { @Test public void testIsVersionWhenShortOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-v"}); + commandLineInterpreter.parseCommandLine(new String[] {"-v"}); final boolean isVersion = commandLineInterpreter.isVersion(); assertThat(isVersion).isTrue(); @@ -46,7 +60,7 @@ public void testIsVersionWhenShortOptionGiven() throws Exception { @Test public void testIsVersionWhenLongOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--version"}); + commandLineInterpreter.parseCommandLine(new String[] {"--version"}); final boolean isVersion = commandLineInterpreter.isVersion(); assertThat(isVersion).isTrue(); @@ -55,7 +69,7 @@ public void testIsVersionWhenLongOptionGiven() throws Exception { @Test public void testIsDebugWhenLongOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--debug"}); + commandLineInterpreter.parseCommandLine(new String[] {"--debug"}); final boolean isDebug = commandLineInterpreter.isDebug(); assertThat(isDebug).isTrue(); @@ -64,7 +78,7 @@ public void testIsDebugWhenLongOptionGiven() throws Exception { @Test public void testIsDebugWhenShortgOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-o"}); + commandLineInterpreter.parseCommandLine(new String[] {"-o"}); final boolean isDebug = commandLineInterpreter.isDebug(); assertThat(isDebug).isTrue(); @@ -73,8 +87,10 @@ public void testIsDebugWhenShortgOptionGiven() throws Exception { @Test public void testIsCacheDisabledWhenLongOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--disable_stub_caching"}); - final boolean isCacheDisabled = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_DISABLE_STUB_CACHING); + commandLineInterpreter.parseCommandLine(new String[] {"--disable_stub_caching"}); + final boolean isCacheDisabled = commandLineInterpreter + .getCommandlineParams() + .containsKey(CommandLineInterpreter.OPTION_DISABLE_STUB_CACHING); assertThat(isCacheDisabled).isTrue(); } @@ -82,8 +98,10 @@ public void testIsCacheDisabledWhenLongOptionGiven() throws Exception { @Test public void testIsCacheDisabledWhenShortOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-dc"}); - final boolean isCacheDisabled = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_DISABLE_STUB_CACHING); + commandLineInterpreter.parseCommandLine(new String[] {"-dc"}); + final boolean isCacheDisabled = commandLineInterpreter + .getCommandlineParams() + .containsKey(CommandLineInterpreter.OPTION_DISABLE_STUB_CACHING); assertThat(isCacheDisabled).isTrue(); } @@ -91,8 +109,9 @@ public void testIsCacheDisabledWhenShortOptionGiven() throws Exception { @Test public void testIsAdminPortalDisabledWhenLongOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--disable_admin_portal"}); - final boolean isAdminDisabled = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_DISABLE_ADMIN); + commandLineInterpreter.parseCommandLine(new String[] {"--disable_admin_portal"}); + final boolean isAdminDisabled = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_DISABLE_ADMIN); assertThat(isAdminDisabled).isTrue(); } @@ -100,8 +119,9 @@ public void testIsAdminPortalDisabledWhenLongOptionGiven() throws Exception { @Test public void testIsAdminPortalDisabledWhenShortOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-da"}); - final boolean isAdminDisabled = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_DISABLE_ADMIN); + commandLineInterpreter.parseCommandLine(new String[] {"-da"}); + final boolean isAdminDisabled = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_DISABLE_ADMIN); assertThat(isAdminDisabled).isTrue(); } @@ -109,8 +129,9 @@ public void testIsAdminPortalDisabledWhenShortOptionGiven() throws Exception { @Test public void testIsSslDisabledWhenLongOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--disable_ssl"}); - final boolean isSslDisabled = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_DISABLE_SSL); + commandLineInterpreter.parseCommandLine(new String[] {"--disable_ssl"}); + final boolean isSslDisabled = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_DISABLE_SSL); assertThat(isSslDisabled).isTrue(); } @@ -118,8 +139,9 @@ public void testIsSslDisabledWhenLongOptionGiven() throws Exception { @Test public void testIsSslDisabledWhenShortOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-ds"}); - final boolean isSslDisabled = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_DISABLE_SSL); + commandLineInterpreter.parseCommandLine(new String[] {"-ds"}); + final boolean isSslDisabled = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_DISABLE_SSL); assertThat(isSslDisabled).isTrue(); } @@ -127,7 +149,7 @@ public void testIsSslDisabledWhenShortOptionGiven() throws Exception { @Test public void testIsMuteWhenShortOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-m"}); + commandLineInterpreter.parseCommandLine(new String[] {"-m"}); final boolean isMuteProvided = commandLineInterpreter.isMute(); assertThat(isMuteProvided).isTrue(); @@ -136,17 +158,16 @@ public void testIsMuteWhenShortOptionGiven() throws Exception { @Test public void testIsMuteWhenLongOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--mute"}); + commandLineInterpreter.parseCommandLine(new String[] {"--mute"}); final boolean isMuteProvided = commandLineInterpreter.isMute(); assertThat(isMuteProvided).isTrue(); } - @Test public void testIsYamlProvidedWhenShortOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-d", "somefilename.yaml"}); + commandLineInterpreter.parseCommandLine(new String[] {"-d", "somefilename.yaml"}); final boolean isYamlProvided = commandLineInterpreter.isYamlProvided(); assertThat(isYamlProvided).isTrue(); @@ -155,7 +176,7 @@ public void testIsYamlProvidedWhenShortOptionGiven() throws Exception { @Test public void testIsYamlProvidedWhenLongOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--data", "somefilename.yaml"}); + commandLineInterpreter.parseCommandLine(new String[] {"--data", "somefilename.yaml"}); final boolean isYamlProvided = commandLineInterpreter.isYamlProvided(); assertThat(isYamlProvided).isTrue(); @@ -164,8 +185,9 @@ public void testIsYamlProvidedWhenLongOptionGiven() throws Exception { @Test public void testtHasAdminPortWhenShortOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-a", "888"}); - final boolean isAdmin = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_ADMINPORT); + commandLineInterpreter.parseCommandLine(new String[] {"-a", "888"}); + final boolean isAdmin = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_ADMINPORT); assertThat(isAdmin).isTrue(); } @@ -173,8 +195,9 @@ public void testtHasAdminPortWhenShortOptionGiven() throws Exception { @Test public void testHasAdminPortWhenLongOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--admin", "8888"}); - final boolean isAdmin = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_ADMINPORT); + commandLineInterpreter.parseCommandLine(new String[] {"--admin", "8888"}); + final boolean isAdmin = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_ADMINPORT); assertThat(isAdmin).isTrue(); } @@ -182,8 +205,9 @@ public void testHasAdminPortWhenLongOptionGiven() throws Exception { @Test public void testtHasStubsPortWhenShortOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-s", "888"}); - final boolean isAdmin = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_CLIENTPORT); + commandLineInterpreter.parseCommandLine(new String[] {"-s", "888"}); + final boolean isAdmin = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_CLIENTPORT); assertThat(isAdmin).isTrue(); } @@ -191,8 +215,9 @@ public void testtHasStubsPortWhenShortOptionGiven() throws Exception { @Test public void testtHasStubsPortWhenLongOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--stubs", "8888"}); - final boolean isAdmin = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_CLIENTPORT); + commandLineInterpreter.parseCommandLine(new String[] {"--stubs", "8888"}); + final boolean isAdmin = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_CLIENTPORT); assertThat(isAdmin).isTrue(); } @@ -200,8 +225,9 @@ public void testtHasStubsPortWhenLongOptionGiven() throws Exception { @Test public void testtIsWatchWhenShortOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-w"}); - final boolean isWatch = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_WATCH); + commandLineInterpreter.parseCommandLine(new String[] {"-w"}); + final boolean isWatch = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_WATCH); assertThat(isWatch).isTrue(); } @@ -209,8 +235,9 @@ public void testtIsWatchWhenShortOptionGiven() throws Exception { @Test public void testIsWatchWhenLongOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--watch"}); - final boolean isWatch = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_WATCH); + commandLineInterpreter.parseCommandLine(new String[] {"--watch"}); + final boolean isWatch = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_WATCH); assertThat(isWatch).isTrue(); } @@ -218,8 +245,9 @@ public void testIsWatchWhenLongOptionGiven() throws Exception { @Test public void testtHasKeystoreLocationWhenShortOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-k", "some/path/to/key"}); - final boolean isKeystore = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_KEYSTORE); + commandLineInterpreter.parseCommandLine(new String[] {"-k", "some/path/to/key"}); + final boolean isKeystore = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_KEYSTORE); assertThat(isKeystore).isTrue(); } @@ -227,8 +255,9 @@ public void testtHasKeystoreLocationWhenShortOptionGiven() throws Exception { @Test public void testHasKeystoreLocationWhenLongOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--keystore", "some/path/to/key"}); - final boolean isKeystore = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_KEYSTORE); + commandLineInterpreter.parseCommandLine(new String[] {"--keystore", "some/path/to/key"}); + final boolean isKeystore = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_KEYSTORE); assertThat(isKeystore).isTrue(); } @@ -236,8 +265,9 @@ public void testHasKeystoreLocationWhenLongOptionGiven() throws Exception { @Test public void testtHasLocationWhenShortOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-l", "hostname"}); - final boolean isLocation = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_ADDRESS); + commandLineInterpreter.parseCommandLine(new String[] {"-l", "hostname"}); + final boolean isLocation = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_ADDRESS); assertThat(isLocation).isTrue(); } @@ -245,8 +275,9 @@ public void testtHasLocationWhenShortOptionGiven() throws Exception { @Test public void testHasLocationWhenLongOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--location", "hostname"}); - final boolean isLocation = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_ADDRESS); + commandLineInterpreter.parseCommandLine(new String[] {"--location", "hostname"}); + final boolean isLocation = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_ADDRESS); assertThat(isLocation).isTrue(); } @@ -254,8 +285,9 @@ public void testHasLocationWhenLongOptionGiven() throws Exception { @Test public void testHasPasswordWhenShortOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-p", "very-complex-password"}); - final boolean isPassword = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_KEYPASS); + commandLineInterpreter.parseCommandLine(new String[] {"-p", "very-complex-password"}); + final boolean isPassword = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_KEYPASS); assertThat(isPassword).isTrue(); } @@ -263,8 +295,9 @@ public void testHasPasswordWhenShortOptionGiven() throws Exception { @Test public void testHasPasswordWhenLongOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--password", "very-complex-password"}); - final boolean isPassword = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_KEYPASS); + commandLineInterpreter.parseCommandLine(new String[] {"--password", "very-complex-password"}); + final boolean isPassword = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_KEYPASS); assertThat(isPassword).isTrue(); } @@ -272,8 +305,9 @@ public void testHasPasswordWhenLongOptionGiven() throws Exception { @Test public void testHasSslPortWhenShortOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-t", "2443"}); - final boolean isSslGiven = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_TLSPORT); + commandLineInterpreter.parseCommandLine(new String[] {"-t", "2443"}); + final boolean isSslGiven = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_TLSPORT); assertThat(isSslGiven).isTrue(); } @@ -281,8 +315,9 @@ public void testHasSslPortWhenShortOptionGiven() throws Exception { @Test public void testHasSslPortWhenLongOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--tls", "2443"}); - final boolean isSslGiven = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_TLSPORT); + commandLineInterpreter.parseCommandLine(new String[] {"--tls", "2443"}); + final boolean isSslGiven = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_TLSPORT); assertThat(isSslGiven).isTrue(); } @@ -290,8 +325,10 @@ public void testHasSslPortWhenLongOptionGiven() throws Exception { @Test public void enabledTlsWithAlpnHttp2WhenShortOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-ta"}); - final boolean isTlsWithAlpnEnabled = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_ENABLE_TLS_WITH_ALPN_AND_HTTP_2); + commandLineInterpreter.parseCommandLine(new String[] {"-ta"}); + final boolean isTlsWithAlpnEnabled = commandLineInterpreter + .getCommandlineParams() + .containsKey(CommandLineInterpreter.OPTION_ENABLE_TLS_WITH_ALPN_AND_HTTP_2); assertThat(isTlsWithAlpnEnabled).isTrue(); } @@ -299,8 +336,10 @@ public void enabledTlsWithAlpnHttp2WhenShortOptionGiven() throws Exception { @Test public void enabledTlsWithAlpnHttp2WhenLongOptionGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--enable_tls_with_alpn_and_http_2"}); - final boolean isTlsWithAlpnEnabled = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_ENABLE_TLS_WITH_ALPN_AND_HTTP_2); + commandLineInterpreter.parseCommandLine(new String[] {"--enable_tls_with_alpn_and_http_2"}); + final boolean isTlsWithAlpnEnabled = commandLineInterpreter + .getCommandlineParams() + .containsKey(CommandLineInterpreter.OPTION_ENABLE_TLS_WITH_ALPN_AND_HTTP_2); assertThat(isTlsWithAlpnEnabled).isTrue(); } @@ -308,18 +347,21 @@ public void enabledTlsWithAlpnHttp2WhenLongOptionGiven() throws Exception { @Test public void shouldRemoveOptionTlsWithAlpnHttp2WhenDisableSslGiven() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--enable_tls_with_alpn_and_http_2", "--disable_ssl"}); - final boolean isTlsWithAlpnEnabled = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_ENABLE_TLS_WITH_ALPN_AND_HTTP_2); + commandLineInterpreter.parseCommandLine(new String[] {"--enable_tls_with_alpn_and_http_2", "--disable_ssl"}); + final boolean isTlsWithAlpnEnabled = commandLineInterpreter + .getCommandlineParams() + .containsKey(CommandLineInterpreter.OPTION_ENABLE_TLS_WITH_ALPN_AND_HTTP_2); assertThat(isTlsWithAlpnEnabled).isFalse(); - final boolean disableSsl = commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_DISABLE_SSL); + final boolean disableSsl = + commandLineInterpreter.getCommandlineParams().containsKey(CommandLineInterpreter.OPTION_DISABLE_SSL); assertThat(disableSsl).isTrue(); } @Test public void shouldBeFalseThatYamlIsNotProvided() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"cheburashka", "zagniotov"}); + commandLineInterpreter.parseCommandLine(new String[] {"cheburashka", "zagniotov"}); final boolean isYamlProvided = commandLineInterpreter.isYamlProvided(); assertThat(isYamlProvided).isFalse(); @@ -330,7 +372,7 @@ public void shouldFailOnInvalidCommandlineLongOptionString() throws Exception { expectedException.expect(ParseException.class); final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--cheburashka"}); + commandLineInterpreter.parseCommandLine(new String[] {"--cheburashka"}); } @Test @@ -338,7 +380,7 @@ public void shouldFailOnInvalidCommandlineShortOptionString() throws Exception { expectedException.expect(ParseException.class); final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-z"}); + commandLineInterpreter.parseCommandLine(new String[] {"-z"}); } @Test @@ -346,7 +388,7 @@ public void shouldFailOnMissingArgumentForExistingShortOption() throws Exception expectedException.expect(MissingArgumentException.class); final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"-a"}); + commandLineInterpreter.parseCommandLine(new String[] {"-a"}); } @Test @@ -354,14 +396,13 @@ public void shouldFailOnMissingArgumentForExistingLongOption() throws Exception expectedException.expect(MissingArgumentException.class); final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--data"}); + commandLineInterpreter.parseCommandLine(new String[] {"--data"}); } - @Test public void shouldReturnOneCommandlineParamWhenHelpArgPresent() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--help"}); + commandLineInterpreter.parseCommandLine(new String[] {"--help"}); final Map params = commandLineInterpreter.getCommandlineParams(); assertThat(params.size()).isEqualTo(1); @@ -370,7 +411,7 @@ public void shouldReturnOneCommandlineParamWhenHelpArgPresent() throws Exception @Test public void shouldReturnEmptyCommandlineParams() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{}); + commandLineInterpreter.parseCommandLine(new String[] {}); final Map params = commandLineInterpreter.getCommandlineParams(); assertThat(params).isEmpty(); @@ -379,9 +420,10 @@ public void shouldReturnEmptyCommandlineParams() throws Exception { @Test public void shouldReturnCommandlineParams() throws Exception { final CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter(); - commandLineInterpreter.parseCommandLine(new String[]{"--data", "somefilename.yaml", "-s", "12345", "--admin", "567"}); + commandLineInterpreter.parseCommandLine( + new String[] {"--data", "somefilename.yaml", "-s", "12345", "--admin", "567"}); final Map params = commandLineInterpreter.getCommandlineParams(); assertThat(params.size()).isEqualTo(3); } -} \ No newline at end of file +} diff --git a/src/test/java/io/github/azagniotov/stubby4j/handlers/AbstractHandlerExtensionTest.java b/src/test/java/io/github/azagniotov/stubby4j/handlers/AbstractHandlerExtensionTest.java index 8695fa11f..5b355a71d 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/handlers/AbstractHandlerExtensionTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/handlers/AbstractHandlerExtensionTest.java @@ -1,6 +1,27 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers; +import static com.google.common.truth.Truth.assertThat; +import static org.mockito.Mockito.when; + import io.github.azagniotov.stubby4j.cli.ANSITerminal; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Request; import org.junit.BeforeClass; import org.junit.Test; @@ -8,12 +29,6 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import static com.google.common.truth.Truth.assertThat; -import static org.mockito.Mockito.when; - @RunWith(MockitoJUnitRunner.class) public class AbstractHandlerExtensionTest { @@ -37,10 +52,8 @@ public void shouldDetermineRequestAsHandledWhenBaseRequestHandled() throws Excep when(mockBaseRequest.isHandled()).thenReturn(true); - final boolean isHandled = abstractHandlerExtension.logAndCheckIsHandled("someName", - mockBaseRequest, - mockHttpServletRequest, - mockHttpServletResponse); + final boolean isHandled = abstractHandlerExtension.logAndCheckIsHandled( + "someName", mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); assertThat(isHandled).isTrue(); } @@ -52,10 +65,8 @@ public void shouldDetermineRequestAsHandledWhenResponseCommitted() throws Except when(mockBaseRequest.isHandled()).thenReturn(false); when(mockHttpServletResponse.isCommitted()).thenReturn(true); - final boolean isHandled = abstractHandlerExtension.logAndCheckIsHandled("someName", - mockBaseRequest, - mockHttpServletRequest, - mockHttpServletResponse); + final boolean isHandled = abstractHandlerExtension.logAndCheckIsHandled( + "someName", mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); assertThat(isHandled).isTrue(); } @@ -67,16 +78,11 @@ public void shouldDetermineRequestAsNotHandled() throws Exception { when(mockBaseRequest.isHandled()).thenReturn(false); when(mockHttpServletResponse.isCommitted()).thenReturn(false); - final boolean isHandled = abstractHandlerExtension.logAndCheckIsHandled("someName", - mockBaseRequest, - mockHttpServletRequest, - mockHttpServletResponse); + final boolean isHandled = abstractHandlerExtension.logAndCheckIsHandled( + "someName", mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); assertThat(isHandled).isFalse(); } - private class DummyHandler implements AbstractHandlerExtension { - - } - -} \ No newline at end of file + private class DummyHandler implements AbstractHandlerExtension {} +} diff --git a/src/test/java/io/github/azagniotov/stubby4j/handlers/AjaxResourceContentHandlerTest.java b/src/test/java/io/github/azagniotov/stubby4j/handlers/AjaxResourceContentHandlerTest.java index a5bde0af1..8c9eb83cb 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/handlers/AjaxResourceContentHandlerTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/handlers/AjaxResourceContentHandlerTest.java @@ -1,10 +1,40 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers; +import static com.google.common.truth.Truth.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.stubs.StubHttpLifecycle; -import io.github.azagniotov.stubby4j.stubs.proxy.StubProxyConfig; import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.stubs.StubTypes; +import io.github.azagniotov.stubby4j.stubs.proxy.StubProxyConfig; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Optional; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.server.Request; import org.junit.Before; @@ -19,27 +49,14 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Optional; - -import static com.google.common.truth.Truth.assertThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - - @RunWith(MockitoJUnitRunner.class) public class AjaxResourceContentHandlerTest { - private static final Optional STUB_HTTP_LIFECYCLE_OPTIONAL = Optional.of(new StubHttpLifecycle.Builder().build()); - private static final StubProxyConfig STUB_PROXY_CONFIG = new StubProxyConfig.Builder().withPropertyEndpoint("http://google.com").build(); + private static final Optional STUB_HTTP_LIFECYCLE_OPTIONAL = + Optional.of(new StubHttpLifecycle.Builder().build()); + private static final StubProxyConfig STUB_PROXY_CONFIG = new StubProxyConfig.Builder() + .withPropertyEndpoint("http://google.com") + .build(); @Rule public ExpectedException expectedException = ExpectedException.none(); @@ -74,7 +91,8 @@ public class AjaxResourceContentHandlerTest { @Captor private ArgumentCaptor stubTypeCaptor; - private AjaxResourceContentHandler spyAjaxResourceContentHandler = new AjaxResourceContentHandler(mockStubRepository); + private AjaxResourceContentHandler spyAjaxResourceContentHandler = + new AjaxResourceContentHandler(mockStubRepository); @BeforeClass public static void beforeClass() throws Exception { @@ -93,14 +111,23 @@ public void beforeEach() throws Exception { public void shouldDetermineRequestAsHandledWhenBaseRequestHandled() throws Exception { when(mockBaseRequest.isHandled()).thenReturn(true); - spyAjaxResourceContentHandler.handle("/some/uri", mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); + spyAjaxResourceContentHandler.handle( + "/some/uri", mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); verify(mockBaseRequest, never()).setHandled(eq(true)); verify(mockHttpServletResponse, never()).setStatus(anyInt()); - verify(spyAjaxResourceContentHandler, never()).renderProxyConfigAjaxResponse(any(HttpServletResponse.class), anyString(), any(StubProxyConfig.class)); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), any(StubTypes.class), anyString(), any(StubHttpLifecycle.class)); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderProxyConfigAjaxResponse(any(HttpServletResponse.class), anyString(), any(StubProxyConfig.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), + any(StubTypes.class), + anyString(), + any(StubHttpLifecycle.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); } @Test @@ -108,14 +135,23 @@ public void shouldDetermineRequestAsHandledWhenResponseCommitted() throws Except when(mockBaseRequest.isHandled()).thenReturn(false); when(mockHttpServletResponse.isCommitted()).thenReturn(true); - spyAjaxResourceContentHandler.handle("/some/uri", mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); + spyAjaxResourceContentHandler.handle( + "/some/uri", mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); verify(mockBaseRequest, never()).setHandled(eq(true)); verify(mockHttpServletResponse, never()).setStatus(anyInt()); - verify(spyAjaxResourceContentHandler, never()).renderProxyConfigAjaxResponse(any(HttpServletResponse.class), anyString(), any(StubProxyConfig.class)); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), any(StubTypes.class), anyString(), any(StubHttpLifecycle.class)); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderProxyConfigAjaxResponse(any(HttpServletResponse.class), anyString(), any(StubProxyConfig.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), + any(StubTypes.class), + anyString(), + any(StubHttpLifecycle.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); } @Test @@ -126,11 +162,20 @@ public void verifyBehaviourWhenAjaxSubmittedToFetchStubbedRequestContent() throw when(mockHttpServletRequest.getRequestURI()).thenReturn(requestURI); when(mockStubRepository.matchStubByIndex(anyInt())).thenReturn(STUB_HTTP_LIFECYCLE_OPTIONAL); - spyAjaxResourceContentHandler.handle(requestURI, mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); - - verify(spyAjaxResourceContentHandler).throwErrorOnNonExistentResourceIndex(any(HttpServletResponse.class), stubIndexCaptor.capture()); - verify(spyAjaxResourceContentHandler).renderAjaxResponseContent(any(HttpServletResponse.class), stubTypeCaptor.capture(), fieldCaptor.capture(), any(StubHttpLifecycle.class)); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); + spyAjaxResourceContentHandler.handle( + requestURI, mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); + + verify(spyAjaxResourceContentHandler) + .throwErrorOnNonExistentResourceIndex(any(HttpServletResponse.class), stubIndexCaptor.capture()); + verify(spyAjaxResourceContentHandler) + .renderAjaxResponseContent( + any(HttpServletResponse.class), + stubTypeCaptor.capture(), + fieldCaptor.capture(), + any(StubHttpLifecycle.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); assertThat(stubIndexCaptor.getValue()).isEqualTo(5); assertThat(stubTypeCaptor.getValue()).isEqualTo(StubTypes.REQUEST); @@ -145,11 +190,20 @@ public void verifyBehaviourWhenAjaxSubmittedToFetchStubbedResponseContent() thro when(mockHttpServletRequest.getRequestURI()).thenReturn(requestURI); when(mockStubRepository.matchStubByIndex(anyInt())).thenReturn(STUB_HTTP_LIFECYCLE_OPTIONAL); - spyAjaxResourceContentHandler.handle(requestURI, mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); - - verify(spyAjaxResourceContentHandler).throwErrorOnNonExistentResourceIndex(any(HttpServletResponse.class), stubIndexCaptor.capture()); - verify(spyAjaxResourceContentHandler).renderAjaxResponseContent(any(HttpServletResponse.class), stubTypeCaptor.capture(), fieldCaptor.capture(), any(StubHttpLifecycle.class)); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); + spyAjaxResourceContentHandler.handle( + requestURI, mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); + + verify(spyAjaxResourceContentHandler) + .throwErrorOnNonExistentResourceIndex(any(HttpServletResponse.class), stubIndexCaptor.capture()); + verify(spyAjaxResourceContentHandler) + .renderAjaxResponseContent( + any(HttpServletResponse.class), + stubTypeCaptor.capture(), + fieldCaptor.capture(), + any(StubHttpLifecycle.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); assertThat(stubIndexCaptor.getValue()).isEqualTo(15); assertThat(stubTypeCaptor.getValue()).isEqualTo(StubTypes.RESPONSE); @@ -164,11 +218,23 @@ public void verifyBehaviourWhenAjaxSubmittedToFetchStubbedSequencedResponseConte when(mockHttpServletRequest.getRequestURI()).thenReturn(requestURI); when(mockStubRepository.matchStubByIndex(anyInt())).thenReturn(STUB_HTTP_LIFECYCLE_OPTIONAL); - spyAjaxResourceContentHandler.handle(requestURI, mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); - - verify(spyAjaxResourceContentHandler).throwErrorOnNonExistentResourceIndex(any(HttpServletResponse.class), stubIndexCaptor.capture()); - verify(spyAjaxResourceContentHandler).renderAjaxResponseContent(any(HttpServletResponse.class), responseSequenceCaptor.capture(), fieldCaptor.capture(), any(StubHttpLifecycle.class)); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), any(StubTypes.class), anyString(), any(StubHttpLifecycle.class)); + spyAjaxResourceContentHandler.handle( + requestURI, mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); + + verify(spyAjaxResourceContentHandler) + .throwErrorOnNonExistentResourceIndex(any(HttpServletResponse.class), stubIndexCaptor.capture()); + verify(spyAjaxResourceContentHandler) + .renderAjaxResponseContent( + any(HttpServletResponse.class), + responseSequenceCaptor.capture(), + fieldCaptor.capture(), + any(StubHttpLifecycle.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), + any(StubTypes.class), + anyString(), + any(StubHttpLifecycle.class)); assertThat(stubIndexCaptor.getValue()).isEqualTo(15); assertThat(responseSequenceCaptor.getValue()).isEqualTo(8); @@ -185,11 +251,20 @@ public void verifyBehaviourWhenAjaxSubmittedToFetchNonExistentStubbedSequencedRe when(mockHttpServletRequest.getRequestURI()).thenReturn(requestURI); when(mockStubRepository.matchStubByIndex(999)).thenReturn(Optional.empty()); - spyAjaxResourceContentHandler.handle(requestURI, mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); - - verify(spyAjaxResourceContentHandler).throwErrorOnNonExistentResourceIndex(any(HttpServletResponse.class), stubIndexCaptor.capture()); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), any(StubTypes.class), anyString(), any(StubHttpLifecycle.class)); + spyAjaxResourceContentHandler.handle( + requestURI, mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); + + verify(spyAjaxResourceContentHandler) + .throwErrorOnNonExistentResourceIndex(any(HttpServletResponse.class), stubIndexCaptor.capture()); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), + any(StubTypes.class), + anyString(), + any(StubHttpLifecycle.class)); } @Test @@ -199,13 +274,22 @@ public void verifyBehaviourWhenAjaxSubmittedToFetchContentForWrongStubType() thr when(mockHttpServletRequest.getRequestURI()).thenReturn(requestURI); when(mockStubRepository.matchStubByIndex(anyInt())).thenReturn(STUB_HTTP_LIFECYCLE_OPTIONAL); - spyAjaxResourceContentHandler.handle(requestURI, mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); + spyAjaxResourceContentHandler.handle( + requestURI, mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); - verify(spyAjaxResourceContentHandler).throwErrorOnNonExistentResourceIndex(any(HttpServletResponse.class), anyInt()); + verify(spyAjaxResourceContentHandler) + .throwErrorOnNonExistentResourceIndex(any(HttpServletResponse.class), anyInt()); verify(mockPrintWriter).println("Could not fetch the content for stub type: WRONG-STUB-TYPE"); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), any(StubTypes.class), anyString(), any(StubHttpLifecycle.class)); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), + any(StubTypes.class), + anyString(), + any(StubHttpLifecycle.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); } @Test @@ -216,13 +300,23 @@ public void verifyBehaviourWhenAjaxSubmittedToFetchStubbedProxyConfigContent() t when(mockHttpServletRequest.getRequestURI()).thenReturn(requestURI); when(mockStubRepository.matchProxyConfigByName(anyString())).thenReturn(STUB_PROXY_CONFIG); - spyAjaxResourceContentHandler.handle(requestURI, mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); + spyAjaxResourceContentHandler.handle( + requestURI, mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); - verify(spyAjaxResourceContentHandler).renderProxyConfigAjaxResponse(any(HttpServletResponse.class), fieldCaptor.capture(), any(StubProxyConfig.class)); + verify(spyAjaxResourceContentHandler) + .renderProxyConfigAjaxResponse( + any(HttpServletResponse.class), fieldCaptor.capture(), any(StubProxyConfig.class)); verify(mockStubRepository).matchProxyConfigByName(stringCaptor.capture()); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), any(StubTypes.class), anyString(), any(StubHttpLifecycle.class)); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), + any(StubTypes.class), + anyString(), + any(StubHttpLifecycle.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); assertThat(fieldCaptor.getValue()).isEqualTo("proxyConfigAsYAML"); assertThat(stringCaptor.getValue()).isEqualTo("some-unique-name"); @@ -237,13 +331,22 @@ public void verifyBehaviourWhenAjaxSubmittedToFetchNonExistentProxyConfigContent // No proxy config in repository for a given name when(mockStubRepository.matchProxyConfigByName(anyString())).thenReturn(null); - spyAjaxResourceContentHandler.handle(requestURI, mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); + spyAjaxResourceContentHandler.handle( + requestURI, mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); verify(mockStubRepository).matchProxyConfigByName(stringCaptor.capture()); - verify(spyAjaxResourceContentHandler, never()).renderProxyConfigAjaxResponse(any(HttpServletResponse.class), anyString(), any(StubProxyConfig.class)); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), any(StubTypes.class), anyString(), any(StubHttpLifecycle.class)); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderProxyConfigAjaxResponse(any(HttpServletResponse.class), anyString(), any(StubProxyConfig.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), + any(StubTypes.class), + anyString(), + any(StubHttpLifecycle.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); assertThat(stringCaptor.getValue()).isEqualTo("some-unique-name"); } @@ -255,12 +358,21 @@ public void verifyBehaviourWhenAjaxSubmittedToFetchWrongProxyConfigContent() thr when(mockHttpServletRequest.getRequestURI()).thenReturn(requestURI); - spyAjaxResourceContentHandler.handle(requestURI, mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); + spyAjaxResourceContentHandler.handle( + requestURI, mockBaseRequest, mockHttpServletRequest, mockHttpServletResponse); verify(mockStubRepository, never()).matchProxyConfigByName(anyString()); - verify(spyAjaxResourceContentHandler, never()).renderProxyConfigAjaxResponse(any(HttpServletResponse.class), anyString(), any(StubProxyConfig.class)); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), any(StubTypes.class), anyString(), any(StubHttpLifecycle.class)); - verify(spyAjaxResourceContentHandler, never()).renderAjaxResponseContent(any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderProxyConfigAjaxResponse(any(HttpServletResponse.class), anyString(), any(StubProxyConfig.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), + any(StubTypes.class), + anyString(), + any(StubHttpLifecycle.class)); + verify(spyAjaxResourceContentHandler, never()) + .renderAjaxResponseContent( + any(HttpServletResponse.class), anyInt(), anyString(), any(StubHttpLifecycle.class)); verify(mockPrintWriter).println("Could not fetch the content for proxy config: WRONG-proxy-config"); } diff --git a/src/test/java/io/github/azagniotov/stubby4j/handlers/StubsPortalHandlerTest.java b/src/test/java/io/github/azagniotov/stubby4j/handlers/StubsPortalHandlerTest.java index 1aa7bec35..a6f585cda 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/handlers/StubsPortalHandlerTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/handlers/StubsPortalHandlerTest.java @@ -1,10 +1,42 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.stubs.StubRequest; import io.github.azagniotov.stubby4j.stubs.StubResponse; import io.github.azagniotov.stubby4j.stubs.StubSearchResult; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.WriteListener; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http.HttpStatus.Code; @@ -15,24 +47,6 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import javax.servlet.ReadListener; -import javax.servlet.ServletInputStream; -import javax.servlet.ServletOutputStream; -import javax.servlet.WriteListener; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintWriter; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - - @SuppressWarnings("serial") @RunWith(MockitoJUnitRunner.class) public class StubsPortalHandlerTest { @@ -41,9 +55,7 @@ public class StubsPortalHandlerTest { private static final ServletOutputStream SERVLET_OUTPUT_STREAM = new ServletOutputStream() { @Override - public void write(final int i) throws IOException { - - } + public void write(final int i) throws IOException {} @Override public boolean isReady() { @@ -51,9 +63,7 @@ public boolean isReady() { } @Override - public void setWriteListener(final WriteListener writeListener) { - - } + public void setWriteListener(final WriteListener writeListener) {} }; @Mock @@ -113,7 +123,7 @@ public void verifyBehaviourDuringHandleGetRequestWithNoResults() throws Exceptio when(mockHttpServletRequest.getMethod()).thenReturn(HttpMethod.GET.asString()); when(mockHttpServletRequest.getPathInfo()).thenReturn(requestPathInfo); when(mockStubResponse.getHttpStatusCode()).thenReturn(Code.NOT_FOUND); - when(mockStubResponse.getResponseBodyAsBytes()).thenReturn(new byte[]{}); + when(mockStubResponse.getResponseBodyAsBytes()).thenReturn(new byte[] {}); setUpStubSearchMockExpectations(requestPathInfo); @@ -130,7 +140,7 @@ public void verifyBehaviourDuringHandlePostRequestWithNoResults() throws Excepti when(mockHttpServletRequest.getMethod()).thenReturn(HttpMethod.POST.asString()); when(mockHttpServletRequest.getPathInfo()).thenReturn(requestPathInfo); when(mockStubResponse.getHttpStatusCode()).thenReturn(Code.NOT_FOUND); - when(mockStubResponse.getResponseBodyAsBytes()).thenReturn(new byte[]{}); + when(mockStubResponse.getResponseBodyAsBytes()).thenReturn(new byte[] {}); final InputStream inputStream = new ByteArrayInputStream(postData.getBytes()); when(mockHttpServletRequest.getInputStream()).thenReturn(getServletInputStream(inputStream)); @@ -263,7 +273,7 @@ public void verifyBehaviourDuringHandleGetRequestWithLatency() throws Exception when(mockHttpServletRequest.getPathInfo()).thenReturn(requestPathInfo); when(mockStubResponse.getLatency()).thenReturn("50"); when(mockStubResponse.getHttpStatusCode()).thenReturn(Code.OK); - when(mockStubResponse.getResponseBodyAsBytes()).thenReturn(new byte[]{}); + when(mockStubResponse.getResponseBodyAsBytes()).thenReturn(new byte[] {}); when(mockHttpServletResponse.getOutputStream()).thenReturn(SERVLET_OUTPUT_STREAM); setUpStubSearchMockExpectations(requestPathInfo); @@ -318,9 +328,7 @@ public boolean isReady() { } @Override - public void setReadListener(final ReadListener readListener) { - - } + public void setReadListener(final ReadListener readListener) {} }; } } diff --git a/src/test/java/io/github/azagniotov/stubby4j/handlers/strategy/DefaultResponseHandlingStrategyTest.java b/src/test/java/io/github/azagniotov/stubby4j/handlers/strategy/DefaultResponseHandlingStrategyTest.java index feab07651..ee83b7779 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/handlers/strategy/DefaultResponseHandlingStrategyTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/handlers/strategy/DefaultResponseHandlingStrategyTest.java @@ -1,9 +1,37 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.utils.StringUtils.getBytesUtf8; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import io.github.azagniotov.stubby4j.handlers.strategy.stubs.DefaultResponseHandlingStrategy; import io.github.azagniotov.stubby4j.stubs.StubRequest; import io.github.azagniotov.stubby4j.stubs.StubResponse; import io.github.azagniotov.stubby4j.utils.HandlerUtils; +import java.io.IOException; +import java.util.HashMap; +import java.util.TreeMap; +import java.util.UUID; +import javax.servlet.ServletOutputStream; +import javax.servlet.WriteListener; +import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http.HttpStatus.Code; @@ -14,20 +42,6 @@ import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import javax.servlet.ServletOutputStream; -import javax.servlet.WriteListener; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.HashMap; -import java.util.TreeMap; -import java.util.UUID; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.utils.StringUtils.getBytesUtf8; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - - @RunWith(MockitoJUnitRunner.class) public class DefaultResponseHandlingStrategyTest { @@ -35,9 +49,7 @@ public class DefaultResponseHandlingStrategyTest { private static final ServletOutputStream SERVLET_OUTPUT_STREAM = new ServletOutputStream() { @Override - public void write(final int i) throws IOException { - - } + public void write(final int i) throws IOException {} @Override public boolean isReady() { @@ -45,9 +57,7 @@ public boolean isReady() { } @Override - public void setWriteListener(final WriteListener writeListener) { - - } + public void setWriteListener(final WriteListener writeListener) {} }; private static final byte[] EMPTY_BYTES = {}; @@ -113,14 +123,18 @@ public void shouldReturnReplacedValueInResponseHeaderWhenRequestBodyHasDynamicTo final String headerValuePrefix = "redirect-uri=https://google.com&nonce="; when(mockHttpServletResponse.getOutputStream()).thenReturn(SERVLET_OUTPUT_STREAM); - when(mockAssertionRequest.getRegexGroups()).thenReturn(new TreeMap() {{ - put("post.1", nonce); - }}); + when(mockAssertionRequest.getRegexGroups()).thenReturn(new TreeMap() { + { + put("post.1", nonce); + } + }); when(mockStubResponse.getHttpStatusCode()).thenReturn(Code.MOVED_TEMPORARILY); - when(mockStubResponse.getHeaders()).thenReturn(new HashMap() {{ - put("Location", headerValuePrefix + "<%post.1%>"); - }}); + when(mockStubResponse.getHeaders()).thenReturn(new HashMap() { + { + put("Location", headerValuePrefix + "<%post.1%>"); + } + }); when(mockStubResponse.getResponseBodyAsBytes()).thenReturn(getBytesUtf8(SOME_RESULTS_MESSAGE)); defaultResponseHandlingStrategy.handle(mockHttpServletResponse, mockAssertionRequest); @@ -130,10 +144,12 @@ public void shouldReturnReplacedValueInResponseHeaderWhenRequestBodyHasDynamicTo } private void verifyMainHeaders(final HttpServletResponse mockHttpServletResponse) throws Exception { - verify(mockHttpServletResponse).setHeader(HttpHeader.SERVER.asString(), HandlerUtils.constructHeaderServerName()); + verify(mockHttpServletResponse) + .setHeader(HttpHeader.SERVER.asString(), HandlerUtils.constructHeaderServerName()); verify(mockHttpServletResponse).setHeader(HttpHeader.CONTENT_TYPE.asString(), "text/html;charset=UTF-8"); - verify(mockHttpServletResponse).setHeader(HttpHeader.CACHE_CONTROL.asString(), "no-cache, no-stage, must-revalidate"); + verify(mockHttpServletResponse) + .setHeader(HttpHeader.CACHE_CONTROL.asString(), "no-cache, no-stage, must-revalidate"); verify(mockHttpServletResponse).setHeader(HttpHeader.PRAGMA.asString(), "no-cache"); verify(mockHttpServletResponse).setDateHeader(HttpHeader.EXPIRES.asString(), 0); } -} \ No newline at end of file +} diff --git a/src/test/java/io/github/azagniotov/stubby4j/handlers/strategy/HandlingStrategyFactoryTest.java b/src/test/java/io/github/azagniotov/stubby4j/handlers/strategy/HandlingStrategyFactoryTest.java index 060b3ac88..3e8ae1065 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/handlers/strategy/HandlingStrategyFactoryTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/handlers/strategy/HandlingStrategyFactoryTest.java @@ -1,5 +1,23 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy; +import static com.google.common.truth.Truth.assertThat; + import io.github.azagniotov.stubby4j.handlers.strategy.stubs.DefaultResponseHandlingStrategy; import io.github.azagniotov.stubby4j.handlers.strategy.stubs.NotFoundResponseHandlingStrategy; import io.github.azagniotov.stubby4j.handlers.strategy.stubs.RedirectResponseHandlingStrategy; @@ -10,16 +28,14 @@ import org.eclipse.jetty.http.HttpStatus.Code; import org.junit.Test; -import static com.google.common.truth.Truth.assertThat; - - public class HandlingStrategyFactoryTest { @Test public void shouldIdentifyResponseStrategyForDefaultResponse() throws Exception { final StubResponse stubResponse = StubResponse.okResponse(); - final StubResponseHandlingStrategy stubResponseHandlingStrategy = StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); + final StubResponseHandlingStrategy stubResponseHandlingStrategy = + StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); assertThat(stubResponseHandlingStrategy).isInstanceOf(DefaultResponseHandlingStrategy.class); } @@ -27,7 +43,8 @@ public void shouldIdentifyResponseStrategyForDefaultResponse() throws Exception public void shouldIdentifyResponseStrategyForNotFoundResponse() throws Exception { final StubResponse stubResponse = StubResponse.notFoundResponse(); - final StubResponseHandlingStrategy stubResponseHandlingStrategy = StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); + final StubResponseHandlingStrategy stubResponseHandlingStrategy = + StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); assertThat(stubResponseHandlingStrategy).isInstanceOf(NotFoundResponseHandlingStrategy.class); } @@ -35,7 +52,8 @@ public void shouldIdentifyResponseStrategyForNotFoundResponse() throws Exception public void shouldIdentifyResponseStrategyForUnauthorizedResponse() throws Exception { final StubResponse stubResponse = StubResponse.unauthorizedResponse(); - final StubResponseHandlingStrategy stubResponseHandlingStrategy = StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); + final StubResponseHandlingStrategy stubResponseHandlingStrategy = + StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); assertThat(stubResponseHandlingStrategy).isInstanceOf(UnauthorizedResponseHandlingStrategy.class); } @@ -45,7 +63,8 @@ public void shouldIdentifyResponseStrategyForRedirectResponseWithStubResponseCod .withHttpStatusCode(Code.MOVED_PERMANENTLY) .build(); - final StubResponseHandlingStrategy stubResponseHandlingStrategy = StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); + final StubResponseHandlingStrategy stubResponseHandlingStrategy = + StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); assertThat(stubResponseHandlingStrategy).isInstanceOf(RedirectResponseHandlingStrategy.class); } @@ -55,27 +74,28 @@ public void shouldIdentifyResponseStrategyForRedirectResponseWithStubResponseCod .withHttpStatusCode(Code.MOVED_TEMPORARILY) .build(); - final StubResponseHandlingStrategy stubResponseHandlingStrategy = StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); + final StubResponseHandlingStrategy stubResponseHandlingStrategy = + StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); assertThat(stubResponseHandlingStrategy).isInstanceOf(RedirectResponseHandlingStrategy.class); } @Test public void shouldIdentifyResponseStrategyForRedirectResponseWithStubResponseCode302_Found() throws Exception { - final StubResponse stubResponse = new StubResponse.Builder() - .withHttpStatusCode(Code.FOUND) - .build(); + final StubResponse stubResponse = + new StubResponse.Builder().withHttpStatusCode(Code.FOUND).build(); - final StubResponseHandlingStrategy stubResponseHandlingStrategy = StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); + final StubResponseHandlingStrategy stubResponseHandlingStrategy = + StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); assertThat(stubResponseHandlingStrategy).isInstanceOf(RedirectResponseHandlingStrategy.class); } @Test public void shouldIdentifyResponseStrategyForRedirectResponseWithStubResponseCode303() throws Exception { - final StubResponse stubResponse = new StubResponse.Builder() - .withHttpStatusCode(Code.SEE_OTHER) - .build(); + final StubResponse stubResponse = + new StubResponse.Builder().withHttpStatusCode(Code.SEE_OTHER).build(); - final StubResponseHandlingStrategy stubResponseHandlingStrategy = StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); + final StubResponseHandlingStrategy stubResponseHandlingStrategy = + StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); assertThat(stubResponseHandlingStrategy).isInstanceOf(RedirectResponseHandlingStrategy.class); } @@ -85,7 +105,8 @@ public void shouldIdentifyResponseStrategyForRedirectResponseWithStubResponseCod .withHttpStatusCode(Code.TEMPORARY_REDIRECT) .build(); - final StubResponseHandlingStrategy stubResponseHandlingStrategy = StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); + final StubResponseHandlingStrategy stubResponseHandlingStrategy = + StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); assertThat(stubResponseHandlingStrategy).isInstanceOf(RedirectResponseHandlingStrategy.class); } @@ -95,7 +116,8 @@ public void shouldIdentifyResponseStrategyForRedirectResponseWithStubResponseCod .withHttpStatusCode(Code.PERMANENT_REDIRECT) .build(); - final StubResponseHandlingStrategy stubResponseHandlingStrategy = StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); + final StubResponseHandlingStrategy stubResponseHandlingStrategy = + StubsResponseHandlingStrategyFactory.getStrategy(stubResponse); assertThat(stubResponseHandlingStrategy).isInstanceOf(RedirectResponseHandlingStrategy.class); } } diff --git a/src/test/java/io/github/azagniotov/stubby4j/handlers/strategy/RedirectResponseHandlingStrategyTest.java b/src/test/java/io/github/azagniotov/stubby4j/handlers/strategy/RedirectResponseHandlingStrategyTest.java index 994c5914d..feb0c897b 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/handlers/strategy/RedirectResponseHandlingStrategyTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/handlers/strategy/RedirectResponseHandlingStrategyTest.java @@ -1,9 +1,32 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import io.github.azagniotov.stubby4j.handlers.strategy.stubs.RedirectResponseHandlingStrategy; import io.github.azagniotov.stubby4j.stubs.StubRequest; import io.github.azagniotov.stubby4j.stubs.StubResponse; import io.github.azagniotov.stubby4j.utils.HandlerUtils; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.TreeMap; +import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http.HttpStatus.Code; @@ -14,15 +37,6 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import javax.servlet.http.HttpServletResponse; -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.TreeMap; - -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - - @RunWith(MockitoJUnitRunner.class) public class RedirectResponseHandlingStrategyTest { @@ -43,9 +57,11 @@ public class RedirectResponseHandlingStrategyTest { @Before public void setUp() { - when(mockStubResponse.getHeaders()).thenReturn(new HashMap() {{ - put("location", "http://location.com"); - }}); + when(mockStubResponse.getHeaders()).thenReturn(new HashMap() { + { + put("location", "http://location.com"); + } + }); } @Test @@ -55,7 +71,10 @@ public void shouldVerifyBehaviourWhenHandlingTemporaryRedirectResponseWithoutLat redirectResponseHandlingStrategy.handle(mockHttpServletResponse, mockAssertionRequest); verify(mockHttpServletResponse).setStatus(HttpStatus.MOVED_TEMPORARILY_302); - verify(mockHttpServletResponse).setHeader(HttpHeader.LOCATION.asString(), mockStubResponse.getHeaders().get("location")); + verify(mockHttpServletResponse) + .setHeader( + HttpHeader.LOCATION.asString(), + mockStubResponse.getHeaders().get("location")); verify(mockHttpServletResponse).setHeader(HttpHeader.CONNECTION.asString(), "close"); verifyMainHeaders(mockHttpServletResponse); } @@ -67,7 +86,10 @@ public void shouldVerifyBehaviourWhenHandlingPermanentRedirectResponseWithoutLat redirectResponseHandlingStrategy.handle(mockHttpServletResponse, mockAssertionRequest); verify(mockHttpServletResponse).setStatus(HttpStatus.MOVED_PERMANENTLY_301); - verify(mockHttpServletResponse).setHeader(HttpHeader.LOCATION.asString(), mockStubResponse.getHeaders().get("location")); + verify(mockHttpServletResponse) + .setHeader( + HttpHeader.LOCATION.asString(), + mockStubResponse.getHeaders().get("location")); verify(mockHttpServletResponse).setHeader(HttpHeader.CONNECTION.asString(), "close"); verifyMainHeaders(mockHttpServletResponse); } @@ -80,7 +102,10 @@ public void shouldVerifyBehaviourWhenHandlingRedirectResponseWithLatency() throw redirectResponseHandlingStrategy.handle(mockHttpServletResponse, mockAssertionRequest); verify(mockHttpServletResponse).setStatus(HttpStatus.MOVED_PERMANENTLY_301); - verify(mockHttpServletResponse).setHeader(HttpHeader.LOCATION.asString(), mockStubResponse.getHeaders().get("location")); + verify(mockHttpServletResponse) + .setHeader( + HttpHeader.LOCATION.asString(), + mockStubResponse.getHeaders().get("location")); verify(mockHttpServletResponse).setHeader(HttpHeader.CONNECTION.asString(), "close"); verifyMainHeaders(mockHttpServletResponse); } @@ -90,13 +115,17 @@ public void shouldReturnReplacedValueInLocationHeaderWhenQueryParamHasDynamicTok String redirectUrlDomain = "test.com"; String tokenizedLocationHeaderValue = "https://<% query.redirect_uri.1 %>/auth"; - when(mockAssertionRequest.getRegexGroups()).thenReturn(new TreeMap() {{ - put("query.redirect_uri.1", redirectUrlDomain); - }}); + when(mockAssertionRequest.getRegexGroups()).thenReturn(new TreeMap() { + { + put("query.redirect_uri.1", redirectUrlDomain); + } + }); when(mockStubResponse.getHttpStatusCode()).thenReturn(Code.MOVED_TEMPORARILY); - when(mockStubResponse.getHeaders()).thenReturn(new HashMap() {{ - put("location", tokenizedLocationHeaderValue); - }}); + when(mockStubResponse.getHeaders()).thenReturn(new HashMap() { + { + put("location", tokenizedLocationHeaderValue); + } + }); redirectResponseHandlingStrategy.handle(mockHttpServletResponse, mockAssertionRequest); @@ -104,13 +133,14 @@ public void shouldReturnReplacedValueInLocationHeaderWhenQueryParamHasDynamicTok verify(mockHttpServletResponse).setHeader(HttpHeader.LOCATION.asString(), "https://test.com/auth"); verify(mockHttpServletResponse).setHeader(HttpHeader.CONNECTION.asString(), "close"); verifyMainHeaders(mockHttpServletResponse); - } private void verifyMainHeaders(final HttpServletResponse mockHttpServletResponse) throws Exception { - verify(mockHttpServletResponse).setHeader(HttpHeader.SERVER.asString(), HandlerUtils.constructHeaderServerName()); + verify(mockHttpServletResponse) + .setHeader(HttpHeader.SERVER.asString(), HandlerUtils.constructHeaderServerName()); verify(mockHttpServletResponse).setHeader(HttpHeader.CONTENT_TYPE.asString(), "text/html;charset=UTF-8"); - verify(mockHttpServletResponse).setHeader(HttpHeader.CACHE_CONTROL.asString(), "no-cache, no-stage, must-revalidate"); + verify(mockHttpServletResponse) + .setHeader(HttpHeader.CACHE_CONTROL.asString(), "no-cache, no-stage, must-revalidate"); verify(mockHttpServletResponse).setHeader(HttpHeader.PRAGMA.asString(), "no-cache"); verify(mockHttpServletResponse).setDateHeader(HttpHeader.EXPIRES.asString(), 0); } diff --git a/src/test/java/io/github/azagniotov/stubby4j/handlers/strategy/StubsResponseHandlingStrategyFactoryTest.java b/src/test/java/io/github/azagniotov/stubby4j/handlers/strategy/StubsResponseHandlingStrategyFactoryTest.java index 2b213783e..6f6e981b9 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/handlers/strategy/StubsResponseHandlingStrategyFactoryTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/handlers/strategy/StubsResponseHandlingStrategyFactoryTest.java @@ -1,5 +1,24 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.handlers.strategy; +import static com.google.common.truth.Truth.assertThat; +import static org.mockito.Mockito.when; + import io.github.azagniotov.stubby4j.handlers.strategy.stubs.DefaultResponseHandlingStrategy; import io.github.azagniotov.stubby4j.handlers.strategy.stubs.NotFoundResponseHandlingStrategy; import io.github.azagniotov.stubby4j.handlers.strategy.stubs.StubResponseHandlingStrategy; @@ -11,9 +30,6 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import static com.google.common.truth.Truth.assertThat; -import static org.mockito.Mockito.when; - @RunWith(MockitoJUnitRunner.class) public class StubsResponseHandlingStrategyFactoryTest { @@ -27,7 +43,8 @@ public void shouldReturnNotFoundResponseHandlingStrategyWhen404ResponseHasNoBody when(mockStubResponse.getHttpStatusCode()).thenReturn(HttpStatus.Code.NOT_FOUND); when(mockStubResponse.getResponseBodyAsBytes()).thenReturn(EMPTY_BYTES); - StubResponseHandlingStrategy handlingStrategy = StubsResponseHandlingStrategyFactory.getStrategy(mockStubResponse); + StubResponseHandlingStrategy handlingStrategy = + StubsResponseHandlingStrategyFactory.getStrategy(mockStubResponse); assertThat(handlingStrategy).isInstanceOf(NotFoundResponseHandlingStrategy.class); } @@ -37,7 +54,8 @@ public void shouldReturnDefaultResponseHandlingStrategyWhen404ResponseHasNoBody( when(mockStubResponse.getHttpStatusCode()).thenReturn(HttpStatus.Code.NOT_FOUND); when(mockStubResponse.getResponseBodyAsBytes()).thenReturn("something".getBytes()); - StubResponseHandlingStrategy handlingStrategy = StubsResponseHandlingStrategyFactory.getStrategy(mockStubResponse); + StubResponseHandlingStrategy handlingStrategy = + StubsResponseHandlingStrategyFactory.getStrategy(mockStubResponse); assertThat(handlingStrategy).isInstanceOf(DefaultResponseHandlingStrategy.class); } diff --git a/src/test/java/io/github/azagniotov/stubby4j/server/ssl/LanIPv4ValidatorTest.java b/src/test/java/io/github/azagniotov/stubby4j/server/ssl/LanIPv4ValidatorTest.java index fca19810d..46a32fc53 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/server/ssl/LanIPv4ValidatorTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/server/ssl/LanIPv4ValidatorTest.java @@ -1,9 +1,25 @@ -package io.github.azagniotov.stubby4j.server.ssl; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import org.junit.Test; +package io.github.azagniotov.stubby4j.server.ssl; import static com.google.common.truth.Truth.assertThat; +import org.junit.Test; + public class LanIPv4ValidatorTest { @Test @@ -27,4 +43,4 @@ public void isNotPrivateIp() throws Exception { assertThat(LanIPv4Validator.isPrivateIp("172.15.0.1")).isFalse(); assertThat(LanIPv4Validator.isPrivateIp("172.32.255.255")).isFalse(); } -} \ No newline at end of file +} diff --git a/src/test/java/io/github/azagniotov/stubby4j/server/websocket/StubsServerWebSocketTest.java b/src/test/java/io/github/azagniotov/stubby4j/server/websocket/StubsServerWebSocketTest.java index 9138fc904..e4c855bf0 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/server/websocket/StubsServerWebSocketTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/server/websocket/StubsServerWebSocketTest.java @@ -1,5 +1,30 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.server.websocket; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.server.websocket.StubsServerWebSocket.EMPTY_BYTE_BUFFER; +import static io.github.azagniotov.stubby4j.utils.FileUtils.tempFileFromString; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketClientRequest; import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketConfig; import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketMessageType; @@ -7,6 +32,13 @@ import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponse; import io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketServerResponsePolicy; import io.github.azagniotov.stubby4j.utils.StringUtils; +import java.net.URI; +import java.nio.ByteBuffer; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import org.eclipse.jetty.websocket.api.RemoteEndpoint; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.StatusCode; @@ -21,30 +53,13 @@ import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import java.net.URI; -import java.nio.ByteBuffer; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.server.websocket.StubsServerWebSocket.EMPTY_BYTE_BUFFER; -import static io.github.azagniotov.stubby4j.utils.FileUtils.tempFileFromString; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - - @RunWith(MockitoJUnitRunner.class) public class StubsServerWebSocketTest { private static final String HELLO_FROM_CLIENT = "hello-from-client"; private static final String HELLO_FROM_SERVER = "hello-from-server"; - private static final ByteBuffer BYTE_BUFFER_HELLO_FROM_SERVER = ByteBuffer.wrap(StringUtils.getBytesUtf8(HELLO_FROM_SERVER)); + private static final ByteBuffer BYTE_BUFFER_HELLO_FROM_SERVER = + ByteBuffer.wrap(StringUtils.getBytesUtf8(HELLO_FROM_SERVER)); @Mock private Session mockSession; @@ -98,10 +113,8 @@ public void onWebSocketConnect_DispatchesExpectedServerTextResponseWhenPolicyOnc serverWebSocket.onWebSocketConnect(mockSession); - verify(spyScheduledExecutorService, times(1)).schedule( - runnableCaptor.capture(), - eq(250L), - eq(TimeUnit.MILLISECONDS)); + verify(spyScheduledExecutorService, times(1)) + .schedule(runnableCaptor.capture(), eq(250L), eq(TimeUnit.MILLISECONDS)); // Execute the captured future which was passed in to the // ScheduledExecutorService, in order to trigger the behavior @@ -126,10 +139,8 @@ public void onWebSocketConnect_DispatchesExpectedServerTextResponseWhenPolicyDis // 1. 1st future is scheduled when sending configured text response // 2. 2nd future is scheduled when session disconnects - verify(spyScheduledExecutorService, times(2)).schedule( - runnableCaptor.capture(), - eq(250L), - eq(TimeUnit.MILLISECONDS)); + verify(spyScheduledExecutorService, times(2)) + .schedule(runnableCaptor.capture(), eq(250L), eq(TimeUnit.MILLISECONDS)); // Execute the captured futures which were passed in to the // ScheduledExecutorService, in order to trigger the behavior @@ -158,10 +169,8 @@ public void onWebSocketConnect_DispatchesExpectedServerBinaryResponseWhenPolicyD // 1. 1st future is scheduled when sending configured text response // 2. 2nd future is scheduled when session disconnects - verify(spyScheduledExecutorService, times(2)).schedule( - runnableCaptor.capture(), - eq(250L), - eq(TimeUnit.MILLISECONDS)); + verify(spyScheduledExecutorService, times(2)) + .schedule(runnableCaptor.capture(), eq(250L), eq(TimeUnit.MILLISECONDS)); // Execute the captured futures which were passed in to the // ScheduledExecutorService, in order to trigger the behavior @@ -189,11 +198,8 @@ public void onWebSocketConnect_DispatchesExpectedServerPeriodicPingResponseWhenP serverWebSocket.onWebSocketConnect(mockSession); - verify(spyScheduledExecutorService, times(1)).scheduleAtFixedRate( - runnableCaptor.capture(), - eq(1337L), - eq(1337L), - eq(TimeUnit.MILLISECONDS)); + verify(spyScheduledExecutorService, times(1)) + .scheduleAtFixedRate(runnableCaptor.capture(), eq(1337L), eq(1337L), eq(TimeUnit.MILLISECONDS)); // Execute the captured future which was passed in to the // ScheduledExecutorService, in order to trigger the behavior @@ -216,11 +222,8 @@ public void onWebSocketConnect_DispatchesExpectedServerPeriodicTextResponseWhenP serverWebSocket.onWebSocketConnect(mockSession); - verify(spyScheduledExecutorService, times(1)).scheduleAtFixedRate( - runnableCaptor.capture(), - eq(5000L), - eq(5000L), - eq(TimeUnit.MILLISECONDS)); + verify(spyScheduledExecutorService, times(1)) + .scheduleAtFixedRate(runnableCaptor.capture(), eq(5000L), eq(5000L), eq(TimeUnit.MILLISECONDS)); // Execute the captured future which was passed in to the // ScheduledExecutorService, in order to trigger the behavior @@ -243,11 +246,8 @@ public void onWebSocketConnect_DispatchesExpectedServerPeriodicBinaryResponseWhe serverWebSocket.onWebSocketConnect(mockSession); - verify(spyScheduledExecutorService, times(1)).scheduleAtFixedRate( - runnableCaptor.capture(), - eq(3500L), - eq(3500L), - eq(TimeUnit.MILLISECONDS)); + verify(spyScheduledExecutorService, times(1)) + .scheduleAtFixedRate(runnableCaptor.capture(), eq(3500L), eq(3500L), eq(TimeUnit.MILLISECONDS)); // Execute the captured future which was passed in to the // ScheduledExecutorService, in order to trigger the behavior @@ -272,10 +272,8 @@ public void onWebSocketConnect_DispatchesExpectedServerBinaryResponseWhenPolicyF serverWebSocket.onWebSocketConnect(mockSession); - verify(spyScheduledExecutorService, times(1)).schedule( - runnableCaptor.capture(), - eq(5L), - eq(TimeUnit.MILLISECONDS)); + verify(spyScheduledExecutorService, times(1)) + .schedule(runnableCaptor.capture(), eq(5L), eq(TimeUnit.MILLISECONDS)); // Execute the captured future which was passed in to the // ScheduledExecutorService, in order to trigger the behavior @@ -289,13 +287,13 @@ public void onWebSocketConnect_DispatchesExpectedServerBinaryResponseWhenPolicyF // Currently I do not see an easy way to enforce the right order of byte frames through // the Argument captor in order to correctly assemble them into a string for assertion. // Normally, the web socket client ensures that all partial frames are assembled correctly -// ByteBuffer allocatedByteBuffer = ByteBuffer.allocate(originalStringBytes.length); -// for (ByteBuffer allCapturedFragment : allCapturedFragments) { -// allocatedByteBuffer = allocatedByteBuffer.put(allCapturedFragment); -// } -// final byte[] actualStringBytes = allocatedByteBuffer.array(); -// -// assertThat(tanuki).isEqualTo(new String(actualStringBytes, StandardCharsets.UTF_8)); + // ByteBuffer allocatedByteBuffer = ByteBuffer.allocate(originalStringBytes.length); + // for (ByteBuffer allCapturedFragment : allCapturedFragments) { + // allocatedByteBuffer = allocatedByteBuffer.put(allCapturedFragment); + // } + // final byte[] actualStringBytes = allocatedByteBuffer.array(); + // + // assertThat(tanuki).isEqualTo(new String(actualStringBytes, StandardCharsets.UTF_8)); } @Test @@ -313,10 +311,8 @@ public void onWebSocketText_DispatchesExpectedServerTextResponseWhenPolicyOnce() serverWebSocket.onWebSocketConnect(mockSession); serverWebSocket.onWebSocketText(HELLO_FROM_CLIENT); - verify(spyScheduledExecutorService, times(1)).schedule( - runnableCaptor.capture(), - eq(250L), - eq(TimeUnit.MILLISECONDS)); + verify(spyScheduledExecutorService, times(1)) + .schedule(runnableCaptor.capture(), eq(250L), eq(TimeUnit.MILLISECONDS)); // Execute the captured future which was passed in to the // ScheduledExecutorService, in order to trigger the behavior @@ -326,8 +322,8 @@ public void onWebSocketText_DispatchesExpectedServerTextResponseWhenPolicyOnce() assertThat(stringCaptor.getValue()).isEqualTo(HELLO_FROM_SERVER); } - private StubWebSocketConfig buildStubWebSocketConfig(final boolean setOnOpen, - final StubWebSocketServerResponse webSocketServerResponse) { + private StubWebSocketConfig buildStubWebSocketConfig( + final boolean setOnOpen, final StubWebSocketServerResponse webSocketServerResponse) { final StubWebSocketClientRequest webSocketClientRequest = new StubWebSocketClientRequest.Builder() .withBody(HELLO_FROM_CLIENT) .withMessageType(StubWebSocketMessageType.TEXT.toString()) @@ -344,4 +340,4 @@ private StubWebSocketConfig buildStubWebSocketConfig(final boolean setOnOpen, .withOnMessage(Collections.singletonList(webSocketOnMessageLifeCycle)) .build(); } -} \ No newline at end of file +} diff --git a/src/test/java/io/github/azagniotov/stubby4j/stubs/RegexParserTest.java b/src/test/java/io/github/azagniotov/stubby4j/stubs/RegexParserTest.java index 3bbd9bc2e..9e57a2f40 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/stubs/RegexParserTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/stubs/RegexParserTest.java @@ -1,14 +1,28 @@ -package io.github.azagniotov.stubby4j.stubs; - -import org.junit.Test; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import java.util.HashMap; -import java.util.Map; +package io.github.azagniotov.stubby4j.stubs; import static com.google.common.truth.Truth.assertThat; import static io.github.azagniotov.stubby4j.stubs.RegexParser.REGEX_CHARS; import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; public class RegexParserTest { @@ -25,20 +39,27 @@ public void shouldDetermineStringAsPotentialRegexPatterns() throws Exception { assertThat(RegexParser.potentialRegex("{JsonObject}")).isTrue(); assertThat(RegexParser.potentialRegex("{JsonObject: [Array]}")).isTrue(); assertThat(RegexParser.potentialRegex("This|That$")).isTrue(); - assertThat(RegexParser.potentialRegex("I have a lot of $, how about you?")).isTrue(); - assertThat(RegexParser.potentialRegex("^I have a lot of, how about you?")).isTrue(); + assertThat(RegexParser.potentialRegex("I have a lot of $, how about you?")) + .isTrue(); + assertThat(RegexParser.potentialRegex("^I have a lot of, how about you?")) + .isTrue(); assertThat(RegexParser.potentialRegex("^[a-zA-Z]$")).isTrue(); - assertThat(RegexParser.potentialRegex("^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")).isTrue(); - assertThat(RegexParser.potentialRegex("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$")).isTrue(); + assertThat(RegexParser.potentialRegex("^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")) + .isTrue(); + assertThat(RegexParser.potentialRegex("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$")) + .isTrue(); assertThat(RegexParser.potentialRegex("^\\\\")).isTrue(); assertThat(RegexParser.potentialRegex("^\\")).isTrue(); assertThat(RegexParser.potentialRegex("**")).isTrue(); assertThat(RegexParser.potentialRegex("()")).isTrue(); assertThat(RegexParser.potentialRegex("!\"~")).isFalse(); - assertThat(RegexParser.potentialRegex("This is a sentence ending with a dot.")).isFalse(); - assertThat(RegexParser.potentialRegex("Is this a sentence ending with a question?")).isFalse(); - assertThat(RegexParser.potentialRegex("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")).isFalse(); + assertThat(RegexParser.potentialRegex("This is a sentence ending with a dot.")) + .isFalse(); + assertThat(RegexParser.potentialRegex("Is this a sentence ending with a question?")) + .isFalse(); + assertThat(RegexParser.potentialRegex("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")) + .isFalse(); assertThat(RegexParser.potentialRegex("")).isFalse(); assertThat(RegexParser.potentialRegex(")")).isFalse(); assertThat(RegexParser.potentialRegex(" ")).isFalse(); @@ -47,30 +68,36 @@ public void shouldDetermineStringAsPotentialRegexPatterns() throws Exception { assertThat(RegexParser.potentialRegex("////////")).isFalse(); assertThat(RegexParser.potentialRegex("")).isFalse(); assertThat(RegexParser.potentialRegex("abcdeABCDE")).isFalse(); - assertThat(RegexParser.potentialRegex(Character.toString((char) (REGEX_CHARS[0] - 1)))).isFalse(); - assertThat(RegexParser.potentialRegex(Character.toString((char) (REGEX_CHARS[REGEX_CHARS.length - 1] + 1)))).isFalse(); + assertThat(RegexParser.potentialRegex(Character.toString((char) (REGEX_CHARS[0] - 1)))) + .isFalse(); + assertThat(RegexParser.potentialRegex(Character.toString((char) (REGEX_CHARS[REGEX_CHARS.length - 1] + 1)))) + .isFalse(); } @Test public void shouldNotMatchWhenRegexPatternWithSyntaxError() throws Exception { final String patternWithSyntaxError = "^abc[xyz{*"; - boolean match = RegexParser.INSTANCE.match(patternWithSyntaxError, "someStringToMatch", "templateTokenName", new HashMap<>()); + boolean match = RegexParser.INSTANCE.match( + patternWithSyntaxError, "someStringToMatch", "templateTokenName", new HashMap<>()); assertThat(match).isFalse(); } @Test public void shouldMatchSubjectWithMultiline() throws Exception { - final String testSubject = - "Biggest tech companies in the world by their market value as of 2018:" + BR + - "Apple: $741.8 billion. In 2014, Apple, Inc. introduced a programming language called Swift." + BR + - "In 2015, the company made Swift open-source, which allowed non-Apple developers to work " + - "on the project." + BR + "Record-breaking three-day sales of 13 million units of the company’s " + - "iPhone 6s and iPhone 6s Plus were announced in October 2015." + BR + BR + - "Alphabet: $367.6 billion. In October 2015, Google restructured the company so that Alphabet, Inc." + BR + - "became the parent company under which Google operates. Alphabet owns all of Google's side projects," + BR + - "such as life-extension company Calico, innovative technology developer Google X, high-speed Internet" + BR + - "provider Fiber and Google's smart home project Nest."; + final String testSubject = "Biggest tech companies in the world by their market value as of 2018:" + BR + + "Apple: $741.8 billion. In 2014, Apple, Inc. introduced a programming language called Swift." + + BR + "In 2015, the company made Swift open-source, which allowed non-Apple developers to work " + + "on the project." + + BR + "Record-breaking three-day sales of 13 million units of the company’s " + + "iPhone 6s and iPhone 6s Plus were announced in October 2015." + + BR + BR + + "Alphabet: $367.6 billion. In October 2015, Google restructured the company so that Alphabet, Inc." + + BR + + "became the parent company under which Google operates. Alphabet owns all of Google's side projects," + + BR + + "such as life-extension company Calico, innovative technology developer Google X, high-speed Internet" + + BR + "provider Fiber and Google's smart home project Nest."; final String regexPattern = "(.*)\\s+Apple:\\s+(.*)\\s+Alphabet:\\s+(.*)"; @@ -78,14 +105,20 @@ public void shouldMatchSubjectWithMultiline() throws Exception { boolean match = RegexParser.INSTANCE.match(regexPattern, testSubject, "token", regexGroups); assertThat(match).isTrue(); - assertThat(regexGroups.get("token.1").trim()).isEqualTo("Biggest tech companies in the world by their market value as of 2018:"); - assertThat(regexGroups.get("token.2").trim()).isEqualTo("$741.8 billion. In 2014, Apple, Inc. introduced a programming language called Swift." + BR + - "In 2015, the company made Swift open-source, which allowed non-Apple developers to work " + - "on the project." + BR + "Record-breaking three-day sales of 13 million units of the company’s " + - "iPhone 6s and iPhone 6s Plus were announced in October 2015."); - assertThat(regexGroups.get("token.3").trim()).isEqualTo("$367.6 billion. In October 2015, Google restructured the company so that Alphabet, Inc." + BR + - "became the parent company under which Google operates. Alphabet owns all of Google's side projects," + BR + - "such as life-extension company Calico, innovative technology developer Google X, high-speed Internet" + BR + - "provider Fiber and Google's smart home project Nest."); + assertThat(regexGroups.get("token.1").trim()) + .isEqualTo("Biggest tech companies in the world by their market value as of 2018:"); + assertThat(regexGroups.get("token.2").trim()) + .isEqualTo("$741.8 billion. In 2014, Apple, Inc. introduced a programming language called Swift." + BR + + "In 2015, the company made Swift open-source, which allowed non-Apple developers to work " + + "on the project." + + BR + "Record-breaking three-day sales of 13 million units of the company’s " + + "iPhone 6s and iPhone 6s Plus were announced in October 2015."); + assertThat(regexGroups.get("token.3").trim()) + .isEqualTo( + "$367.6 billion. In October 2015, Google restructured the company so that Alphabet, Inc." + BR + + "became the parent company under which Google operates. Alphabet owns all of Google's side projects," + + BR + + "such as life-extension company Calico, innovative technology developer Google X, high-speed Internet" + + BR + "provider Fiber and Google's smart home project Nest."); } } diff --git a/src/test/java/io/github/azagniotov/stubby4j/stubs/StubHttpLifecycleBuilderTest.java b/src/test/java/io/github/azagniotov/stubby4j/stubs/StubHttpLifecycleBuilderTest.java index 5c1dec652..c829b2c71 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/stubs/StubHttpLifecycleBuilderTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/stubs/StubHttpLifecycleBuilderTest.java @@ -1,5 +1,30 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs; +import static com.google.common.truth.Truth.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; import org.eclipse.jetty.http.HttpStatus.Code; import org.junit.Before; import org.junit.Rule; @@ -8,16 +33,6 @@ import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; - -import static com.google.common.truth.Truth.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; - @RunWith(MockitoJUnitRunner.class) public class StubHttpLifecycleBuilderTest { @@ -65,14 +80,16 @@ public void shouldReturnStubResponse_WhenNoSequenceResponses() throws Exception .withBody("SELF") .build(); - final StubHttpLifecycle stubHttpLifecycle = httpCycleBuilder.withResponse(stubResponse).build(); + final StubHttpLifecycle stubHttpLifecycle = + httpCycleBuilder.withResponse(stubResponse).build(); assertThat(stubHttpLifecycle.getResponse(true)).isEqualTo(stubResponse); } @Test public void shouldReturnDescription_WhenDescription() { - final StubHttpLifecycle stubHttpLifecycle = httpCycleBuilder.withDescription("wibble").build(); + final StubHttpLifecycle stubHttpLifecycle = + httpCycleBuilder.withDescription("wibble").build(); assertThat(stubHttpLifecycle.getDescription()).isEqualTo("wibble"); } @@ -90,13 +107,13 @@ public void shouldThrow_WhenResponseObjectIsNotCollectionType() throws Exception expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Trying to set response of the wrong type"); - httpCycleBuilder.withResponse(new HashMap<>()).build(); } @Test public void shouldReturnDefaultStubResponse_WhenNoSequenceResponsePresentInTheList() throws Exception { - final StubHttpLifecycle stubHttpLifecycle = httpCycleBuilder.withResponse(new LinkedList<>()).build(); + final StubHttpLifecycle stubHttpLifecycle = + httpCycleBuilder.withResponse(new LinkedList<>()).build(); final StubResponse actualStubbedResponse = stubHttpLifecycle.getResponse(true); assertThat(actualStubbedResponse.getHttpStatusCode()).isEqualTo(Code.OK); @@ -114,11 +131,17 @@ public void shouldReturnSequenceResponse_WhenOneSequenceResponsePresent() throws final Code expectedStatus = Code.OK; final String expectedBody = "This is a sequence response #1"; - final List sequence = new LinkedList() {{ - add(responseBuilder.withHttpStatusCode(expectedStatus).withBody(expectedBody).build()); - }}; - - final StubHttpLifecycle stubHttpLifecycle = httpCycleBuilder.withResponse(sequence).build(); + final List sequence = new LinkedList() { + { + add(responseBuilder + .withHttpStatusCode(expectedStatus) + .withBody(expectedBody) + .build()); + } + }; + + final StubHttpLifecycle stubHttpLifecycle = + httpCycleBuilder.withResponse(sequence).build(); final StubResponse actualStubbedResponse = stubHttpLifecycle.getResponse(true); assertThat(actualStubbedResponse).isNotEqualTo(stubResponse); @@ -138,12 +161,21 @@ public void shouldReturnSecondSequenceResponseAfterSecondCall_WhenTwoSequenceRes final Code expectedStatus = Code.INTERNAL_SERVER_ERROR; final String expectedBody = "This is a sequence response #2"; - final List sequence = new LinkedList() {{ - add(responseBuilder.withHttpStatusCode(Code.OK).withBody("This is a sequence response #1").build()); - add(responseBuilder.withHttpStatusCode(expectedStatus).withBody(expectedBody).build()); - }}; - - final StubHttpLifecycle stubHttpLifecycle = httpCycleBuilder.withResponse(sequence).build(); + final List sequence = new LinkedList() { + { + add(responseBuilder + .withHttpStatusCode(Code.OK) + .withBody("This is a sequence response #1") + .build()); + add(responseBuilder + .withHttpStatusCode(expectedStatus) + .withBody(expectedBody) + .build()); + } + }; + + final StubHttpLifecycle stubHttpLifecycle = + httpCycleBuilder.withResponse(sequence).build(); // Do not remove this stubbing, even if this is an unused variable final StubResponse irrelevantStubbedResponse = stubHttpLifecycle.getResponse(true); @@ -162,7 +194,8 @@ public void shouldRequireBasicAuthorization() throws Exception { .withYAMLHeaderAuthorizationBasic(AUTHORIZATION_HEADER_BASIC) .build(); - final StubHttpLifecycle stubHttpLifecycle = httpCycleBuilder.withRequest(stubRequest).build(); + final StubHttpLifecycle stubHttpLifecycle = + httpCycleBuilder.withRequest(stubRequest).build(); assertThat(stubHttpLifecycle.isAuthorizationRequired()).isTrue(); } @@ -174,7 +207,8 @@ public void shouldRequireBearerAuthorization() throws Exception { .withYAMLHeaderAuthorizationBasic(AUTHORIZATION_HEADER_BEARER) .build(); - final StubHttpLifecycle stubHttpLifecycle = httpCycleBuilder.withRequest(stubRequest).build(); + final StubHttpLifecycle stubHttpLifecycle = + httpCycleBuilder.withRequest(stubRequest).build(); assertThat(stubHttpLifecycle.isAuthorizationRequired()).isTrue(); } @@ -186,7 +220,8 @@ public void shouldGetRawBasicAuthorizationHttpHeader() throws Exception { .withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, AUTHORIZATION_HEADER_BASIC) .build(); - final StubHttpLifecycle stubHttpLifecycle = httpCycleBuilder.withRequest(stubRequest).build(); + final StubHttpLifecycle stubHttpLifecycle = + httpCycleBuilder.withRequest(stubRequest).build(); assertThat(AUTHORIZATION_HEADER_BASIC).isEqualTo(stubHttpLifecycle.getRawHeaderAuthorization()); } @@ -198,45 +233,71 @@ public void shouldGetRawBearerAuthorizationHttpHeader() throws Exception { .withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, AUTHORIZATION_HEADER_BEARER) .build(); - final StubHttpLifecycle stubHttpLifecycle = httpCycleBuilder.withRequest(stubRequest).build(); + final StubHttpLifecycle stubHttpLifecycle = + httpCycleBuilder.withRequest(stubRequest).build(); assertThat(AUTHORIZATION_HEADER_BEARER).isEqualTo(stubHttpLifecycle.getRawHeaderAuthorization()); } @Test public void shouldNotAuthorizeViaBasic_WhenAssertingAuthorizationHeaderBasicIsNotSet() throws Exception { - final StubRequest assertingStubRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).build(); - final StubHttpLifecycle assertingStubHttpLifecycle = httpCycleBuilder.withRequest(assertingStubRequest).build(); + final StubRequest assertingStubRequest = + requestBuilder.withUrl(SOME_RESOURCE_URI).build(); + final StubHttpLifecycle assertingStubHttpLifecycle = + httpCycleBuilder.withRequest(assertingStubRequest).build(); - final StubRequest stubbedStubRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withYAMLHeaderAuthorizationBasic(AUTHORIZATION_HEADER_BASIC).build(); - final StubHttpLifecycle stubbedStubHttpLifecycle = httpCycleBuilder.withRequest(stubbedStubRequest).build(); + final StubRequest stubbedStubRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withYAMLHeaderAuthorizationBasic(AUTHORIZATION_HEADER_BASIC) + .build(); + final StubHttpLifecycle stubbedStubHttpLifecycle = + httpCycleBuilder.withRequest(stubbedStubRequest).build(); - assertThat(stubbedStubHttpLifecycle.isIncomingRequestUnauthorized(assertingStubHttpLifecycle)).isTrue(); + assertThat(stubbedStubHttpLifecycle.isIncomingRequestUnauthorized(assertingStubHttpLifecycle)) + .isTrue(); } @Test public void shouldNotAuthorizeViaBasic_WhenAuthorizationHeaderBasicIsNotTheSame() throws Exception { - final StubRequest assertingRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withYAMLHeaderAuthorizationBasic(AUTHORIZATION_HEADER_BASIC_INVALID).build(); - final StubRequest stubbedRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withYAMLHeaderAuthorizationBasic(AUTHORIZATION_HEADER_BASIC).build(); + final StubRequest assertingRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withYAMLHeaderAuthorizationBasic(AUTHORIZATION_HEADER_BASIC_INVALID) + .build(); + final StubRequest stubbedRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withYAMLHeaderAuthorizationBasic(AUTHORIZATION_HEADER_BASIC) + .build(); - final StubHttpLifecycle spyStubbedStubHttpLifecycle = spy(httpCycleBuilder.withRequest(stubbedRequest).build()); - final StubHttpLifecycle spyAssertingStubHttpLifecycle = spy(httpCycleBuilder.withRequest(assertingRequest).build()); + final StubHttpLifecycle spyStubbedStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(stubbedRequest).build()); + final StubHttpLifecycle spyAssertingStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(assertingRequest).build()); - assertThat(spyStubbedStubHttpLifecycle.isIncomingRequestUnauthorized(spyAssertingStubHttpLifecycle)).isTrue(); + assertThat(spyStubbedStubHttpLifecycle.isIncomingRequestUnauthorized(spyAssertingStubHttpLifecycle)) + .isTrue(); } @Test public void shouldVerifyBehaviour_WhenAuthorizationHeaderBasicIsNotTheSame() throws Exception { - final StubRequest assertingRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withYAMLHeaderAuthorizationBasic(AUTHORIZATION_HEADER_BASIC_INVALID).build(); - final StubRequest stubbedRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withYAMLHeaderAuthorizationBasic(AUTHORIZATION_HEADER_BASIC).build(); + final StubRequest assertingRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withYAMLHeaderAuthorizationBasic(AUTHORIZATION_HEADER_BASIC_INVALID) + .build(); + final StubRequest stubbedRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withYAMLHeaderAuthorizationBasic(AUTHORIZATION_HEADER_BASIC) + .build(); - final StubHttpLifecycle spyStubbedStubHttpLifecycle = spy(httpCycleBuilder.withRequest(stubbedRequest).build()); - final StubHttpLifecycle spyAssertingStubHttpLifecycle = spy(httpCycleBuilder.withRequest(assertingRequest).build()); + final StubHttpLifecycle spyStubbedStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(stubbedRequest).build()); + final StubHttpLifecycle spyAssertingStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(assertingRequest).build()); spyStubbedStubHttpLifecycle.isIncomingRequestUnauthorized(spyAssertingStubHttpLifecycle); verify(spyAssertingStubHttpLifecycle).getRawHeaderAuthorization(); - verify(spyAssertingStubHttpLifecycle, never()).getStubbedHeaderAuthorization(any(StubbableAuthorizationType.class)); + verify(spyAssertingStubHttpLifecycle, never()) + .getStubbedHeaderAuthorization(any(StubbableAuthorizationType.class)); verify(spyStubbedStubHttpLifecycle, never()).getRawHeaderAuthorization(); verify(spyStubbedStubHttpLifecycle).getStubbedHeaderAuthorization(StubbableAuthorizationType.BASIC); @@ -244,27 +305,45 @@ public void shouldVerifyBehaviour_WhenAuthorizationHeaderBasicIsNotTheSame() thr @Test public void shouldAuthorizeViaBasic_WhenAuthorizationHeaderBasicEquals() throws Exception { - final StubRequest assertingRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, AUTHORIZATION_HEADER_BASIC).build(); - final StubRequest stubbedRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withYAMLHeaderAuthorizationBasic(AUTHORIZATION_HEADER_BASIC).build(); + final StubRequest assertingRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, AUTHORIZATION_HEADER_BASIC) + .build(); + final StubRequest stubbedRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withYAMLHeaderAuthorizationBasic(AUTHORIZATION_HEADER_BASIC) + .build(); - final StubHttpLifecycle spyStubbedStubHttpLifecycle = spy(httpCycleBuilder.withRequest(stubbedRequest).build()); - final StubHttpLifecycle spyAssertingStubHttpLifecycle = spy(httpCycleBuilder.withRequest(assertingRequest).build()); + final StubHttpLifecycle spyStubbedStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(stubbedRequest).build()); + final StubHttpLifecycle spyAssertingStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(assertingRequest).build()); - assertThat(spyStubbedStubHttpLifecycle.isIncomingRequestUnauthorized(spyAssertingStubHttpLifecycle)).isFalse(); + assertThat(spyStubbedStubHttpLifecycle.isIncomingRequestUnauthorized(spyAssertingStubHttpLifecycle)) + .isFalse(); } @Test public void shouldVerifyBehaviour_WhenAuthorizationHeaderBasicEquals() throws Exception { - final StubRequest assertingRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, AUTHORIZATION_HEADER_BASIC).build(); - final StubRequest stubbedRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withYAMLHeaderAuthorizationBasic(AUTHORIZATION_HEADER_BASIC).build(); + final StubRequest assertingRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, AUTHORIZATION_HEADER_BASIC) + .build(); + final StubRequest stubbedRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withYAMLHeaderAuthorizationBasic(AUTHORIZATION_HEADER_BASIC) + .build(); - final StubHttpLifecycle spyStubbedStubHttpLifecycle = spy(httpCycleBuilder.withRequest(stubbedRequest).build()); - final StubHttpLifecycle spyAssertingStubHttpLifecycle = spy(httpCycleBuilder.withRequest(assertingRequest).build()); + final StubHttpLifecycle spyStubbedStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(stubbedRequest).build()); + final StubHttpLifecycle spyAssertingStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(assertingRequest).build()); spyStubbedStubHttpLifecycle.isIncomingRequestUnauthorized(spyAssertingStubHttpLifecycle); verify(spyAssertingStubHttpLifecycle).getRawHeaderAuthorization(); - verify(spyAssertingStubHttpLifecycle, never()).getStubbedHeaderAuthorization(any(StubbableAuthorizationType.class)); + verify(spyAssertingStubHttpLifecycle, never()) + .getStubbedHeaderAuthorization(any(StubbableAuthorizationType.class)); verify(spyStubbedStubHttpLifecycle, never()).getRawHeaderAuthorization(); verify(spyStubbedStubHttpLifecycle).getStubbedHeaderAuthorization(StubbableAuthorizationType.BASIC); @@ -272,27 +351,41 @@ public void shouldVerifyBehaviour_WhenAuthorizationHeaderBasicEquals() throws Ex @Test public void shouldNotAuthorizeViaBearer_WhenAssertingAuthorizationHeaderBearerIsNotSet() throws Exception { - final StubRequest assertingRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).build(); - final StubRequest stubbedRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withYAMLHeaderAuthorizationBearer(AUTHORIZATION_HEADER_BEARER).build(); + final StubRequest assertingRequest = + requestBuilder.withUrl(SOME_RESOURCE_URI).build(); + final StubRequest stubbedRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withYAMLHeaderAuthorizationBearer(AUTHORIZATION_HEADER_BEARER) + .build(); - final StubHttpLifecycle spyStubbedStubHttpLifecycle = spy(httpCycleBuilder.withRequest(stubbedRequest).build()); - final StubHttpLifecycle spyAssertingStubHttpLifecycle = spy(httpCycleBuilder.withRequest(assertingRequest).build()); + final StubHttpLifecycle spyStubbedStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(stubbedRequest).build()); + final StubHttpLifecycle spyAssertingStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(assertingRequest).build()); - assertThat(spyStubbedStubHttpLifecycle.isIncomingRequestUnauthorized(spyAssertingStubHttpLifecycle)).isTrue(); + assertThat(spyStubbedStubHttpLifecycle.isIncomingRequestUnauthorized(spyAssertingStubHttpLifecycle)) + .isTrue(); } @Test public void shouldVerifyBehaviour_WhenAuthorizationHeaderBearerIsNotSet() throws Exception { - final StubRequest assertingRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).build(); - final StubRequest stubbedRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withYAMLHeaderAuthorizationBearer(AUTHORIZATION_HEADER_BEARER).build(); + final StubRequest assertingRequest = + requestBuilder.withUrl(SOME_RESOURCE_URI).build(); + final StubRequest stubbedRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withYAMLHeaderAuthorizationBearer(AUTHORIZATION_HEADER_BEARER) + .build(); - final StubHttpLifecycle spyStubbedStubHttpLifecycle = spy(httpCycleBuilder.withRequest(stubbedRequest).build()); - final StubHttpLifecycle spyAssertingStubHttpLifecycle = spy(httpCycleBuilder.withRequest(assertingRequest).build()); + final StubHttpLifecycle spyStubbedStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(stubbedRequest).build()); + final StubHttpLifecycle spyAssertingStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(assertingRequest).build()); spyStubbedStubHttpLifecycle.isIncomingRequestUnauthorized(spyAssertingStubHttpLifecycle); verify(spyAssertingStubHttpLifecycle).getRawHeaderAuthorization(); - verify(spyAssertingStubHttpLifecycle, never()).getStubbedHeaderAuthorization(any(StubbableAuthorizationType.class)); + verify(spyAssertingStubHttpLifecycle, never()) + .getStubbedHeaderAuthorization(any(StubbableAuthorizationType.class)); verify(spyStubbedStubHttpLifecycle, never()).getRawHeaderAuthorization(); verify(spyStubbedStubHttpLifecycle).getStubbedHeaderAuthorization(StubbableAuthorizationType.BEARER); @@ -301,28 +394,46 @@ public void shouldVerifyBehaviour_WhenAuthorizationHeaderBearerIsNotSet() throws @Test public void shouldNotAuthorizeViaBearer_WhenAuthorizationHeaderBearerIsNotTheSame() throws Exception { - final StubRequest stubbedRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withYAMLHeaderAuthorizationBearer("Bearer Ym9iOnNlY3JldA==").build(); - final StubRequest assertingRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, "Bearer 888888888888==").build(); + final StubRequest stubbedRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withYAMLHeaderAuthorizationBearer("Bearer Ym9iOnNlY3JldA==") + .build(); + final StubRequest assertingRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, "Bearer 888888888888==") + .build(); - final StubHttpLifecycle spyStubbedStubHttpLifecycle = spy(httpCycleBuilder.withRequest(stubbedRequest).build()); - final StubHttpLifecycle spyAssertingStubHttpLifecycle = spy(httpCycleBuilder.withRequest(assertingRequest).build()); + final StubHttpLifecycle spyStubbedStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(stubbedRequest).build()); + final StubHttpLifecycle spyAssertingStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(assertingRequest).build()); - assertThat(spyStubbedStubHttpLifecycle.isIncomingRequestUnauthorized(spyAssertingStubHttpLifecycle)).isTrue(); + assertThat(spyStubbedStubHttpLifecycle.isIncomingRequestUnauthorized(spyAssertingStubHttpLifecycle)) + .isTrue(); } @Test public void shouldVerifyBehaviour_WhenAuthorizationHeaderBearerIsNotTheSame() throws Exception { - final StubRequest stubbedRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withYAMLHeaderAuthorizationBearer("Bearer Ym9iOnNlY3JldA==").build(); - final StubRequest assertingRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, "Bearer 888888888888==").build(); + final StubRequest stubbedRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withYAMLHeaderAuthorizationBearer("Bearer Ym9iOnNlY3JldA==") + .build(); + final StubRequest assertingRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, "Bearer 888888888888==") + .build(); - final StubHttpLifecycle spyStubbedStubHttpLifecycle = spy(httpCycleBuilder.withRequest(stubbedRequest).build()); - final StubHttpLifecycle spyAssertingStubHttpLifecycle = spy(httpCycleBuilder.withRequest(assertingRequest).build()); + final StubHttpLifecycle spyStubbedStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(stubbedRequest).build()); + final StubHttpLifecycle spyAssertingStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(assertingRequest).build()); spyStubbedStubHttpLifecycle.isIncomingRequestUnauthorized(spyAssertingStubHttpLifecycle); verify(spyAssertingStubHttpLifecycle).getRawHeaderAuthorization(); - verify(spyAssertingStubHttpLifecycle, never()).getStubbedHeaderAuthorization(any(StubbableAuthorizationType.class)); + verify(spyAssertingStubHttpLifecycle, never()) + .getStubbedHeaderAuthorization(any(StubbableAuthorizationType.class)); verify(spyStubbedStubHttpLifecycle, never()).getRawHeaderAuthorization(); verify(spyStubbedStubHttpLifecycle).getStubbedHeaderAuthorization(StubbableAuthorizationType.BEARER); @@ -330,27 +441,45 @@ public void shouldVerifyBehaviour_WhenAuthorizationHeaderBearerIsNotTheSame() th @Test public void shouldAuthorizeViaBearer_WhenAuthorizationHeaderBearerEquals() throws Exception { - final StubRequest stubbedRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withYAMLHeaderAuthorizationBearer(AUTHORIZATION_HEADER_BEARER).build(); - final StubRequest assertingRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, AUTHORIZATION_HEADER_BEARER).build(); + final StubRequest stubbedRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withYAMLHeaderAuthorizationBearer(AUTHORIZATION_HEADER_BEARER) + .build(); + final StubRequest assertingRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withHeader(StubRequest.HTTP_HEADER_AUTHORIZATION, AUTHORIZATION_HEADER_BEARER) + .build(); - final StubHttpLifecycle spyStubbedStubHttpLifecycle = spy(httpCycleBuilder.withRequest(stubbedRequest).build()); - final StubHttpLifecycle spyAssertingStubHttpLifecycle = spy(httpCycleBuilder.withRequest(assertingRequest).build()); + final StubHttpLifecycle spyStubbedStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(stubbedRequest).build()); + final StubHttpLifecycle spyAssertingStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(assertingRequest).build()); - assertThat(spyStubbedStubHttpLifecycle.isIncomingRequestUnauthorized(spyAssertingStubHttpLifecycle)).isFalse(); + assertThat(spyStubbedStubHttpLifecycle.isIncomingRequestUnauthorized(spyAssertingStubHttpLifecycle)) + .isFalse(); } @Test public void shouldVerifyBehaviour_WhenAuthorizationHeaderBearerEquals() throws Exception { - final StubRequest stubbedRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withYAMLHeaderAuthorizationBearer(AUTHORIZATION_HEADER_BEARER).build(); - final StubRequest assertingRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withYAMLHeaderAuthorizationBearer(AUTHORIZATION_HEADER_BEARER).build(); + final StubRequest stubbedRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withYAMLHeaderAuthorizationBearer(AUTHORIZATION_HEADER_BEARER) + .build(); + final StubRequest assertingRequest = requestBuilder + .withUrl(SOME_RESOURCE_URI) + .withYAMLHeaderAuthorizationBearer(AUTHORIZATION_HEADER_BEARER) + .build(); - final StubHttpLifecycle spyStubbedStubHttpLifecycle = spy(httpCycleBuilder.withRequest(stubbedRequest).build()); - final StubHttpLifecycle spyAssertingStubHttpLifecycle = spy(httpCycleBuilder.withRequest(assertingRequest).build()); + final StubHttpLifecycle spyStubbedStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(stubbedRequest).build()); + final StubHttpLifecycle spyAssertingStubHttpLifecycle = + spy(httpCycleBuilder.withRequest(assertingRequest).build()); spyStubbedStubHttpLifecycle.isIncomingRequestUnauthorized(spyAssertingStubHttpLifecycle); verify(spyAssertingStubHttpLifecycle).getRawHeaderAuthorization(); - verify(spyAssertingStubHttpLifecycle, never()).getStubbedHeaderAuthorization(any(StubbableAuthorizationType.class)); + verify(spyAssertingStubHttpLifecycle, never()) + .getStubbedHeaderAuthorization(any(StubbableAuthorizationType.class)); verify(spyStubbedStubHttpLifecycle, never()).getRawHeaderAuthorization(); verify(spyStubbedStubHttpLifecycle).getStubbedHeaderAuthorization(StubbableAuthorizationType.BEARER); @@ -360,8 +489,10 @@ public void shouldVerifyBehaviour_WhenAuthorizationHeaderBearerEquals() throws E public void shouldReturnAjaxResponseContent_WhenStubTypeRequest() throws Exception { final String expectedPost = "this is a POST"; - final StubRequest stubRequest = requestBuilder.withUrl(SOME_RESOURCE_URI).withPost(expectedPost).build(); - final StubHttpLifecycle stubHttpLifecycle = httpCycleBuilder.withRequest(stubRequest).build(); + final StubRequest stubRequest = + requestBuilder.withUrl(SOME_RESOURCE_URI).withPost(expectedPost).build(); + final StubHttpLifecycle stubHttpLifecycle = + httpCycleBuilder.withRequest(stubRequest).build(); final String actualPost = stubHttpLifecycle.getAjaxResponseContent(StubTypes.REQUEST, "post"); assertThat(expectedPost).isEqualTo(actualPost); @@ -376,7 +507,8 @@ public void shouldReturnAjaxResponseContent_WhenStubTypeResponse() throws Except .withBody(expectedBody) .build(); - final StubHttpLifecycle stubHttpLifecycle = httpCycleBuilder.withResponse(stubResponse).build(); + final StubHttpLifecycle stubHttpLifecycle = + httpCycleBuilder.withResponse(stubResponse).build(); final String actualBody = stubHttpLifecycle.getAjaxResponseContent(StubTypes.RESPONSE, "body"); assertThat(expectedBody).isEqualTo(actualBody); diff --git a/src/test/java/io/github/azagniotov/stubby4j/stubs/StubMatcherTest.java b/src/test/java/io/github/azagniotov/stubby4j/stubs/StubMatcherTest.java index 03b1509a0..81b63dba2 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/stubs/StubMatcherTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/stubs/StubMatcherTest.java @@ -1,15 +1,29 @@ -package io.github.azagniotov.stubby4j.stubs; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.azagniotov.stubby4j.stubs; -import org.eclipse.jetty.http.HttpMethod; -import org.junit.Before; -import org.junit.Test; +import static com.google.common.truth.Truth.assertThat; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; - -import static com.google.common.truth.Truth.assertThat; +import org.eclipse.jetty.http.HttpMethod; +import org.junit.Before; +import org.junit.Test; public class StubMatcherTest { @@ -22,18 +36,24 @@ public void setUp() throws Exception { @Test public void arraysIntersect_ShouldReturnTrue_WhenDataStoreArrayEmpty() throws Exception { - final boolean isArraysIntersect = stubMatcher.listsIntersect(new ArrayList<>(), new ArrayList() {{ - add("apple"); - }}); + final boolean isArraysIntersect = stubMatcher.listsIntersect(new ArrayList<>(), new ArrayList() { + { + add("apple"); + } + }); assertThat(isArraysIntersect).isTrue(); } @Test public void arraysIntersect_ShouldReturnFalse_WhenAssertingArrayEmpty() throws Exception { - final boolean isArraysIntersect = stubMatcher.listsIntersect(new ArrayList() {{ - add("apple"); - }}, new ArrayList<>()); + final boolean isArraysIntersect = stubMatcher.listsIntersect( + new ArrayList() { + { + add("apple"); + } + }, + new ArrayList<>()); assertThat(isArraysIntersect).isFalse(); } @@ -41,12 +61,16 @@ public void arraysIntersect_ShouldReturnFalse_WhenAssertingArrayEmpty() throws E @Test public void arraysIntersect_ShouldReturnTrue_WhenTwoArraysHaveTheSameElements() throws Exception { final boolean isArraysIntersect = stubMatcher.listsIntersect( - new ArrayList() {{ - add("apple"); - }}, new ArrayList() {{ - add("apple"); - }} - ); + new ArrayList() { + { + add("apple"); + } + }, + new ArrayList() { + { + add("apple"); + } + }); assertThat(isArraysIntersect).isTrue(); } @@ -54,12 +78,16 @@ public void arraysIntersect_ShouldReturnTrue_WhenTwoArraysHaveTheSameElements() @Test public void arraysIntersect_ShouldReturnFalse_WhenTwoArraysDontHaveTheSameElements() throws Exception { final boolean isArraysIntersect = stubMatcher.listsIntersect( - new ArrayList() {{ - add("apple"); - }}, new ArrayList() {{ - add("orange"); - }} - ); + new ArrayList() { + { + add("apple"); + } + }, + new ArrayList() { + { + add("orange"); + } + }); assertThat(isArraysIntersect).isFalse(); } @@ -68,7 +96,8 @@ public void arraysIntersect_ShouldReturnFalse_WhenTwoArraysDontHaveTheSameElemen public void stringsMatch_ShouldReturnTrue_WhenDataStoreValueNull() throws Exception { final String dataStoreVlaue = null; final String assertingValue = "blah"; - final boolean isStringsMatch = stubMatcher.stringsMatch(dataStoreVlaue, assertingValue, "arbitrary template token name"); + final boolean isStringsMatch = + stubMatcher.stringsMatch(dataStoreVlaue, assertingValue, "arbitrary template token name"); assertThat(isStringsMatch).isTrue(); } @@ -77,7 +106,8 @@ public void stringsMatch_ShouldReturnTrue_WhenDataStoreValueNull() throws Except public void stringsMatch_ShouldReturnTrue_WhenDataStoreValueEmpty() throws Exception { final String dataStoreVlaue = ""; final String assertingValue = "blah"; - final boolean isStringsMatch = stubMatcher.stringsMatch(dataStoreVlaue, assertingValue, "arbitrary template token name"); + final boolean isStringsMatch = + stubMatcher.stringsMatch(dataStoreVlaue, assertingValue, "arbitrary template token name"); assertThat(isStringsMatch).isTrue(); } @@ -86,7 +116,8 @@ public void stringsMatch_ShouldReturnTrue_WhenDataStoreValueEmpty() throws Excep public void stringsMatch_ShouldReturnFalse_WhenAssertingValueNull() throws Exception { final String dataStoreVlaue = "stubbedValue"; final String assertingValue = null; - final boolean isStringsMatch = stubMatcher.stringsMatch(dataStoreVlaue, assertingValue, "arbitrary template token name"); + final boolean isStringsMatch = + stubMatcher.stringsMatch(dataStoreVlaue, assertingValue, "arbitrary template token name"); assertThat(isStringsMatch).isFalse(); } @@ -95,7 +126,8 @@ public void stringsMatch_ShouldReturnFalse_WhenAssertingValueNull() throws Excep public void stringsMatch_ShouldReturnFalse_WhenAssertingValueEmpty() throws Exception { final String dataStoreVlaue = "stubbedValue"; final String assertingValue = ""; - final boolean isStringsMatch = stubMatcher.stringsMatch(dataStoreVlaue, assertingValue, "arbitrary template token name"); + final boolean isStringsMatch = + stubMatcher.stringsMatch(dataStoreVlaue, assertingValue, "arbitrary template token name"); assertThat(isStringsMatch).isFalse(); } @@ -112,9 +144,11 @@ public void mapsMatch_ShouldReturnTrue_WhenDataStoreMapEmptyAndAssertingMapEmpty @Test public void mapsMatch_ShouldReturnTrue_WhenDataStoreMapEmpty() throws Exception { final Map dataStoreMap = new HashMap<>(); - final Map assertingMap = new HashMap() {{ - put("key", "value"); - }}; + final Map assertingMap = new HashMap() { + { + put("key", "value"); + } + }; final boolean isMapsMatch = stubMatcher.mapsMatch(dataStoreMap, assertingMap, "arbitrary template token name"); assertThat(isMapsMatch).isTrue(); @@ -122,9 +156,11 @@ public void mapsMatch_ShouldReturnTrue_WhenDataStoreMapEmpty() throws Exception @Test public void mapsMatch_ShouldReturnFalse_WhenDataStoreMapNotEmptyAndAssertingMapEmpty() throws Exception { - final Map dataStoreMap = new HashMap() {{ - put("key", "value"); - }}; + final Map dataStoreMap = new HashMap() { + { + put("key", "value"); + } + }; final Map assertingMap = new HashMap<>(); final boolean isMapsMatch = stubMatcher.mapsMatch(dataStoreMap, assertingMap, "arbitrary template token name"); @@ -133,12 +169,16 @@ public void mapsMatch_ShouldReturnFalse_WhenDataStoreMapNotEmptyAndAssertingMapE @Test public void mapsMatch_ShouldReturnFalse_WhenAssertingMapDoesNotContainDataStoreKey() throws Exception { - final Map dataStoreMap = new HashMap() {{ - put("requiredKey", "requiredValue"); - }}; - final Map assertingMap = new HashMap() {{ - put("someKey", "someValue"); - }}; + final Map dataStoreMap = new HashMap() { + { + put("requiredKey", "requiredValue"); + } + }; + final Map assertingMap = new HashMap() { + { + put("someKey", "someValue"); + } + }; final boolean isMapsMatch = stubMatcher.mapsMatch(dataStoreMap, assertingMap, "arbitrary template token name"); assertThat(isMapsMatch).isFalse(); @@ -146,12 +186,16 @@ public void mapsMatch_ShouldReturnFalse_WhenAssertingMapDoesNotContainDataStoreK @Test public void mapsMatch_ShouldReturnFalse_WhenAssertingMapDoesNotContainDataStoreValue() throws Exception { - final Map dataStoreMap = new HashMap() {{ - put("requiredKey", "requiredValue"); - }}; - final Map assertingMap = new HashMap() {{ - put("requiredKey", "someValue"); - }}; + final Map dataStoreMap = new HashMap() { + { + put("requiredKey", "requiredValue"); + } + }; + final Map assertingMap = new HashMap() { + { + put("requiredKey", "someValue"); + } + }; final boolean isMapsMatch = stubMatcher.mapsMatch(dataStoreMap, assertingMap, "arbitrary template token name"); assertThat(isMapsMatch).isFalse(); @@ -159,12 +203,16 @@ public void mapsMatch_ShouldReturnFalse_WhenAssertingMapDoesNotContainDataStoreV @Test public void mapsMatch_ShouldReturnTrue_WhenAssertingMapMatchesDataStoreMap() throws Exception { - final Map dataStoreMap = new HashMap() {{ - put("requiredKey", "requiredValue"); - }}; - final Map assertingMap = new HashMap() {{ - put("requiredKey", "requiredValue"); - }}; + final Map dataStoreMap = new HashMap() { + { + put("requiredKey", "requiredValue"); + } + }; + final Map assertingMap = new HashMap() { + { + put("requiredKey", "requiredValue"); + } + }; final boolean isMapsMatch = stubMatcher.mapsMatch(dataStoreMap, assertingMap, "arbitrary template token name"); assertThat(isMapsMatch).isTrue(); @@ -172,9 +220,8 @@ public void mapsMatch_ShouldReturnTrue_WhenAssertingMapMatchesDataStoreMap() thr @Test public void postBodiesMatch_ShouldReturnTrue_WhenIsPostStubbedFalse() { - final StubRequest stubbedRequest = new StubRequest.Builder() - .withMethod(HttpMethod.POST.asString()) - .build(); + final StubRequest stubbedRequest = + new StubRequest.Builder().withMethod(HttpMethod.POST.asString()).build(); final boolean isBodiesMatch = stubMatcher.postBodiesMatch(stubbedRequest, null); assertThat(isBodiesMatch).isTrue(); @@ -184,10 +231,10 @@ public void postBodiesMatch_ShouldReturnTrue_WhenIsPostStubbedFalse() { public void postBodiesMatch_ShouldReturnFalse_WhenAssertingPostBodyNull() { final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost("stubbed").build(); - final StubRequest assertingRequest = new StubRequest.Builder() - .withMethod(HttpMethod.POST.asString()) + .withPost("stubbed") .build(); + final StubRequest assertingRequest = + new StubRequest.Builder().withMethod(HttpMethod.POST.asString()).build(); final boolean isBodiesMatch = stubMatcher.postBodiesMatch(stubbedRequest, assertingRequest); @@ -198,7 +245,8 @@ public void postBodiesMatch_ShouldReturnFalse_WhenAssertingPostBodyNull() { public void postBodiesMatch_ShouldReturnFalse_WhenAssertingBodyWhitespace() { final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost("stubbed").build(); + .withPost("stubbed") + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost(" ") @@ -213,7 +261,8 @@ public void postBodiesMatch_ShouldReturnFalse_WhenAssertingBodyWhitespace() { public void postBodiesMatch_ShouldReturnFalse_WhenDifferentJson() { final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost("{\"name\":\"tod\"}").build(); + .withPost("{\"name\":\"tod\"}") + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost("{\"name\":\"bob\"}") @@ -229,7 +278,8 @@ public void postBodiesMatch_ShouldReturnFalse_WhenDifferentJson() { public void postBodiesMatch_ShouldReturnTrue_WhenEquivalentJson() { final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost("{\"c\":\"d\",\"a\":\"b\"}").build(); + .withPost("{\"c\":\"d\",\"a\":\"b\"}") + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost("{\"a\":\"b\",\"c\":\"d\"}") @@ -245,7 +295,8 @@ public void postBodiesMatch_ShouldReturnTrue_WhenEquivalentJson() { public void postBodiesMatch_ShouldReturnTrue_WhenEquivalentJsonWithCustomContentType() { final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost("{\"c\":\"d\",\"a\":\"b\"}").build(); + .withPost("{\"c\":\"d\",\"a\":\"b\"}") + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost("{\"a\":\"b\",\"c\":\"d\"}") @@ -261,7 +312,8 @@ public void postBodiesMatch_ShouldReturnTrue_WhenEquivalentJsonWithCustomContent public void postBodiesMatch_ShouldReturnTrue_WhenEquivalentJsonWithCustomContentTypeAndCharset() { final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost("{\"c\":\"d\",\"a\":\"b\"}").build(); + .withPost("{\"c\":\"d\",\"a\":\"b\"}") + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost("{\"a\":\"b\",\"c\":\"d\"}") @@ -277,7 +329,8 @@ public void postBodiesMatch_ShouldReturnTrue_WhenEquivalentJsonWithCustomContent public void postBodiesMatch_ShouldReturnFalse_WhenDifferentXml() { final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost("two").build(); + .withPost("two") + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost("one") @@ -293,7 +346,8 @@ public void postBodiesMatch_ShouldReturnFalse_WhenDifferentXml() { public void postBodiesMatch_ShouldReturnTrue_WhenEquivalentXml() { final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost("ba").build(); + .withPost("ba") + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost("ab") @@ -307,20 +361,20 @@ public void postBodiesMatch_ShouldReturnTrue_WhenEquivalentXml() { @Test public void postBodiesMatchUsingVanillaRegex_ShouldReturnTrue() { - final String stubbedXml = "<\\?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"\\?>" + - ".*(.+?).*(.+?).*"; + final String stubbedXml = "<\\?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"\\?>" + + ".*(.+?).*(.+?).*"; - final String postedXml = - "\n" + - "\n" + - " ALEX-1\n" + - " ALEX-2\n" + - " ALEX-3\n" + - ""; + final String postedXml = "\n" + + "\n" + + " ALEX-1\n" + + " ALEX-2\n" + + " ALEX-3\n" + + ""; final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost(stubbedXml).build(); + .withPost(stubbedXml) + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost(postedXml) @@ -338,71 +392,70 @@ public void postBodiesMatchUsingComplexVanillaRegex_ShouldReturnTrue() { // Note: // 1. the '?' in are escaped as these are regex characters - final String stubbedXml = - "<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?>\n" + - "\n" + - " \n" + - " (.*)\n" + - " (.*)\n" + - " (.*)\n" + - " (.*)\n" + - " (.*)\n" + - " " + - " (.*)\n" + - " (.*)\n" + - " " + - " \n" + - " (.*)\n" + - " (.*)\n" + - " (.*)\n" + - " \n" + - " (.*)" + - " (.*)" + - " (.*)" + - ""; - - final String postedXml = - "\n" + - "\n" + - " \n" + - " Piramidon\n" + - " Generic Pharma Co.\n" + - " CAPSULE\n" + - " 125 mg\n" + - " 100\n" + - " " + - " Rob\n" + - " 37\n" + - " " + - " \n" + - " 0.00\n" + - " 123.000\n" + - " London has a lot of monkeys during summer\n" + - " \n" + - " ValueOne" + - " ValueTwo" + - " " + - " This is a text which span across a very very Very long line!" + - " " + - ""; + final String stubbedXml = "<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?>\n" + + "\n" + + " \n" + + " (.*)\n" + + " (.*)\n" + + " (.*)\n" + + " (.*)\n" + + " (.*)\n" + + " " + + " (.*)\n" + + " (.*)\n" + + " " + + " \n" + + " (.*)\n" + + " (.*)\n" + + " (.*)\n" + + " \n" + + " (.*)" + + " (.*)" + + " (.*)" + + ""; + + final String postedXml = "\n" + + "\n" + + " \n" + + " Piramidon\n" + + " Generic Pharma Co.\n" + + " CAPSULE\n" + + " 125 mg\n" + + " 100\n" + + " " + + " Rob\n" + + " 37\n" + + " " + + " \n" + + " 0.00\n" + + " 123.000\n" + + " London has a lot of monkeys during summer\n" + + " \n" + + " ValueOne" + + " ValueTwo" + + " " + + " This is a text which span across a very very Very long line!" + + " " + + ""; final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost(stubbedXml).build(); + .withPost(stubbedXml) + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost(postedXml) @@ -416,71 +469,70 @@ public void postBodiesMatchUsingComplexVanillaRegex_ShouldReturnTrue() { @Test public void postBodiesMatchUsingXMLUnitRegexPlaceholder_ShouldReturnTrue() { - final String stubbedXml = - "\n" + - "\n" + - " \n" + - " Piramidon\n" + - " Generic Pharma Co.\n" + - " CAPSULE\n" + - " 125 mg\n" + - " 100\n" + - " " + - " Rob\n" + - " 37\n" + - " " + - " \n" + - " 0.00\n" + - " 123.000\n" + - " ${xmlunit.matchesRegex(.*monkeys.*)}\n" + - " \n" + - " ValueOne" + - " ValueTwo" + - " ${xmlunit.matchesRegex(.*)}" + - ""; - - final String postedXml = - "\n" + - "\n" + - " \n" + - " Piramidon\n" + - " Generic Pharma Co.\n" + - " CAPSULE\n" + - " 125 mg\n" + - " 100\n" + - " " + - " Rob\n" + - " 37\n" + - " " + - " \n" + - " 0.00\n" + - " 123.000\n" + - " London has a lot of monkeys during summer\n" + - " \n" + - " ValueOne" + - " ValueTwo" + - " " + - " This is a text which span across a very very Very long line!" + - " " + - ""; + final String stubbedXml = "\n" + + "\n" + + " \n" + + " Piramidon\n" + + " Generic Pharma Co.\n" + + " CAPSULE\n" + + " 125 mg\n" + + " 100\n" + + " " + + " Rob\n" + + " 37\n" + + " " + + " \n" + + " 0.00\n" + + " 123.000\n" + + " ${xmlunit.matchesRegex(.*monkeys.*)}\n" + + " \n" + + " ValueOne" + + " ValueTwo" + + " ${xmlunit.matchesRegex(.*)}" + + ""; + + final String postedXml = "\n" + + "\n" + + " \n" + + " Piramidon\n" + + " Generic Pharma Co.\n" + + " CAPSULE\n" + + " 125 mg\n" + + " 100\n" + + " " + + " Rob\n" + + " 37\n" + + " " + + " \n" + + " 0.00\n" + + " 123.000\n" + + " London has a lot of monkeys during summer\n" + + " \n" + + " ValueOne" + + " ValueTwo" + + " " + + " This is a text which span across a very very Very long line!" + + " " + + ""; final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost(stubbedXml).build(); + .withPost(stubbedXml) + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost(postedXml) @@ -495,65 +547,64 @@ public void postBodiesMatchUsingXMLUnitRegexPlaceholder_ShouldReturnTrue() { @Test public void postBodiesMatch_ShouldReturnTrue_WhenEquivalentXmlWithAttributes() { - final String stubbedXml = - "\n" + - "\n" + - " \n" + - " Piramidon\n" + - " Generic Pharma Co.\n" + - " CAPSULE\n" + - " 125 mg\n" + - " 100\n" + - " " + - " Rob\n" + - " 37\n" + - " " + - " \n" + - " 0.00\n" + - " 123.000\n" + - " London\n" + - " \n" + - " ValueOne" + - " ValueTwo" + - " " + - " This is a text which span across a very very Very long line!" + - " " + - ""; - - final String postedXml = - "\n" + - "\n" + - " 37\n" + - " Rob\n" + - " ValueOne" + - " ValueTwo" + - " " + - " This is a text which span across a very very Very long line!" + - " " + - " \n" + - " London\n" + - " 123.000\n" + - " 0.00\n" + - " \n" + - " \n" + - " Piramidon\n" + - " Generic Pharma Co.\n" + - " CAPSULE\n" + - " 125 mg\n" + - " 100\n" + - " " + - ""; + final String stubbedXml = "\n" + + "\n" + + " \n" + + " Piramidon\n" + + " Generic Pharma Co.\n" + + " CAPSULE\n" + + " 125 mg\n" + + " 100\n" + + " " + + " Rob\n" + + " 37\n" + + " " + + " \n" + + " 0.00\n" + + " 123.000\n" + + " London\n" + + " \n" + + " ValueOne" + + " ValueTwo" + + " " + + " This is a text which span across a very very Very long line!" + + " " + + ""; + + final String postedXml = "\n" + + "\n" + + " 37\n" + + " Rob\n" + + " ValueOne" + + " ValueTwo" + + " " + + " This is a text which span across a very very Very long line!" + + " " + + " \n" + + " London\n" + + " 123.000\n" + + " 0.00\n" + + " \n" + + " \n" + + " Piramidon\n" + + " Generic Pharma Co.\n" + + " CAPSULE\n" + + " 125 mg\n" + + " 100\n" + + " " + + ""; final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost(stubbedXml).build(); + .withPost(stubbedXml) + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost(postedXml) @@ -568,67 +619,66 @@ public void postBodiesMatch_ShouldReturnTrue_WhenEquivalentXmlWithAttributes() { @Test public void postBodiesDoNotMatch_ShouldReturnFalse_WhenDifferentXmlWithAttributes() { - final String stubbedXml = - "\n" + - "\n" + - " \n" + - " Piramidon\n" + - " Generic Pharma Co.\n" + - " CAPSULE\n" + - " 125 mg\n" + - " 100\n" + - " 888\n" + - " " + - " Rob\n" + - " 37\n" + - " " + - " \n" + - " 0.00\n" + - " 123.000\n" + - " London\n" + - " \n" + - " ValueOne" + - " ValueTwo" + - " " + - " This is a text which span across a very very Very long line!" + - " " + - ""; - - final String postedXml = - "\n" + - "\n" + - " 37\n" + - " Rob\n" + - " Schneider\n" + - " ValueOne" + - " ValueTwo" + - " " + - " This is a text which span across a very very Very long line!" + - " " + - " \n" + - " London\n" + - " 123.000\n" + - " 0.00\n" + - " \n" + - " \n" + - " Piramidon\n" + - " Generic Pharma Co.\n" + - " CAPSULE\n" + - " 125 mg\n" + - " 100\n" + - " " + - ""; + final String stubbedXml = "\n" + + "\n" + + " \n" + + " Piramidon\n" + + " Generic Pharma Co.\n" + + " CAPSULE\n" + + " 125 mg\n" + + " 100\n" + + " 888\n" + + " " + + " Rob\n" + + " 37\n" + + " " + + " \n" + + " 0.00\n" + + " 123.000\n" + + " London\n" + + " \n" + + " ValueOne" + + " ValueTwo" + + " " + + " This is a text which span across a very very Very long line!" + + " " + + ""; + + final String postedXml = "\n" + + "\n" + + " 37\n" + + " Rob\n" + + " Schneider\n" + + " ValueOne" + + " ValueTwo" + + " " + + " This is a text which span across a very very Very long line!" + + " " + + " \n" + + " London\n" + + " 123.000\n" + + " 0.00\n" + + " \n" + + " \n" + + " Piramidon\n" + + " Generic Pharma Co.\n" + + " CAPSULE\n" + + " 125 mg\n" + + " 100\n" + + " " + + ""; final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost(stubbedXml).build(); + .withPost(stubbedXml) + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost(postedXml) @@ -644,7 +694,8 @@ public void postBodiesDoNotMatch_ShouldReturnFalse_WhenDifferentXmlWithAttribute public void postBodiesMatch_ShouldReturnTrue_WhenEquivalentXmlWithCustomContentType() { final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost("ba").build(); + .withPost("ba") + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost("ab") @@ -660,7 +711,8 @@ public void postBodiesMatch_ShouldReturnTrue_WhenEquivalentXmlWithCustomContentT public void postBodiesMatch_ShouldReturnTrue_WhenEquivalentXmlWithCustomContentTypeAndCharset() { final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost("ba").build(); + .withPost("ba") + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost("ab") @@ -676,7 +728,8 @@ public void postBodiesMatch_ShouldReturnTrue_WhenEquivalentXmlWithCustomContentT public void postBodiesMatch_ShouldReturnTrue_WhenStringMatch() { final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost("wibble").build(); + .withPost("wibble") + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost("wibble") @@ -691,7 +744,8 @@ public void postBodiesMatch_ShouldReturnTrue_WhenStringMatch() { public void postBodiesMatch_ShouldReturnFalse_WhenStringNotMatch() { final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost("wobble").build(); + .withPost("wobble") + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost("wibble") @@ -706,7 +760,8 @@ public void postBodiesMatch_ShouldReturnFalse_WhenStringNotMatch() { public void postBodiesMatch_ShouldReturnTrue_WhenEquivalentStringWithInvalidContentType() { final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost("wibble").build(); + .withPost("wibble") + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost("wibble") @@ -722,7 +777,8 @@ public void postBodiesMatch_ShouldReturnTrue_WhenEquivalentStringWithInvalidCont public void postBodiesMatch_ShouldReturnFalse_WhenNonEquivalentStringWithInvalidContentType() { final StubRequest stubbedRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) - .withPost("wibble").build(); + .withPost("wibble") + .build(); final StubRequest assertingRequest = new StubRequest.Builder() .withMethod(HttpMethod.POST.asString()) .withPost("wobble") diff --git a/src/test/java/io/github/azagniotov/stubby4j/stubs/StubProxyConfigBuilderTest.java b/src/test/java/io/github/azagniotov/stubby4j/stubs/StubProxyConfigBuilderTest.java index 6662bc6c0..726ae5fbe 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/stubs/StubProxyConfigBuilderTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/stubs/StubProxyConfigBuilderTest.java @@ -1,20 +1,34 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs; +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; + import io.github.azagniotov.stubby4j.stubs.proxy.StubProxyConfig; import io.github.azagniotov.stubby4j.stubs.proxy.StubProxyStrategy; +import java.util.HashMap; +import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; -import java.util.HashMap; -import java.util.Map; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; - - @RunWith(MockitoJUnitRunner.class) public class StubProxyConfigBuilderTest { @@ -41,7 +55,8 @@ public void stubbedProxyConfigDefaultStrategyNotAdditive() throws Exception { @Test public void stubbedProxyConfigStrategyAdditive() throws Exception { - final StubProxyConfig stubProxyConfig = builder.withStrategy(StubProxyStrategy.ADDITIVE.toString()).build(); + final StubProxyConfig stubProxyConfig = + builder.withStrategy(StubProxyStrategy.ADDITIVE.toString()).build(); assertThat(stubProxyConfig.isAdditiveStrategy()).isTrue(); assertThat(stubProxyConfig.getStrategy()).isEqualTo(StubProxyStrategy.ADDITIVE); } @@ -84,12 +99,9 @@ public void stubbedProxyConfigEqualsAssertingConfig_WhenProxyNameNull() throws E public void stubbedProxyConfigEqualsAssertingConfig_WhenProxyConfigDescriptionDifferent() throws Exception { // proxy config description does NOT participate in equality - final StubProxyConfig expectedStubProxyConfig = builder.withUuid("one") - .withDescription("description") - .build(); - final StubProxyConfig assertingStubProxyConfig = builder - .withUuid("one") - .build(); + final StubProxyConfig expectedStubProxyConfig = + builder.withUuid("one").withDescription("description").build(); + final StubProxyConfig assertingStubProxyConfig = builder.withUuid("one").build(); assertThat(assertingStubProxyConfig).isEqualTo(expectedStubProxyConfig); } @@ -106,8 +118,10 @@ public void stubbedProxyConfigNotEqualsAssertingConfig_WhenProxyNamesDifferent() @Test public void stubbedProxyConfigNotEqualsAssertingConfig_WhenProxyPropertiesDifferent() throws Exception { - final StubProxyConfig expectedStubProxyConfig = builder.withProperty("key", "anotherValue").build(); - final StubProxyConfig assertingStubProxyConfig = builder.withProperty("key", "value").build(); + final StubProxyConfig expectedStubProxyConfig = + builder.withProperty("key", "anotherValue").build(); + final StubProxyConfig assertingStubProxyConfig = + builder.withProperty("key", "value").build(); assertThat(assertingStubProxyConfig).isNotEqualTo(expectedStubProxyConfig); } @@ -115,8 +129,7 @@ public void stubbedProxyConfigNotEqualsAssertingConfig_WhenProxyPropertiesDiffer @Test public void stubbedProxyConfigReturnsExpectedEndpointAndDescription() throws Exception { - final StubProxyConfig stubProxyConfig = builder - .withDescription("This is a proxy config for Google") + final StubProxyConfig stubProxyConfig = builder.withDescription("This is a proxy config for Google") .withUuid("unique") .withStrategy("as-is") .withProperty("key", "value") @@ -130,16 +143,14 @@ public void stubbedProxyConfigReturnsExpectedEndpointAndDescription() throws Exc @Test public void stubbedProxyConfigEqualsAssertingConfig() throws Exception { - final StubProxyConfig expectedStubProxyConfig = builder - .withUuid("unique") + final StubProxyConfig expectedStubProxyConfig = builder.withUuid("unique") .withStrategy("as-is") .withHeader("headerKey", "headerValue") .withProperty("key", "value") .withPropertyEndpoint("http://google.com") .build(); - final StubProxyConfig assertingStubProxyConfig = builder - .withUuid("unique") + final StubProxyConfig assertingStubProxyConfig = builder.withUuid("unique") .withStrategy("as-is") .withHeader("headerKey", "headerValue") .withProperty("key", "value") @@ -155,16 +166,14 @@ public void stubbedProxyConfigEqualsAssertingConfig() throws Exception { @Test public void stubbedProxyConfigNotEqualsAssertingConfigWithDifferentHeader() throws Exception { - final StubProxyConfig expectedStubProxyConfig = builder - .withUuid("unique") + final StubProxyConfig expectedStubProxyConfig = builder.withUuid("unique") .withStrategy("as-is") .withHeader("headerKey", "headerValue") .withProperty("key", "value") .withPropertyEndpoint("http://google.com") .build(); - final StubProxyConfig assertingStubProxyConfig = builder - .withUuid("unique") + final StubProxyConfig assertingStubProxyConfig = builder.withUuid("unique") .withStrategy("as-is") .withHeader("headerKey", "headerDifferentValue") .withProperty("key", "value") @@ -183,14 +192,12 @@ public void stubbedProxyConfigNotEqualsAssertingConfigWithDifferentHeader() thro @Test public void stubbedProxyConfigNotEqualsAssertingConfig() throws Exception { - final StubProxyConfig expectedStubProxyConfig = builder - .withUuid("unique") + final StubProxyConfig expectedStubProxyConfig = builder.withUuid("unique") .withStrategy("as-is") .withPropertyEndpoint("http://google.com") .build(); - final StubProxyConfig assertingStubProxyConfig = builder - .withUuid("unique") + final StubProxyConfig assertingStubProxyConfig = builder.withUuid("unique") .withStrategy("additive") .withPropertyEndpoint("http://google.com") .build(); @@ -201,14 +208,12 @@ public void stubbedProxyConfigNotEqualsAssertingConfig() throws Exception { @Test public void stubbedProxyConfigHashCode() throws Exception { - final StubProxyConfig stubProxyConfigOne = builder - .withUuid("unique") + final StubProxyConfig stubProxyConfigOne = builder.withUuid("unique") .withStrategy("as-is") .withPropertyEndpoint("http://google.com") .build(); - final StubProxyConfig stubProxyConfigTwo = builder - .withUuid("unique") + final StubProxyConfig stubProxyConfigTwo = builder.withUuid("unique") .withStrategy("as-is") .withPropertyEndpoint("http://google.com") .build(); @@ -223,23 +228,19 @@ public void stubbedProxyConfigHashCode() throws Exception { @Test public void stubbedProxyConfigAsYaml() throws Exception { - final StubProxyConfig stubProxyConfig = builder - .withUuid("unique") + final StubProxyConfig stubProxyConfig = builder.withUuid("unique") .withStrategy("as-is") .withProperty("key", "value") .withPropertyEndpoint("http://google.com") - .withProxyConfigAsYAML( - "- proxy-config:\n" + - " proxy-strategy: as-is\n" + - " proxy-properties:\n" + - " endpoint: https://jsonplaceholder.typicode.com") + .withProxyConfigAsYAML("- proxy-config:\n" + " proxy-strategy: as-is\n" + + " proxy-properties:\n" + + " endpoint: https://jsonplaceholder.typicode.com") .build(); - assertThat(stubProxyConfig.getProxyConfigAsYAML()).isEqualTo( - "- proxy-config:\n" + - " proxy-strategy: as-is\n" + - " proxy-properties:\n" + - " endpoint: https://jsonplaceholder.typicode.com"); + assertThat(stubProxyConfig.getProxyConfigAsYAML()) + .isEqualTo("- proxy-config:\n" + " proxy-strategy: as-is\n" + + " proxy-properties:\n" + + " endpoint: https://jsonplaceholder.typicode.com"); } @Test diff --git a/src/test/java/io/github/azagniotov/stubby4j/stubs/StubRepositoryTest.java b/src/test/java/io/github/azagniotov/stubby4j/stubs/StubRepositoryTest.java index eb47841d4..b65e3732a 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/stubs/StubRepositoryTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/stubs/StubRepositoryTest.java @@ -1,5 +1,36 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_CONFIG; +import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_REQUEST; +import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_RESPONSE; +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.google.api.client.http.HttpMethods; import io.github.azagniotov.stubby4j.caching.Cache; import io.github.azagniotov.stubby4j.client.StubbyResponse; @@ -8,18 +39,6 @@ import io.github.azagniotov.stubby4j.stubs.proxy.StubProxyConfig; import io.github.azagniotov.stubby4j.yaml.YamlParseResultSet; import io.github.azagniotov.stubby4j.yaml.YamlParser; -import org.eclipse.jetty.http.HttpStatus; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.util.Arrays; @@ -30,22 +49,17 @@ import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.regex.Pattern; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_CONFIG; -import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_REQUEST; -import static io.github.azagniotov.stubby4j.common.Common.HEADER_X_STUBBY_PROXY_RESPONSE; -import static org.junit.Assert.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - +import javax.servlet.http.HttpServletRequest; +import org.eclipse.jetty.http.HttpStatus; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class StubRepositoryTest { @@ -93,7 +107,8 @@ public void beforeEach() throws Exception { requestBuilder = new StubRequest.Builder(); responseBuilder = new StubResponse.Builder(); - final StubRepository stubRepository = new StubRepository(CONFIG_FILE, + final StubRepository stubRepository = new StubRepository( + CONFIG_FILE, Cache.stubHttpLifecycleCache(false), YAML_PARSE_RESULT_SET_FUTURE, mockStubbyHttpTransport); @@ -149,7 +164,10 @@ public void shouldNotMatchHttplifecycle_WhenInvalidIndexGiven() throws Exception public void shouldMatchProxyConfig_WhenUniqueProxyNameGiven() throws Exception { final StubHttpLifecycle httpLifecycle = new StubHttpLifecycle.Builder() .withUUID("uuid") - .withRequest(new StubRequest.Builder().withUrl("/some/uri/path/1").withMethod("GET").build()) + .withRequest(new StubRequest.Builder() + .withUrl("/some/uri/path/1") + .withMethod("GET") + .build()) .withResponse(new StubResponse.Builder().build()) .build(); @@ -164,14 +182,23 @@ public void shouldMatchProxyConfig_WhenUniqueProxyNameGiven() throws Exception { .withPropertyEndpoint("https://jsonplaceholder.typicode.com") .build(); - final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet(new LinkedList() {{ - add(httpLifecycle); - }}, new HashMap() {{ - put(httpLifecycle.getUUID(), httpLifecycle); - }}, new HashMap() {{ - put(stubProxyConfigDefault.getUUID(), stubProxyConfigDefault); - put(stubProxyConfigOther.getUUID(), stubProxyConfigOther); - }}); + final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet( + new LinkedList() { + { + add(httpLifecycle); + } + }, + new HashMap() { + { + put(httpLifecycle.getUUID(), httpLifecycle); + } + }, + new HashMap() { + { + put(stubProxyConfigDefault.getUUID(), stubProxyConfigDefault); + put(stubProxyConfigOther.getUUID(), stubProxyConfigOther); + } + }); spyStubRepository.resetStubsCache(yamlParseResultSet); final boolean resetResult = spyStubRepository.resetStubsCache(yamlParseResultSet); @@ -237,15 +264,21 @@ public void shouldDeleteStubsByUuid() throws Exception { final YamlParseResultSet yamlParseResultSetThree = parseYaml("/resource/item/3", STUB_UUID_THREE); // Setting state for the test - spyStubRepository.resetStubsCache(new YamlParseResultSet(new LinkedList() {{ - addAll(yamlParseResultSetOne.getStubs()); - addAll(yamlParseResultSetTwo.getStubs()); - addAll(yamlParseResultSetThree.getStubs()); - }}, new HashMap() {{ - putAll(yamlParseResultSetOne.getUuidToStubs()); - putAll(yamlParseResultSetTwo.getUuidToStubs()); - putAll(yamlParseResultSetThree.getUuidToStubs()); - }})); + spyStubRepository.resetStubsCache(new YamlParseResultSet( + new LinkedList() { + { + addAll(yamlParseResultSetOne.getStubs()); + addAll(yamlParseResultSetTwo.getStubs()); + addAll(yamlParseResultSetThree.getStubs()); + } + }, + new HashMap() { + { + putAll(yamlParseResultSetOne.getUuidToStubs()); + putAll(yamlParseResultSetTwo.getUuidToStubs()); + putAll(yamlParseResultSetThree.getUuidToStubs()); + } + })); assertThat(spyStubRepository.getStubs().size()).isEqualTo(3); assertThat(spyStubRepository.canMatchStubByUuid(STUB_UUID_ONE)).isTrue(); @@ -263,9 +296,10 @@ public void shouldDeleteStubsByUuid() throws Exception { assertThat(spyStubRepository.canMatchStubByUuid(STUB_UUID_THREE)).isTrue(); // Stubs that left, do not contain deleted URI - assertThat(spyStubRepository.getStubs().get(0).getRequest().getUri().equals("/resource/item/2")).isFalse(); - assertThat(spyStubRepository.getStubs().get(1).getRequest().getUri().equals("/resource/item/2")).isFalse(); - + assertThat(spyStubRepository.getStubs().get(0).getRequest().getUri().equals("/resource/item/2")) + .isFalse(); + assertThat(spyStubRepository.getStubs().get(1).getRequest().getUri().equals("/resource/item/2")) + .isFalse(); /////////////////////////////////////////////////////////////////////////////////////// // The actual test: deleting by third UUID (STUB_UUID_THREE) @@ -278,9 +312,10 @@ public void shouldDeleteStubsByUuid() throws Exception { assertThat(spyStubRepository.canMatchStubByUuid(STUB_UUID_THREE)).isFalse(); // Stubs that left, do not contain deleted URI - assertThat(spyStubRepository.getStubs().get(0).getRequest().getUri().equals("/resource/item/2")).isFalse(); - assertThat(spyStubRepository.getStubs().get(0).getRequest().getUri().equals("/resource/item/3")).isFalse(); - + assertThat(spyStubRepository.getStubs().get(0).getRequest().getUri().equals("/resource/item/2")) + .isFalse(); + assertThat(spyStubRepository.getStubs().get(0).getRequest().getUri().equals("/resource/item/3")) + .isFalse(); /////////////////////////////////////////////////////////////////////////////////////// // The actual test: deleting by first UUID (STUB_UUID_ONE) @@ -297,7 +332,10 @@ public void shouldDeleteStubsByUuid() throws Exception { public void shouldUpdateProxyConfigsByUuid() throws Exception { final StubHttpLifecycle httpLifecycle = new StubHttpLifecycle.Builder() .withUUID("uuid") - .withRequest(new StubRequest.Builder().withUrl("/some/uri/path/1").withMethod("GET").build()) + .withRequest(new StubRequest.Builder() + .withUrl("/some/uri/path/1") + .withMethod("GET") + .build()) .withResponse(new StubResponse.Builder().build()) .build(); @@ -324,16 +362,25 @@ public void shouldUpdateProxyConfigsByUuid() throws Exception { .withPropertyEndpoint("https://jsonplaceholder.typicode.com") .build(); - final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet(new LinkedList() {{ - add(httpLifecycle); - }}, new HashMap() {{ - put(httpLifecycle.getUUID(), httpLifecycle); - }}, new HashMap() {{ - put(stubProxyConfigDefault.getUUID(), stubProxyConfigDefault); - put(stubProxyConfigOne.getUUID(), stubProxyConfigOne); - put(stubProxyConfigTwo.getUUID(), stubProxyConfigTwo); - put(stubProxyConfigThree.getUUID(), stubProxyConfigThree); - }}); + final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet( + new LinkedList() { + { + add(httpLifecycle); + } + }, + new HashMap() { + { + put(httpLifecycle.getUUID(), httpLifecycle); + } + }, + new HashMap() { + { + put(stubProxyConfigDefault.getUUID(), stubProxyConfigDefault); + put(stubProxyConfigOne.getUUID(), stubProxyConfigOne); + put(stubProxyConfigTwo.getUUID(), stubProxyConfigTwo); + put(stubProxyConfigThree.getUUID(), stubProxyConfigThree); + } + }); spyStubRepository.resetStubsCache(yamlParseResultSet); final boolean resetResult = spyStubRepository.resetStubsCache(yamlParseResultSet); @@ -361,7 +408,12 @@ public void shouldUpdateProxyConfigsByUuid() throws Exception { assertThat(spyStubRepository.canMatchProxyConfigByUuid(STUB_UUID_TWO)).isTrue(); assertThat(spyStubRepository.canMatchProxyConfigByUuid(STUB_UUID_THREE)).isTrue(); - assertThat(spyStubRepository.getProxyConfigs().get(STUB_UUID_TWO).getPropertyEndpoint().equals("http://google.com")).isTrue(); + assertThat(spyStubRepository + .getProxyConfigs() + .get(STUB_UUID_TWO) + .getPropertyEndpoint() + .equals("http://google.com")) + .isTrue(); /////////////////////////////////////////////////////////////////////////////////////// // The actual test: update by third UUID (STUB_UUID_THREE) @@ -379,8 +431,12 @@ public void shouldUpdateProxyConfigsByUuid() throws Exception { assertThat(spyStubRepository.canMatchProxyConfigByUuid(STUB_UUID_TWO)).isTrue(); assertThat(spyStubRepository.canMatchProxyConfigByUuid(STUB_UUID_THREE)).isTrue(); - assertThat(spyStubRepository.getProxyConfigs().get(STUB_UUID_THREE).getPropertyEndpoint().equals("http://yahoo.com")).isTrue(); - + assertThat(spyStubRepository + .getProxyConfigs() + .get(STUB_UUID_THREE) + .getPropertyEndpoint() + .equals("http://yahoo.com")) + .isTrue(); /////////////////////////////////////////////////////////////////////////////////////// // The actual test: update by third UUID (STUB_UUID_ONE) @@ -398,8 +454,12 @@ public void shouldUpdateProxyConfigsByUuid() throws Exception { assertThat(spyStubRepository.canMatchProxyConfigByUuid(STUB_UUID_TWO)).isTrue(); assertThat(spyStubRepository.canMatchProxyConfigByUuid(STUB_UUID_THREE)).isTrue(); - assertThat(spyStubRepository.getProxyConfigs().get(STUB_UUID_ONE).getPropertyEndpoint().equals("http://mail.com")).isTrue(); - + assertThat(spyStubRepository + .getProxyConfigs() + .get(STUB_UUID_ONE) + .getPropertyEndpoint() + .equals("http://mail.com")) + .isTrue(); /////////////////////////////////////////////////////////////////////////////////////// // The actual test: update by 'default' UUID @@ -417,14 +477,22 @@ public void shouldUpdateProxyConfigsByUuid() throws Exception { assertThat(spyStubRepository.canMatchProxyConfigByUuid(STUB_UUID_TWO)).isTrue(); assertThat(spyStubRepository.canMatchProxyConfigByUuid(STUB_UUID_THREE)).isTrue(); - assertThat(spyStubRepository.getProxyConfigs().get("default").getPropertyEndpoint().equals("http://rambler.ru")).isTrue(); + assertThat(spyStubRepository + .getProxyConfigs() + .get("default") + .getPropertyEndpoint() + .equals("http://rambler.ru")) + .isTrue(); } @Test public void shouldFailUpdatingProxyConfigByUuidWhenUuidDoNotMatch() throws Exception { final StubHttpLifecycle httpLifecycle = new StubHttpLifecycle.Builder() .withUUID("uuid") - .withRequest(new StubRequest.Builder().withUrl("/some/uri/path/1").withMethod("GET").build()) + .withRequest(new StubRequest.Builder() + .withUrl("/some/uri/path/1") + .withMethod("GET") + .build()) .withResponse(new StubResponse.Builder().build()) .build(); @@ -433,13 +501,22 @@ public void shouldFailUpdatingProxyConfigByUuidWhenUuidDoNotMatch() throws Excep .withPropertyEndpoint("https://jsonplaceholder.typicode.com") .build(); - final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet(new LinkedList() {{ - add(httpLifecycle); - }}, new HashMap() {{ - put(httpLifecycle.getUUID(), httpLifecycle); - }}, new HashMap() {{ - put(stubProxyConfigDefault.getUUID(), stubProxyConfigDefault); - }}); + final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet( + new LinkedList() { + { + add(httpLifecycle); + } + }, + new HashMap() { + { + put(httpLifecycle.getUUID(), httpLifecycle); + } + }, + new HashMap() { + { + put(stubProxyConfigDefault.getUUID(), stubProxyConfigDefault); + } + }); spyStubRepository.resetStubsCache(yamlParseResultSet); final boolean resetResult = spyStubRepository.resetStubsCache(yamlParseResultSet); @@ -460,7 +537,8 @@ public void shouldFailUpdatingProxyConfigByUuidWhenUuidDoNotMatch() throws Excep spyStubRepository.updateProxyConfigByUuid("totally-different-uuid", newStubProxyConfigDefault); }); - String expectedMessage = "Provided proxy config UUID 'default' does not match the target UUID 'totally-different-uuid'"; + String expectedMessage = + "Provided proxy config UUID 'default' does not match the target UUID 'totally-different-uuid'"; String actualMessage = exception.getMessage(); assertThat(actualMessage).isEqualTo(expectedMessage); @@ -470,7 +548,10 @@ public void shouldFailUpdatingProxyConfigByUuidWhenUuidDoNotMatch() throws Excep public void shouldDeleteProxyConfigsByUuid() throws Exception { final StubHttpLifecycle httpLifecycle = new StubHttpLifecycle.Builder() .withUUID("uuid") - .withRequest(new StubRequest.Builder().withUrl("/some/uri/path/1").withMethod("GET").build()) + .withRequest(new StubRequest.Builder() + .withUrl("/some/uri/path/1") + .withMethod("GET") + .build()) .withResponse(new StubResponse.Builder().build()) .build(); @@ -497,16 +578,25 @@ public void shouldDeleteProxyConfigsByUuid() throws Exception { .withPropertyEndpoint("https://jsonplaceholder.typicode.com") .build(); - final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet(new LinkedList() {{ - add(httpLifecycle); - }}, new HashMap() {{ - put(httpLifecycle.getUUID(), httpLifecycle); - }}, new HashMap() {{ - put(stubProxyConfigDefault.getUUID(), stubProxyConfigDefault); - put(stubProxyConfigOne.getUUID(), stubProxyConfigOne); - put(stubProxyConfigTwo.getUUID(), stubProxyConfigTwo); - put(stubProxyConfigThree.getUUID(), stubProxyConfigThree); - }}); + final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet( + new LinkedList() { + { + add(httpLifecycle); + } + }, + new HashMap() { + { + put(httpLifecycle.getUUID(), httpLifecycle); + } + }, + new HashMap() { + { + put(stubProxyConfigDefault.getUUID(), stubProxyConfigDefault); + put(stubProxyConfigOne.getUUID(), stubProxyConfigOne); + put(stubProxyConfigTwo.getUUID(), stubProxyConfigTwo); + put(stubProxyConfigThree.getUUID(), stubProxyConfigThree); + } + }); spyStubRepository.resetStubsCache(yamlParseResultSet); final boolean resetResult = spyStubRepository.resetStubsCache(yamlParseResultSet); @@ -559,7 +649,10 @@ public void shouldDeleteProxyConfigsByUuid() throws Exception { public void shouldFailDeletingDefaultProxyConfigByUuid() throws Exception { final StubHttpLifecycle httpLifecycle = new StubHttpLifecycle.Builder() .withUUID("uuid") - .withRequest(new StubRequest.Builder().withUrl("/some/uri/path/1").withMethod("GET").build()) + .withRequest(new StubRequest.Builder() + .withUrl("/some/uri/path/1") + .withMethod("GET") + .build()) .withResponse(new StubResponse.Builder().build()) .build(); @@ -568,13 +661,22 @@ public void shouldFailDeletingDefaultProxyConfigByUuid() throws Exception { .withPropertyEndpoint("https://jsonplaceholder.typicode.com") .build(); - final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet(new LinkedList() {{ - add(httpLifecycle); - }}, new HashMap() {{ - put(httpLifecycle.getUUID(), httpLifecycle); - }}, new HashMap() {{ - put(stubProxyConfigDefault.getUUID(), stubProxyConfigDefault); - }}); + final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet( + new LinkedList() { + { + add(httpLifecycle); + } + }, + new HashMap() { + { + put(httpLifecycle.getUUID(), httpLifecycle); + } + }, + new HashMap() { + { + put(stubProxyConfigDefault.getUUID(), stubProxyConfigDefault); + } + }); spyStubRepository.resetStubsCache(yamlParseResultSet); final boolean resetResult = spyStubRepository.resetStubsCache(yamlParseResultSet); @@ -603,15 +705,21 @@ public void shouldUpdateStubsByUuid() throws Exception { final YamlParseResultSet yamlParseResultSetThree = parseYaml("/resource/item/3", STUB_UUID_THREE); // Setting state for the test - spyStubRepository.resetStubsCache(new YamlParseResultSet(new LinkedList() {{ - addAll(yamlParseResultSetOne.getStubs()); - addAll(yamlParseResultSetTwo.getStubs()); - addAll(yamlParseResultSetThree.getStubs()); - }}, new HashMap() {{ - putAll(yamlParseResultSetOne.getUuidToStubs()); - putAll(yamlParseResultSetTwo.getUuidToStubs()); - putAll(yamlParseResultSetThree.getUuidToStubs()); - }})); + spyStubRepository.resetStubsCache(new YamlParseResultSet( + new LinkedList() { + { + addAll(yamlParseResultSetOne.getStubs()); + addAll(yamlParseResultSetTwo.getStubs()); + addAll(yamlParseResultSetThree.getStubs()); + } + }, + new HashMap() { + { + putAll(yamlParseResultSetOne.getUuidToStubs()); + putAll(yamlParseResultSetTwo.getUuidToStubs()); + putAll(yamlParseResultSetThree.getUuidToStubs()); + } + })); assertThat(spyStubRepository.getStubs().size()).isEqualTo(3); assertThat(spyStubRepository.canMatchStubByUuid(STUB_UUID_ONE)).isTrue(); @@ -625,57 +733,75 @@ public void shouldUpdateStubsByUuid() throws Exception { /////////////////////////////////////////////////////////////////////////////////////// // The actual test: update by second UUID (STUB_UUID_TWO) /////////////////////////////////////////////////////////////////////////////////////// - spyStubRepository.updateStubByUuid(STUB_UUID_TWO, - parseYaml("/resource/completely/new/item/2", STUB_UUID_TWO).getStubs().get(0)); + spyStubRepository.updateStubByUuid( + STUB_UUID_TWO, + parseYaml("/resource/completely/new/item/2", STUB_UUID_TWO) + .getStubs() + .get(0)); assertThat(spyStubRepository.getStubs().size()).isEqualTo(3); assertThat(spyStubRepository.canMatchStubByUuid(STUB_UUID_ONE)).isTrue(); assertThat(spyStubRepository.canMatchStubByUuid(STUB_UUID_TWO)).isTrue(); assertThat(spyStubRepository.canMatchStubByUuid(STUB_UUID_THREE)).isTrue(); - assertThat(spyStubRepository.getStubs().get(0).getRequest().getUri().equals("/resource/item/1")).isTrue(); - assertThat(spyStubRepository.getStubs().get(1).getRequest().getUri().equals("/resource/completely/new/item/2")).isTrue(); - assertThat(spyStubRepository.getStubs().get(2).getRequest().getUri().equals("/resource/item/3")).isTrue(); - + assertThat(spyStubRepository.getStubs().get(0).getRequest().getUri().equals("/resource/item/1")) + .isTrue(); + assertThat(spyStubRepository.getStubs().get(1).getRequest().getUri().equals("/resource/completely/new/item/2")) + .isTrue(); + assertThat(spyStubRepository.getStubs().get(2).getRequest().getUri().equals("/resource/item/3")) + .isTrue(); /////////////////////////////////////////////////////////////////////////////////////// // The actual test: update by third UUID (STUB_UUID_THREE) /////////////////////////////////////////////////////////////////////////////////////// - spyStubRepository.updateStubByUuid(STUB_UUID_THREE, - parseYaml("/resource/completely/new/item/3", STUB_UUID_THREE).getStubs().get(0)); + spyStubRepository.updateStubByUuid( + STUB_UUID_THREE, + parseYaml("/resource/completely/new/item/3", STUB_UUID_THREE) + .getStubs() + .get(0)); assertThat(spyStubRepository.getStubs().size()).isEqualTo(3); assertThat(spyStubRepository.canMatchStubByUuid(STUB_UUID_ONE)).isTrue(); assertThat(spyStubRepository.canMatchStubByUuid(STUB_UUID_TWO)).isTrue(); assertThat(spyStubRepository.canMatchStubByUuid(STUB_UUID_THREE)).isTrue(); - assertThat(spyStubRepository.getStubs().get(0).getRequest().getUri().equals("/resource/item/1")).isTrue(); - assertThat(spyStubRepository.getStubs().get(1).getRequest().getUri().equals("/resource/completely/new/item/2")).isTrue(); - assertThat(spyStubRepository.getStubs().get(2).getRequest().getUri().equals("/resource/completely/new/item/3")).isTrue(); - + assertThat(spyStubRepository.getStubs().get(0).getRequest().getUri().equals("/resource/item/1")) + .isTrue(); + assertThat(spyStubRepository.getStubs().get(1).getRequest().getUri().equals("/resource/completely/new/item/2")) + .isTrue(); + assertThat(spyStubRepository.getStubs().get(2).getRequest().getUri().equals("/resource/completely/new/item/3")) + .isTrue(); /////////////////////////////////////////////////////////////////////////////////////// // The actual test: update by third UUID (STUB_UUID_ONE) /////////////////////////////////////////////////////////////////////////////////////// - spyStubRepository.updateStubByUuid(STUB_UUID_ONE, - parseYaml("/resource/completely/new/item/1", STUB_UUID_ONE).getStubs().get(0)); + spyStubRepository.updateStubByUuid( + STUB_UUID_ONE, + parseYaml("/resource/completely/new/item/1", STUB_UUID_ONE) + .getStubs() + .get(0)); assertThat(spyStubRepository.getStubs().size()).isEqualTo(3); assertThat(spyStubRepository.canMatchStubByUuid(STUB_UUID_ONE)).isTrue(); assertThat(spyStubRepository.canMatchStubByUuid(STUB_UUID_TWO)).isTrue(); assertThat(spyStubRepository.canMatchStubByUuid(STUB_UUID_THREE)).isTrue(); - assertThat(spyStubRepository.getStubs().get(0).getRequest().getUri().equals("/resource/completely/new/item/1")).isTrue(); - assertThat(spyStubRepository.getStubs().get(1).getRequest().getUri().equals("/resource/completely/new/item/2")).isTrue(); - assertThat(spyStubRepository.getStubs().get(2).getRequest().getUri().equals("/resource/completely/new/item/3")).isTrue(); - + assertThat(spyStubRepository.getStubs().get(0).getRequest().getUri().equals("/resource/completely/new/item/1")) + .isTrue(); + assertThat(spyStubRepository.getStubs().get(1).getRequest().getUri().equals("/resource/completely/new/item/2")) + .isTrue(); + assertThat(spyStubRepository.getStubs().get(2).getRequest().getUri().equals("/resource/completely/new/item/3")) + .isTrue(); /////////////////////////////////////////////////////////////////////////////////////// // The actual test: update by second UUID (STUB_UUID_TWO) & override with a new UUID /////////////////////////////////////////////////////////////////////////////////////// final String newUuid = "new-uuid-abc-123"; - spyStubRepository.updateStubByUuid(STUB_UUID_TWO, - parseYaml("/resource/completely/new/item/with/new/uuid/2", newUuid).getStubs().get(0)); + spyStubRepository.updateStubByUuid( + STUB_UUID_TWO, + parseYaml("/resource/completely/new/item/with/new/uuid/2", newUuid) + .getStubs() + .get(0)); assertThat(spyStubRepository.getStubs().size()).isEqualTo(3); assertThat(spyStubRepository.canMatchStubByUuid(STUB_UUID_ONE)).isTrue(); @@ -683,10 +809,19 @@ public void shouldUpdateStubsByUuid() throws Exception { assertThat(spyStubRepository.canMatchStubByUuid(STUB_UUID_THREE)).isTrue(); assertThat(spyStubRepository.canMatchStubByUuid(newUuid)).isTrue(); - assertThat(spyStubRepository.getStubs().get(0).getRequest().getUri().equals("/resource/completely/new/item/1")).isTrue(); - assertThat(spyStubRepository.getStubs().get(1).getRequest().getUri().equals("/resource/completely/new/item/with/new/uuid/2")).isTrue(); - assertThat(spyStubRepository.getStubs().get(1).getUUID().equals(newUuid)).isTrue(); - assertThat(spyStubRepository.getStubs().get(2).getRequest().getUri().equals("/resource/completely/new/item/3")).isTrue(); + assertThat(spyStubRepository.getStubs().get(0).getRequest().getUri().equals("/resource/completely/new/item/1")) + .isTrue(); + assertThat(spyStubRepository + .getStubs() + .get(1) + .getRequest() + .getUri() + .equals("/resource/completely/new/item/with/new/uuid/2")) + .isTrue(); + assertThat(spyStubRepository.getStubs().get(1).getUUID().equals(newUuid)) + .isTrue(); + assertThat(spyStubRepository.getStubs().get(2).getRequest().getUri().equals("/resource/completely/new/item/3")) + .isTrue(); } @Test @@ -738,9 +873,11 @@ public void shouldUpdateStubHttpLifecycleByIndex_WhenValidHttpCycleListIndexGive final String expectedNewUrl = "/resource/completely/new"; final YamlParseResultSet newYamlParseResultSet = parseYaml(expectedNewUrl, STUB_UUID_TWO); - final StubHttpLifecycle newStubHttpLifecycle = newYamlParseResultSet.getStubs().get(0); + final StubHttpLifecycle newStubHttpLifecycle = + newYamlParseResultSet.getStubs().get(0); spyStubRepository.updateStubByIndex(0, newStubHttpLifecycle); - final StubRequest stubbedNewRequest = spyStubRepository.getStubs().get(0).getRequest(); + final StubRequest stubbedNewRequest = + spyStubRepository.getStubs().get(0).getRequest(); assertThat(stubbedNewRequest.getUrl()).isEqualTo(expectedNewUrl); assertThat(spyStubRepository.canMatchStubByUuid(STUB_UUID_ONE)).isFalse(); @@ -761,7 +898,8 @@ public void shouldUpdateStubHttpLifecycleByIndex_WhenInvalidHttpCycleListIndexGi final String expectedNewUrl = "/resource/completely/new"; final YamlParseResultSet newYamlParseResultSet = parseYaml(expectedNewUrl, STUB_UUID_ONE); - final StubHttpLifecycle newStubHttpLifecycle = newYamlParseResultSet.getStubs().get(0); + final StubHttpLifecycle newStubHttpLifecycle = + newYamlParseResultSet.getStubs().get(0); spyStubRepository.updateStubByIndex(10, newStubHttpLifecycle); } @@ -769,7 +907,10 @@ public void shouldUpdateStubHttpLifecycleByIndex_WhenInvalidHttpCycleListIndexGi public void shouldUpdateStubResponseBody_WhenResponseIsRecordable() throws Exception { final String sourceToRecord = "http://google.com"; final String expectedOriginalUrl = "/resource/item/1"; - final YamlParseResultSet yamlParseResultSet = parseYaml(expectedOriginalUrl, responseBuilder.emptyWithBody(sourceToRecord).build(), STUB_UUID_ONE); + final YamlParseResultSet yamlParseResultSet = parseYaml( + expectedOriginalUrl, + responseBuilder.emptyWithBody(sourceToRecord).build(), + STUB_UUID_ONE); spyStubRepository.resetStubsCache(yamlParseResultSet); @@ -779,7 +920,8 @@ public void shouldUpdateStubResponseBody_WhenResponseIsRecordable() throws Excep final String actualResponseText = "OK, this is recorded response text!"; final StubRequest stubbedRequest = spyStubRepository.getStubs().get(0).getRequest(); - when(mockStubbyHttpTransport.httpRequestFromStub(eq(stubbedRequest), anyString())).thenReturn(new StubbyResponse(200, actualResponseText, new HashMap<>())); + when(mockStubbyHttpTransport.httpRequestFromStub(eq(stubbedRequest), anyString())) + .thenReturn(new StubbyResponse(200, actualResponseText, new HashMap<>())); final List stubs = yamlParseResultSet.getStubs(); for (int idx = 0; idx < 5; idx++) { @@ -797,14 +939,17 @@ public void shouldUpdateStubResponseBody_WhenResponseIsRecordable() throws Excep @Test public void shouldNotUpdateStubResponseBody_WhenResponseIsNotRecordable() throws Exception { - final String recordingSource = "htt://google.com"; //makes it non recordable + final String recordingSource = "htt://google.com"; // makes it non recordable final String expectedOriginalUrl = "/resource/item/1"; - final YamlParseResultSet yamlParseResultSet = parseYaml(expectedOriginalUrl, - responseBuilder.emptyWithBody(recordingSource).build(), STUB_UUID_ONE); + final YamlParseResultSet yamlParseResultSet = parseYaml( + expectedOriginalUrl, + responseBuilder.emptyWithBody(recordingSource).build(), + STUB_UUID_ONE); spyStubRepository.resetStubsCache(yamlParseResultSet); - final StubResponse expectedResponse = spyStubRepository.getStubs().get(0).getResponse(true); + final StubResponse expectedResponse = + spyStubRepository.getStubs().get(0).getResponse(true); assertThat(expectedResponse.getBody()).isEqualTo(recordingSource); final List stubs = yamlParseResultSet.getStubs(); @@ -819,30 +964,29 @@ public void shouldNotUpdateStubResponseBody_WhenResponseIsNotRecordable() throws @Test public void shouldRecordingUsingIncomingRequestQueryStringAndStubbedRecordableUrl() throws Exception { final String sourceToRecord = "http://127.0.0.1:8888"; - final StubRequest stubbedRequest = - requestBuilder - .withUrl("/search") - .withMethodGet() - .withHeader("content-type", Common.HEADER_APPLICATION_JSON) - .withQuery("queryOne", "([a-zA-Z]+)") - .withQuery("queryTwo", "([1-9]+)") - .build(); - final YamlParseResultSet yamlParseResultSet = parseYaml(stubbedRequest, - responseBuilder.emptyWithBody(sourceToRecord).build(), STUB_UUID_ONE); + final StubRequest stubbedRequest = requestBuilder + .withUrl("/search") + .withMethodGet() + .withHeader("content-type", Common.HEADER_APPLICATION_JSON) + .withQuery("queryOne", "([a-zA-Z]+)") + .withQuery("queryTwo", "([1-9]+)") + .build(); + final YamlParseResultSet yamlParseResultSet = parseYaml( + stubbedRequest, responseBuilder.emptyWithBody(sourceToRecord).build(), STUB_UUID_ONE); spyStubRepository.resetStubsCache(yamlParseResultSet); final String actualResponseText = "OK, this is recorded response text!"; - when(mockStubbyHttpTransport.httpRequestFromStub(eq(stubbedRequest), stringCaptor.capture())).thenReturn(new StubbyResponse(200, actualResponseText, new HashMap<>())); - - final StubRequest incomingRequest = - requestBuilder - .withUrl("/search") - .withMethodGet() - .withHeader("content-type", Common.HEADER_APPLICATION_JSON) - .withQuery("queryTwo", "12345") - .withQuery("queryOne", "arbitraryValue") - .build(); + when(mockStubbyHttpTransport.httpRequestFromStub(eq(stubbedRequest), stringCaptor.capture())) + .thenReturn(new StubbyResponse(200, actualResponseText, new HashMap<>())); + + final StubRequest incomingRequest = requestBuilder + .withUrl("/search") + .withMethodGet() + .withHeader("content-type", Common.HEADER_APPLICATION_JSON) + .withQuery("queryTwo", "12345") + .withQuery("queryOne", "arbitraryValue") + .build(); doReturn(incomingRequest).when(spyStubRepository).toStubRequest(any(HttpServletRequest.class)); final StubSearchResult stubSearchResult = spyStubRepository.search(mockHttpServletRequest); @@ -856,16 +1000,20 @@ public void shouldRecordingUsingIncomingRequestQueryStringAndStubbedRecordableUr public void shouldNotUpdateStubResponseBody_WhenResponseIsRecordableButExceptionThrown() throws Exception { final String recordingSource = "http://google.com"; final String expectedOriginalUrl = "/resource/item/1"; - final YamlParseResultSet yamlParseResultSet = parseYaml(expectedOriginalUrl, - responseBuilder.emptyWithBody(recordingSource).build(), STUB_UUID_ONE); + final YamlParseResultSet yamlParseResultSet = parseYaml( + expectedOriginalUrl, + responseBuilder.emptyWithBody(recordingSource).build(), + STUB_UUID_ONE); spyStubRepository.resetStubsCache(yamlParseResultSet); - final StubResponse expectedResponse = spyStubRepository.getStubs().get(0).getResponse(true); + final StubResponse expectedResponse = + spyStubRepository.getStubs().get(0).getResponse(true); assertThat(expectedResponse.getBody()).isEqualTo(recordingSource); final StubRequest matchedRequest = spyStubRepository.getStubs().get(0).getRequest(); - when(mockStubbyHttpTransport.httpRequestFromStub(eq(matchedRequest), anyString())).thenThrow(IOException.class); + when(mockStubbyHttpTransport.httpRequestFromStub(eq(matchedRequest), anyString())) + .thenThrow(IOException.class); final List stubs = yamlParseResultSet.getStubs(); doReturn(stubs.get(0).getRequest()).when(spyStubRepository).toStubRequest(any(HttpServletRequest.class)); @@ -877,18 +1025,20 @@ public void shouldNotUpdateStubResponseBody_WhenResponseIsRecordableButException } @Test - public void stubbedRequestEqualsAssertingRequest_WhenQueryParamArrayHasElementsWithinUrlEncodedQuotes() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenQueryParamArrayHasElementsWithinUrlEncodedQuotes() + throws Exception { final String paramOne = "names"; final String paramOneValue = "[\"cheburashka\",\"wendy\"]"; final String url = "/invoice/789"; - final StubRequest expectedRequest = - requestBuilder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue).build(); + final StubRequest expectedRequest = requestBuilder + .withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .build(); when(mockHttpServletRequest.getPathInfo()).thenReturn(url); when(mockHttpServletRequest.getMethod()).thenReturn(HttpMethods.GET); @@ -900,18 +1050,20 @@ public void stubbedRequestEqualsAssertingRequest_WhenQueryParamArrayHasElementsW } @Test - public void stubbedRequestEqualsAssertingRequest_WhenQueryParamUrlEncodedArrayHasElementsWithinUrlEncodedQuotes() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenQueryParamUrlEncodedArrayHasElementsWithinUrlEncodedQuotes() + throws Exception { final String paramOne = "names"; final String paramOneValue = "[\"cheburashka\",\"wendy\"]"; final String url = "/invoice/789"; - final StubRequest expectedRequest = - requestBuilder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue).build(); + final StubRequest expectedRequest = requestBuilder + .withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .build(); when(mockHttpServletRequest.getPathInfo()).thenReturn(url); when(mockHttpServletRequest.getMethod()).thenReturn(HttpMethods.GET); @@ -923,19 +1075,21 @@ public void stubbedRequestEqualsAssertingRequest_WhenQueryParamUrlEncodedArrayHa } @Test - public void stubbedRequestEqualsAssertingRequest_WhenQueryParamUrlEncodedArrayHasElementsWithinUrlEncodedSingleQuotes() throws Exception { + public void + stubbedRequestEqualsAssertingRequest_WhenQueryParamUrlEncodedArrayHasElementsWithinUrlEncodedSingleQuotes() + throws Exception { final String paramOne = "names"; final String paramOneValue = "['cheburashka','wendy']"; final String url = "/invoice/789"; - final StubRequest expectedRequest = - requestBuilder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue).build(); - + final StubRequest expectedRequest = requestBuilder + .withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .build(); when(mockHttpServletRequest.getPathInfo()).thenReturn(url); when(mockHttpServletRequest.getMethod()).thenReturn(HttpMethods.GET); @@ -955,11 +1109,11 @@ public void stubbedRequestEqualsAssertingRequest_WhenQueryValuesHaveEncodedSingl final String url = "/invoice/789"; - final StubRequest expectedRequest = - requestBuilder.withUrl(url) - .withMethodGet() - .withQuery(paramOne, paramOneValue).build(); - + final StubRequest expectedRequest = requestBuilder + .withUrl(url) + .withMethodGet() + .withQuery(paramOne, paramOneValue) + .build(); when(mockHttpServletRequest.getPathInfo()).thenReturn(url); when(mockHttpServletRequest.getMethod()).thenReturn(HttpMethods.GET); @@ -979,11 +1133,11 @@ public void stubbedRequestEqualsAssertingRequest_WhenQueryValuesHaveMultipleRawP final String url = "/invoice/789"; - final StubRequest expectedRequest = - requestBuilder.withUrl(url) - .withMethodGet() - .withQuery(paramOne, paramOneValue).build(); - + final StubRequest expectedRequest = requestBuilder + .withUrl(url) + .withMethodGet() + .withQuery(paramOne, paramOneValue) + .build(); when(mockHttpServletRequest.getPathInfo()).thenReturn(url); when(mockHttpServletRequest.getMethod()).thenReturn(HttpMethods.GET); @@ -1003,11 +1157,11 @@ public void stubbedRequestEqualsAssertingRequest_WhenQueryValuesHaveEncodedMulti final String url = "/invoice/789"; - final StubRequest expectedRequest = - requestBuilder.withUrl(url) - .withMethodGet() - .withQuery(paramOne, paramOneValue).build(); - + final StubRequest expectedRequest = requestBuilder + .withUrl(url) + .withMethodGet() + .withQuery(paramOne, paramOneValue) + .build(); when(mockHttpServletRequest.getPathInfo()).thenReturn(url); when(mockHttpServletRequest.getMethod()).thenReturn(HttpMethods.GET); @@ -1019,7 +1173,9 @@ public void stubbedRequestEqualsAssertingRequest_WhenQueryValuesHaveEncodedMulti } @Test - public void stubbedRequestEqualsAssertingRequest_WhenQueryValues_HasArrayElementsWithEncodedSpacesWithinUrlEncodedSingleQuotes() throws Exception { + public void + stubbedRequestEqualsAssertingRequest_WhenQueryValues_HasArrayElementsWithEncodedSpacesWithinUrlEncodedSingleQuotes() + throws Exception { final String paramOne = "names"; final String paramOneValue = "['stalin and truman','are best friends']"; @@ -1031,12 +1187,12 @@ public void stubbedRequestEqualsAssertingRequest_WhenQueryValues_HasArrayElement final String url = "/invoice/789"; - final StubRequest expectedRequest = - requestBuilder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue).build(); - + final StubRequest expectedRequest = requestBuilder + .withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .build(); when(mockHttpServletRequest.getPathInfo()).thenReturn(url); when(mockHttpServletRequest.getMethod()).thenReturn(HttpMethods.GET); @@ -1048,7 +1204,9 @@ public void stubbedRequestEqualsAssertingRequest_WhenQueryValues_HasArrayElement } @Test - public void stubbedRequestEqualsAssertingRequest_WhenQueryValues_HasArrayElementsWithEncodedPlusWithinUrlEncodedSingleQuotes() throws Exception { + public void + stubbedRequestEqualsAssertingRequest_WhenQueryValues_HasArrayElementsWithEncodedPlusWithinUrlEncodedSingleQuotes() + throws Exception { final String paramOne = "names"; final String paramOneValue = "['stalin and truman','are best friends']"; @@ -1060,12 +1218,12 @@ public void stubbedRequestEqualsAssertingRequest_WhenQueryValues_HasArrayElement final String url = "/invoice/789"; - final StubRequest expectedRequest = - requestBuilder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue).build(); - + final StubRequest expectedRequest = requestBuilder + .withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .build(); when(mockHttpServletRequest.getPathInfo()).thenReturn(url); when(mockHttpServletRequest.getMethod()).thenReturn(HttpMethods.GET); @@ -1081,7 +1239,10 @@ public void shouldApplyDefaultProxyConfigToHttpTransport_WhenResponseIsProxiable final StubHttpLifecycle httpLifecycle = new StubHttpLifecycle.Builder() .withUUID("uuid") - .withRequest(new StubRequest.Builder().withUrl("/some/uri/path/1").withMethod("GET").build()) + .withRequest(new StubRequest.Builder() + .withUrl("/some/uri/path/1") + .withMethod("GET") + .build()) .withResponse(new StubResponse.Builder().build()) .build(); @@ -1090,13 +1251,22 @@ public void shouldApplyDefaultProxyConfigToHttpTransport_WhenResponseIsProxiable .withPropertyEndpoint("https://jsonplaceholder.typicode.com") .build(); - final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet(new LinkedList() {{ - add(httpLifecycle); - }}, new HashMap() {{ - put(httpLifecycle.getUUID(), httpLifecycle); - }}, new HashMap() {{ - put(stubProxyConfig.getUUID(), stubProxyConfig); - }}); + final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet( + new LinkedList() { + { + add(httpLifecycle); + } + }, + new HashMap() { + { + put(httpLifecycle.getUUID(), httpLifecycle); + } + }, + new HashMap() { + { + put(stubProxyConfig.getUUID(), stubProxyConfig); + } + }); spyStubRepository.resetStubsCache(yamlParseResultSet); @@ -1107,14 +1277,14 @@ public void shouldApplyDefaultProxyConfigToHttpTransport_WhenResponseIsProxiable httpProxyResponseHeaders.put("Expires", Collections.singletonList("12345")); httpProxyResponseHeaders.put("SomeHeader", Arrays.asList("one", "two")); - when(mockStubbyHttpTransport.httpRequestFromStub(any(StubRequest.class), anyString())).thenReturn(new StubbyResponse(201, actualResponseText, httpProxyResponseHeaders)); + when(mockStubbyHttpTransport.httpRequestFromStub(any(StubRequest.class), anyString())) + .thenReturn(new StubbyResponse(201, actualResponseText, httpProxyResponseHeaders)); - final StubRequest incomingRequest = - requestBuilder - .withUrl("/post/1") - .withMethodGet() - .withHeader("content-type", Common.HEADER_APPLICATION_JSON) - .build(); + final StubRequest incomingRequest = requestBuilder + .withUrl("/post/1") + .withMethodGet() + .withHeader("content-type", Common.HEADER_APPLICATION_JSON) + .build(); doReturn(incomingRequest).when(spyStubRepository).toStubRequest(any(HttpServletRequest.class)); final StubSearchResult stubSearchResult = spyStubRepository.search(mockHttpServletRequest); @@ -1129,21 +1299,29 @@ public void shouldApplyDefaultProxyConfigToHttpTransport_WhenResponseIsProxiable assertThat(proxiedResponse.getHeaders().get("Expires")).isEqualTo("12345"); assertThat(proxiedResponse.getHeaders().get("SomeHeader")).isEqualTo("[one, two]"); - verify(mockStubbyHttpTransport, times(1)).httpRequestFromStub(stubRequestCaptor.capture(), stringCaptor.capture()); + verify(mockStubbyHttpTransport, times(1)) + .httpRequestFromStub(stubRequestCaptor.capture(), stringCaptor.capture()); assertThat(stringCaptor.getValue()).isEqualTo("https://jsonplaceholder.typicode.com/post/1"); - assertThat(stubRequestCaptor.getValue().getHeaders().containsKey(HEADER_X_STUBBY_PROXY_REQUEST)).isTrue(); + assertThat(stubRequestCaptor.getValue().getHeaders().containsKey(HEADER_X_STUBBY_PROXY_REQUEST)) + .isTrue(); - final String proxyRequestUuid = stubRequestCaptor.getValue().getHeaders().get(HEADER_X_STUBBY_PROXY_REQUEST); - assertThat(proxiedResponse.getHeaders().get(HEADER_X_STUBBY_PROXY_RESPONSE)).isEqualTo(proxyRequestUuid); + final String proxyRequestUuid = + stubRequestCaptor.getValue().getHeaders().get(HEADER_X_STUBBY_PROXY_REQUEST); + assertThat(proxiedResponse.getHeaders().get(HEADER_X_STUBBY_PROXY_RESPONSE)) + .isEqualTo(proxyRequestUuid); } @Test - public void shouldApplyProxyConfigAdditiveStrategyHeadersToHttpTransport_WhenResponseIsProxiable() throws Exception { + public void shouldApplyProxyConfigAdditiveStrategyHeadersToHttpTransport_WhenResponseIsProxiable() + throws Exception { final StubHttpLifecycle httpLifecycle = new StubHttpLifecycle.Builder() .withUUID("uuid") - .withRequest(new StubRequest.Builder().withUrl("/some/uri/path/1").withMethod("GET").build()) + .withRequest(new StubRequest.Builder() + .withUrl("/some/uri/path/1") + .withMethod("GET") + .build()) .withResponse(new StubResponse.Builder().build()) .build(); @@ -1154,24 +1332,33 @@ public void shouldApplyProxyConfigAdditiveStrategyHeadersToHttpTransport_WhenRes .withPropertyEndpoint("https://jsonplaceholder.typicode.com") .build(); - final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet(new LinkedList() {{ - add(httpLifecycle); - }}, new HashMap() {{ - put(httpLifecycle.getUUID(), httpLifecycle); - }}, new HashMap() {{ - put(stubProxyConfig.getUUID(), stubProxyConfig); - }}); + final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet( + new LinkedList() { + { + add(httpLifecycle); + } + }, + new HashMap() { + { + put(httpLifecycle.getUUID(), httpLifecycle); + } + }, + new HashMap() { + { + put(stubProxyConfig.getUUID(), stubProxyConfig); + } + }); spyStubRepository.resetStubsCache(yamlParseResultSet); - when(mockStubbyHttpTransport.httpRequestFromStub(any(StubRequest.class), anyString())).thenReturn(new StubbyResponse(201, "OK!", new HashMap<>())); + when(mockStubbyHttpTransport.httpRequestFromStub(any(StubRequest.class), anyString())) + .thenReturn(new StubbyResponse(201, "OK!", new HashMap<>())); - final StubRequest incomingRequest = - requestBuilder - .withUrl("/post/1") - .withMethodGet() - .withHeader("content-type", Common.HEADER_APPLICATION_JSON) - .build(); + final StubRequest incomingRequest = requestBuilder + .withUrl("/post/1") + .withMethodGet() + .withHeader("content-type", Common.HEADER_APPLICATION_JSON) + .build(); doReturn(incomingRequest).when(spyStubRepository).toStubRequest(any(HttpServletRequest.class)); spyStubRepository.search(mockHttpServletRequest); @@ -1180,17 +1367,24 @@ public void shouldApplyProxyConfigAdditiveStrategyHeadersToHttpTransport_WhenRes // The 'content-type', HEADER_X_STUBBY_PROXY_REQUEST and two additive headers assertThat(stubRequestCaptor.getValue().getHeaders().size()).isEqualTo(4); - assertThat(stubRequestCaptor.getValue().getHeaders().containsKey(HEADER_X_STUBBY_PROXY_REQUEST)).isTrue(); - assertThat(stubRequestCaptor.getValue().getHeaders().containsKey("x-custom-header")).isTrue(); - assertThat(stubRequestCaptor.getValue().getHeaders().containsKey("x-custom-header-2")).isTrue(); + assertThat(stubRequestCaptor.getValue().getHeaders().containsKey(HEADER_X_STUBBY_PROXY_REQUEST)) + .isTrue(); + assertThat(stubRequestCaptor.getValue().getHeaders().containsKey("x-custom-header")) + .isTrue(); + assertThat(stubRequestCaptor.getValue().getHeaders().containsKey("x-custom-header-2")) + .isTrue(); } @Test - public void shouldNotApplyProxyConfigAdditiveStrategyEmptyHeadersToHttpTransport_WhenResponseIsProxiable() throws Exception { + public void shouldNotApplyProxyConfigAdditiveStrategyEmptyHeadersToHttpTransport_WhenResponseIsProxiable() + throws Exception { final StubHttpLifecycle httpLifecycle = new StubHttpLifecycle.Builder() .withUUID("uuid") - .withRequest(new StubRequest.Builder().withUrl("/some/uri/path/1").withMethod("GET").build()) + .withRequest(new StubRequest.Builder() + .withUrl("/some/uri/path/1") + .withMethod("GET") + .build()) .withResponse(new StubResponse.Builder().build()) .build(); @@ -1199,24 +1393,33 @@ public void shouldNotApplyProxyConfigAdditiveStrategyEmptyHeadersToHttpTransport .withPropertyEndpoint("https://jsonplaceholder.typicode.com") .build(); - final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet(new LinkedList() {{ - add(httpLifecycle); - }}, new HashMap() {{ - put(httpLifecycle.getUUID(), httpLifecycle); - }}, new HashMap() {{ - put(stubProxyConfig.getUUID(), stubProxyConfig); - }}); + final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet( + new LinkedList() { + { + add(httpLifecycle); + } + }, + new HashMap() { + { + put(httpLifecycle.getUUID(), httpLifecycle); + } + }, + new HashMap() { + { + put(stubProxyConfig.getUUID(), stubProxyConfig); + } + }); spyStubRepository.resetStubsCache(yamlParseResultSet); - when(mockStubbyHttpTransport.httpRequestFromStub(any(StubRequest.class), anyString())).thenReturn(new StubbyResponse(201, "OK!", new HashMap<>())); + when(mockStubbyHttpTransport.httpRequestFromStub(any(StubRequest.class), anyString())) + .thenReturn(new StubbyResponse(201, "OK!", new HashMap<>())); - final StubRequest incomingRequest = - requestBuilder - .withUrl("/post/1") - .withMethodGet() - .withHeader("content-type", Common.HEADER_APPLICATION_JSON) - .build(); + final StubRequest incomingRequest = requestBuilder + .withUrl("/post/1") + .withMethodGet() + .withHeader("content-type", Common.HEADER_APPLICATION_JSON) + .build(); doReturn(incomingRequest).when(spyStubRepository).toStubRequest(any(HttpServletRequest.class)); spyStubRepository.search(mockHttpServletRequest); @@ -1225,16 +1428,22 @@ public void shouldNotApplyProxyConfigAdditiveStrategyEmptyHeadersToHttpTransport // The 'content-type' header and the HEADER_X_STUBBY_PROXY_REQUEST only assertThat(stubRequestCaptor.getValue().getHeaders().size()).isEqualTo(2); - assertThat(stubRequestCaptor.getValue().getHeaders().containsKey(HEADER_X_STUBBY_PROXY_REQUEST)).isTrue(); - assertThat(stubRequestCaptor.getValue().getHeaders().containsKey("content-type")).isTrue(); + assertThat(stubRequestCaptor.getValue().getHeaders().containsKey(HEADER_X_STUBBY_PROXY_REQUEST)) + .isTrue(); + assertThat(stubRequestCaptor.getValue().getHeaders().containsKey("content-type")) + .isTrue(); } @Test - public void shouldApplyProxyConfigByProxyConfigUuidHeaderToHttpTransport_WhenResponseIsProxiable() throws Exception { + public void shouldApplyProxyConfigByProxyConfigUuidHeaderToHttpTransport_WhenResponseIsProxiable() + throws Exception { final StubHttpLifecycle httpLifecycle = new StubHttpLifecycle.Builder() .withUUID("uuid") - .withRequest(new StubRequest.Builder().withUrl("/some/uri/path/1").withMethod("GET").build()) + .withRequest(new StubRequest.Builder() + .withUrl("/some/uri/path/1") + .withMethod("GET") + .build()) .withResponse(new StubResponse.Builder().build()) .build(); @@ -1250,14 +1459,23 @@ public void shouldApplyProxyConfigByProxyConfigUuidHeaderToHttpTransport_WhenRes .withPropertyEndpoint("https://google.com") .build(); - final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet(new LinkedList() {{ - add(httpLifecycle); - }}, new HashMap() {{ - put(httpLifecycle.getUUID(), httpLifecycle); - }}, new HashMap() {{ - put(defaultStubProxyConfig.getUUID(), defaultStubProxyConfig); - put(anotherStubProxyConfig.getUUID(), anotherStubProxyConfig); - }}); + final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet( + new LinkedList() { + { + add(httpLifecycle); + } + }, + new HashMap() { + { + put(httpLifecycle.getUUID(), httpLifecycle); + } + }, + new HashMap() { + { + put(defaultStubProxyConfig.getUUID(), defaultStubProxyConfig); + put(anotherStubProxyConfig.getUUID(), anotherStubProxyConfig); + } + }); spyStubRepository.resetStubsCache(yamlParseResultSet); @@ -1268,15 +1486,15 @@ public void shouldApplyProxyConfigByProxyConfigUuidHeaderToHttpTransport_WhenRes httpProxyResponseHeaders.put("Expires", Collections.singletonList("12345")); httpProxyResponseHeaders.put("SomeHeader", Arrays.asList("one", "two")); - when(mockStubbyHttpTransport.httpRequestFromStub(any(StubRequest.class), anyString())).thenReturn(new StubbyResponse(201, actualResponseText, httpProxyResponseHeaders)); + when(mockStubbyHttpTransport.httpRequestFromStub(any(StubRequest.class), anyString())) + .thenReturn(new StubbyResponse(201, actualResponseText, httpProxyResponseHeaders)); - final StubRequest incomingRequest = - requestBuilder - .withUrl("/post/1") - .withMethodGet() - .withHeader("content-type", Common.HEADER_APPLICATION_JSON) - .withHeader(HEADER_X_STUBBY_PROXY_CONFIG, anotherStubProxyConfig.getUUID()) - .build(); + final StubRequest incomingRequest = requestBuilder + .withUrl("/post/1") + .withMethodGet() + .withHeader("content-type", Common.HEADER_APPLICATION_JSON) + .withHeader(HEADER_X_STUBBY_PROXY_CONFIG, anotherStubProxyConfig.getUUID()) + .build(); doReturn(incomingRequest).when(spyStubRepository).toStubRequest(any(HttpServletRequest.class)); final StubSearchResult stubSearchResult = spyStubRepository.search(mockHttpServletRequest); @@ -1291,25 +1509,34 @@ public void shouldApplyProxyConfigByProxyConfigUuidHeaderToHttpTransport_WhenRes assertThat(proxiedResponse.getHeaders().get("Expires")).isEqualTo("12345"); assertThat(proxiedResponse.getHeaders().get("SomeHeader")).isEqualTo("[one, two]"); - verify(mockStubbyHttpTransport, times(1)).httpRequestFromStub(stubRequestCaptor.capture(), stringCaptor.capture()); + verify(mockStubbyHttpTransport, times(1)) + .httpRequestFromStub(stubRequestCaptor.capture(), stringCaptor.capture()); // the non-default proxy config was used to proxy the request because // the 'x-stubby4j-proxy-config-uuid' header was set on the asserting incoming HTTP request assertThat(stringCaptor.getValue()).isEqualTo("https://google.com/post/1"); - assertThat(stubRequestCaptor.getValue().getHeaders().containsKey(HEADER_X_STUBBY_PROXY_REQUEST)).isTrue(); + assertThat(stubRequestCaptor.getValue().getHeaders().containsKey(HEADER_X_STUBBY_PROXY_REQUEST)) + .isTrue(); - final String proxyRequestUuid = stubRequestCaptor.getValue().getHeaders().get(HEADER_X_STUBBY_PROXY_REQUEST); - assertThat(proxiedResponse.getHeaders().get(HEADER_X_STUBBY_PROXY_RESPONSE)).isEqualTo(proxyRequestUuid); + final String proxyRequestUuid = + stubRequestCaptor.getValue().getHeaders().get(HEADER_X_STUBBY_PROXY_REQUEST); + assertThat(proxiedResponse.getHeaders().get(HEADER_X_STUBBY_PROXY_RESPONSE)) + .isEqualTo(proxyRequestUuid); - verify(mockStubbyHttpTransport, never()).httpRequestFromStub(any(StubRequest.class), eq("https://jsonplaceholder.typicode.com")); + verify(mockStubbyHttpTransport, never()) + .httpRequestFromStub(any(StubRequest.class), eq("https://jsonplaceholder.typicode.com")); } @Test - public void shouldApplyDefaultProxyConfigWhenProxyConfigUuidHeaderIncorrectToHttpTransport_WhenResponseIsProxiable() throws Exception { + public void shouldApplyDefaultProxyConfigWhenProxyConfigUuidHeaderIncorrectToHttpTransport_WhenResponseIsProxiable() + throws Exception { final StubHttpLifecycle httpLifecycle = new StubHttpLifecycle.Builder() .withUUID("uuid") - .withRequest(new StubRequest.Builder().withUrl("/some/uri/path/1").withMethod("GET").build()) + .withRequest(new StubRequest.Builder() + .withUrl("/some/uri/path/1") + .withMethod("GET") + .build()) .withResponse(new StubResponse.Builder().build()) .build(); @@ -1325,14 +1552,23 @@ public void shouldApplyDefaultProxyConfigWhenProxyConfigUuidHeaderIncorrectToHtt .withPropertyEndpoint("https://google.com") .build(); - final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet(new LinkedList() {{ - add(httpLifecycle); - }}, new HashMap() {{ - put(httpLifecycle.getUUID(), httpLifecycle); - }}, new HashMap() {{ - put(defaultStubProxyConfig.getUUID(), defaultStubProxyConfig); - put(anotherStubProxyConfig.getUUID(), anotherStubProxyConfig); - }}); + final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet( + new LinkedList() { + { + add(httpLifecycle); + } + }, + new HashMap() { + { + put(httpLifecycle.getUUID(), httpLifecycle); + } + }, + new HashMap() { + { + put(defaultStubProxyConfig.getUUID(), defaultStubProxyConfig); + put(anotherStubProxyConfig.getUUID(), anotherStubProxyConfig); + } + }); spyStubRepository.resetStubsCache(yamlParseResultSet); @@ -1343,15 +1579,15 @@ public void shouldApplyDefaultProxyConfigWhenProxyConfigUuidHeaderIncorrectToHtt httpProxyResponseHeaders.put("Expires", Collections.singletonList("12345")); httpProxyResponseHeaders.put("SomeHeader", Arrays.asList("one", "two")); - when(mockStubbyHttpTransport.httpRequestFromStub(any(StubRequest.class), anyString())).thenReturn(new StubbyResponse(201, actualResponseText, httpProxyResponseHeaders)); + when(mockStubbyHttpTransport.httpRequestFromStub(any(StubRequest.class), anyString())) + .thenReturn(new StubbyResponse(201, actualResponseText, httpProxyResponseHeaders)); - final StubRequest incomingRequest = - requestBuilder - .withUrl("/post/1") - .withMethodGet() - .withHeader("content-type", Common.HEADER_APPLICATION_JSON) - .withHeader(HEADER_X_STUBBY_PROXY_CONFIG, "WrongStubProxyConfigHeaderUUID") - .build(); + final StubRequest incomingRequest = requestBuilder + .withUrl("/post/1") + .withMethodGet() + .withHeader("content-type", Common.HEADER_APPLICATION_JSON) + .withHeader(HEADER_X_STUBBY_PROXY_CONFIG, "WrongStubProxyConfigHeaderUUID") + .build(); doReturn(incomingRequest).when(spyStubRepository).toStubRequest(any(HttpServletRequest.class)); final StubSearchResult stubSearchResult = spyStubRepository.search(mockHttpServletRequest); @@ -1366,25 +1602,34 @@ public void shouldApplyDefaultProxyConfigWhenProxyConfigUuidHeaderIncorrectToHtt assertThat(proxiedResponse.getHeaders().get("Expires")).isEqualTo("12345"); assertThat(proxiedResponse.getHeaders().get("SomeHeader")).isEqualTo("[one, two]"); - verify(mockStubbyHttpTransport, times(1)).httpRequestFromStub(stubRequestCaptor.capture(), stringCaptor.capture()); + verify(mockStubbyHttpTransport, times(1)) + .httpRequestFromStub(stubRequestCaptor.capture(), stringCaptor.capture()); // the default proxy config was used to proxy the request because // the 'x-stubby4j-proxy-config-uuid' header was set to a value that does not exist in proxyConfigs map assertThat(stringCaptor.getValue()).isEqualTo("https://jsonplaceholder.typicode.com/post/1"); - assertThat(stubRequestCaptor.getValue().getHeaders().containsKey(HEADER_X_STUBBY_PROXY_REQUEST)).isTrue(); + assertThat(stubRequestCaptor.getValue().getHeaders().containsKey(HEADER_X_STUBBY_PROXY_REQUEST)) + .isTrue(); - final String proxyRequestUuid = stubRequestCaptor.getValue().getHeaders().get(HEADER_X_STUBBY_PROXY_REQUEST); - assertThat(proxiedResponse.getHeaders().get(HEADER_X_STUBBY_PROXY_RESPONSE)).isEqualTo(proxyRequestUuid); + final String proxyRequestUuid = + stubRequestCaptor.getValue().getHeaders().get(HEADER_X_STUBBY_PROXY_REQUEST); + assertThat(proxiedResponse.getHeaders().get(HEADER_X_STUBBY_PROXY_RESPONSE)) + .isEqualTo(proxyRequestUuid); - verify(mockStubbyHttpTransport, never()).httpRequestFromStub(any(StubRequest.class), eq("https://jsonplaceholder.typicode.com")); + verify(mockStubbyHttpTransport, never()) + .httpRequestFromStub(any(StubRequest.class), eq("https://jsonplaceholder.typicode.com")); } @Test - public void shouldPassDefaultProxyConfigStateToHttpTransport_WhenResponseIsProxiableButExceptionThrows() throws Exception { + public void shouldPassDefaultProxyConfigStateToHttpTransport_WhenResponseIsProxiableButExceptionThrows() + throws Exception { final StubHttpLifecycle httpLifecycle = new StubHttpLifecycle.Builder() .withUUID("uuid") - .withRequest(new StubRequest.Builder().withUrl("/some/uri/path/1").withMethod("GET").build()) + .withRequest(new StubRequest.Builder() + .withUrl("/some/uri/path/1") + .withMethod("GET") + .build()) .withResponse(new StubResponse.Builder().build()) .build(); @@ -1393,23 +1638,32 @@ public void shouldPassDefaultProxyConfigStateToHttpTransport_WhenResponseIsProxi .withPropertyEndpoint("https://jsonplaceholder.typicode.com") .build(); - final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet(new LinkedList() {{ - add(httpLifecycle); - }}, new HashMap() {{ - put(httpLifecycle.getUUID(), httpLifecycle); - }}, new HashMap() {{ - put(stubProxyConfig.getUUID(), stubProxyConfig); - }}); + final YamlParseResultSet yamlParseResultSet = new YamlParseResultSet( + new LinkedList() { + { + add(httpLifecycle); + } + }, + new HashMap() { + { + put(httpLifecycle.getUUID(), httpLifecycle); + } + }, + new HashMap() { + { + put(stubProxyConfig.getUUID(), stubProxyConfig); + } + }); spyStubRepository.resetStubsCache(yamlParseResultSet); - when(mockStubbyHttpTransport.httpRequestFromStub(any(StubRequest.class), anyString())).thenThrow(new IOException("Boom!")); + when(mockStubbyHttpTransport.httpRequestFromStub(any(StubRequest.class), anyString())) + .thenThrow(new IOException("Boom!")); - final StubRequest incomingRequest = - requestBuilder - .withUrl("/post/1") - .withMethodGet() - .withHeader("content-type", Common.HEADER_APPLICATION_JSON) - .build(); + final StubRequest incomingRequest = requestBuilder + .withUrl("/post/1") + .withMethodGet() + .withHeader("content-type", Common.HEADER_APPLICATION_JSON) + .build(); doReturn(incomingRequest).when(spyStubRepository).toStubRequest(any(HttpServletRequest.class)); final StubSearchResult stubSearchResult = spyStubRepository.search(mockHttpServletRequest); @@ -1419,29 +1673,34 @@ public void shouldPassDefaultProxyConfigStateToHttpTransport_WhenResponseIsProxi assertThat(proxiedResponse.getHttpStatusCode()).isEqualTo(HttpStatus.Code.INTERNAL_SERVER_ERROR); assertThat(proxiedResponse.getHeaders().size()).isEqualTo(1); - verify(mockStubbyHttpTransport, times(1)).httpRequestFromStub(stubRequestCaptor.capture(), stringCaptor.capture()); + verify(mockStubbyHttpTransport, times(1)) + .httpRequestFromStub(stubRequestCaptor.capture(), stringCaptor.capture()); assertThat(stringCaptor.getValue()).isEqualTo("https://jsonplaceholder.typicode.com/post/1"); - assertThat(stubRequestCaptor.getValue().getHeaders().containsKey(HEADER_X_STUBBY_PROXY_REQUEST)).isTrue(); + assertThat(stubRequestCaptor.getValue().getHeaders().containsKey(HEADER_X_STUBBY_PROXY_REQUEST)) + .isTrue(); - final String proxyRequestUuid = stubRequestCaptor.getValue().getHeaders().get(HEADER_X_STUBBY_PROXY_REQUEST); - assertThat(proxiedResponse.getHeaders().get(HEADER_X_STUBBY_PROXY_RESPONSE)).isEqualTo(proxyRequestUuid); + final String proxyRequestUuid = + stubRequestCaptor.getValue().getHeaders().get(HEADER_X_STUBBY_PROXY_REQUEST); + assertThat(proxiedResponse.getHeaders().get(HEADER_X_STUBBY_PROXY_RESPONSE)) + .isEqualTo(proxyRequestUuid); } @Test - public void stubbedRequestNotEqualsAssertingRequest_WhenQueryParamArrayElementsHaveDifferentSpacing() throws Exception { + public void stubbedRequestNotEqualsAssertingRequest_WhenQueryParamArrayElementsHaveDifferentSpacing() + throws Exception { final String paramOne = "names"; final String paramOneValue = "[\"cheburashka\", \"wendy\"]"; final String url = "/invoice/789"; - final StubRequest expectedRequest = - requestBuilder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue).build(); - + final StubRequest expectedRequest = requestBuilder + .withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .build(); when(mockHttpServletRequest.getPathInfo()).thenReturn(url); when(mockHttpServletRequest.getMethod()).thenReturn(HttpMethods.GET); @@ -1456,30 +1715,38 @@ private YamlParseResultSet parseYaml(final String url, final String uuid) throws return parseYaml(url, StubResponse.okResponse(), uuid); } - private YamlParseResultSet parseYaml(final String url, final StubResponse stubResponse, final String uuid) throws Exception { - final StubRequest stubRequest = - requestBuilder - .withUrl(url) - .withMethodGet() - .withHeader("content-type", Common.HEADER_APPLICATION_JSON) - .build(); + private YamlParseResultSet parseYaml(final String url, final StubResponse stubResponse, final String uuid) + throws Exception { + final StubRequest stubRequest = requestBuilder + .withUrl(url) + .withMethodGet() + .withHeader("content-type", Common.HEADER_APPLICATION_JSON) + .build(); return parseYaml(stubRequest, stubResponse, uuid); } - private YamlParseResultSet parseYaml(final StubRequest stubRequest, final StubResponse stubResponse, final String uuid) throws Exception { + private YamlParseResultSet parseYaml( + final StubRequest stubRequest, final StubResponse stubResponse, final String uuid) throws Exception { final StubHttpLifecycle.Builder stubBuilder = new StubHttpLifecycle.Builder(); - stubBuilder.withRequest(stubRequest) + stubBuilder + .withRequest(stubRequest) .withResponse(stubResponse) .withUUID(uuid) .withCompleteYAML("This is marshalled yaml snippet"); final StubHttpLifecycle stubHttpLifecycle = stubBuilder.build(); - return new YamlParseResultSet(new LinkedList() {{ - add(stubHttpLifecycle); - }}, new HashMap() {{ - put(stubHttpLifecycle.getUUID(), stubHttpLifecycle); - }}); + return new YamlParseResultSet( + new LinkedList() { + { + add(stubHttpLifecycle); + } + }, + new HashMap() { + { + put(stubHttpLifecycle.getUUID(), stubHttpLifecycle); + } + }); } } diff --git a/src/test/java/io/github/azagniotov/stubby4j/stubs/StubRequestBuilderTest.java b/src/test/java/io/github/azagniotov/stubby4j/stubs/StubRequestBuilderTest.java index ea6349040..a23df90aa 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/stubs/StubRequestBuilderTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/stubs/StubRequestBuilderTest.java @@ -1,16 +1,20 @@ -package io.github.azagniotov.stubby4j.stubs; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import io.github.azagniotov.stubby4j.utils.FileUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; - -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Optional; +package io.github.azagniotov.stubby4j.stubs; import static com.google.common.truth.Truth.assertThat; import static io.github.azagniotov.stubby4j.stubs.StubbableAuthorizationType.BASIC; @@ -19,6 +23,16 @@ import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.BODY; +import io.github.azagniotov.stubby4j.utils.FileUtils; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class StubRequestBuilderTest { @@ -59,8 +73,10 @@ public void shouldNotStage_WhenConfigurablePropertyPresentButFieldValueMissing() @Test public void stubbedRequestEqualsAssertingRequest_WhenNullUrlStubbed_AndNullUrlSubmitted() throws Exception { - final StubRequest expectedRequest = builder.withUrl(null).withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl(null).withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl(null).withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl(null).withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -77,8 +93,10 @@ public void stubbedRequestEqualsAssertingRequest_WhenEmptyUrlStubbed_AndEmptyUrl @Test public void stubbedRequestEqualsAssertingRequest_WhenNullUrlStubbed_ButUrlSubmitted() throws Exception { - final StubRequest expectedRequest = builder.withUrl(null).withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("invoice/123").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl(null).withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("invoice/123").withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -86,8 +104,10 @@ public void stubbedRequestEqualsAssertingRequest_WhenNullUrlStubbed_ButUrlSubmit @Test public void stubbedRequestNotEqualsAssertingRequest_WhenUrlStubbed_ButNullUrlSubmitted() throws Exception { - final StubRequest expectedRequest = builder.withUrl("/invoice/123").withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl(null).withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("/invoice/123").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl(null).withMethodGet().build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } @@ -109,7 +129,8 @@ public void stubbedRequestEqualsAssertingRequest_WhenUrlNotStubbed_ButUrlSubmitt final String url = "/invoice/123"; final StubRequest expectedRequest = builder.withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl(url).withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl(url).withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -118,44 +139,56 @@ public void stubbedRequestEqualsAssertingRequest_WhenUrlNotStubbed_ButUrlSubmitt public void stubbedRequestEqualsAssertingRequest_WhenRootUrlsEquals() throws Exception { final StubRequest expectedRequest = builder.withUrl("/").withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/").withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @Test - public void stubbedRequestEqualsAssertingRequest_WhenStubbedRootUrlStartsWithRegex_ButSubmittedUrlRoot() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenStubbedRootUrlStartsWithRegex_ButSubmittedUrlRoot() + throws Exception { - final StubRequest expectedRequest = builder.withUrl("^/$").withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("^/$").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/").withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } - @Test - public void stubbedRequestEqualsAssertingRequest_WhenStubbedUrlHasOptionalTrailingSlash_ButNoSlashSubmitted() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenStubbedUrlHasOptionalTrailingSlash_ButNoSlashSubmitted() + throws Exception { - final StubRequest expectedRequest = builder.withUrl("/invoice/123/?").withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/invoice/123").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("/invoice/123/?").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/invoice/123").withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @Test - public void stubbedRequestEqualsAssertingRequest_WhenStubbedUrlHasOptionalTrailingSlash_ButSlashSubmitted() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenStubbedUrlHasOptionalTrailingSlash_ButSlashSubmitted() + throws Exception { - final StubRequest expectedRequest = builder.withUrl("/invoice/123/?").withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/invoice/123/").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("/invoice/123/?").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/invoice/123/").withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @Test - public void stubbedRequestNotEqualsAssertingRequest_WhenStubbedUrlHasRequiredTrailingSlash_ButNoSlashSubmitted() throws Exception { + public void stubbedRequestNotEqualsAssertingRequest_WhenStubbedUrlHasRequiredTrailingSlash_ButNoSlashSubmitted() + throws Exception { - final StubRequest expectedRequest = builder.withUrl("/invoice/123/").withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/invoice/123").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("/invoice/123/").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/invoice/123").withMethodGet().build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } @@ -163,8 +196,10 @@ public void stubbedRequestNotEqualsAssertingRequest_WhenStubbedUrlHasRequiredTra @Test public void stubbedRequestEqualsAssertingRequest_WhenStubbedUrlRegexExact_AndUrlsEqual() throws Exception { - final StubRequest expectedRequest = builder.withUrl("^/invoice/123$").withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/invoice/123").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("^/invoice/123$").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/invoice/123").withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -172,8 +207,10 @@ public void stubbedRequestEqualsAssertingRequest_WhenStubbedUrlRegexExact_AndUrl @Test public void stubbedRequestEqualsAssertingRequest_WhenStubbedUrlRegexBeginsWith() throws Exception { - final StubRequest expectedRequest = builder.withUrl("^/invoice/123.*").withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/invoice/12345").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("^/invoice/123.*").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/invoice/12345").withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -181,17 +218,22 @@ public void stubbedRequestEqualsAssertingRequest_WhenStubbedUrlRegexBeginsWith() @Test public void stubbedRequestNotEqualsAssertingRequest_WhenSubmittedUrlLonger() throws Exception { - final StubRequest expectedRequest = builder.withUrl("/invoice/123").withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/invoice/12345").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("/invoice/123").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/invoice/12345").withMethodGet().build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } @Test - public void stubbedRequestNotEqualsAssertingRequest_WhenStubbedUrlRegexBeginsWith_AndSubmittedUrlWrong() throws Exception { + public void stubbedRequestNotEqualsAssertingRequest_WhenStubbedUrlRegexBeginsWith_AndSubmittedUrlWrong() + throws Exception { - final StubRequest expectedRequest = builder.withUrl("^/invoice/123").withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/invoice/1").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("^/invoice/123").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/invoice/1").withMethodGet().build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } @@ -199,8 +241,10 @@ public void stubbedRequestNotEqualsAssertingRequest_WhenStubbedUrlRegexBeginsWit @Test public void stubbedRequestNotEqualsAssertingRequest_WhenSubmittedUrlShorter() throws Exception { - final StubRequest expectedRequest = builder.withUrl("/invoice/123").withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/invoice/1").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("/invoice/123").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/invoice/1").withMethodGet().build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } @@ -208,17 +252,22 @@ public void stubbedRequestNotEqualsAssertingRequest_WhenSubmittedUrlShorter() th @Test public void stubbedRequestEqualsAssertingRequest_WhenUrlsEquals() throws Exception { - final StubRequest expectedRequest = builder.withUrl("/invoice/123").withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/invoice/123").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("/invoice/123").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/invoice/123").withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @Test - public void stubbedRequestEqualsAssertingRequest_WhenStubbedUrlRegexEndsWith_AndSubmittedUrlHasExtraBeggining() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenStubbedUrlRegexEndsWith_AndSubmittedUrlHasExtraBeggining() + throws Exception { - final StubRequest expectedRequest = builder.withUrl(".*/invoice/123$").withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/some/beggining/invoice/123").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl(".*/invoice/123$").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/some/beggining/invoice/123").withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -226,8 +275,10 @@ public void stubbedRequestEqualsAssertingRequest_WhenStubbedUrlRegexEndsWith_And @Test public void stubbedRequestEqualsAssertingRequest_WhenStubbedUrlRegexAnythingAround_AndUrlsEqual() throws Exception { - final StubRequest expectedRequest = builder.withUrl(".*/invoice/123.*").withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/invoice/123").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl(".*/invoice/123.*").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/invoice/123").withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -235,8 +286,10 @@ public void stubbedRequestEqualsAssertingRequest_WhenStubbedUrlRegexAnythingArou @Test public void stubbedRequestEqualsAssertingRequest_WhenStubbedUrlRegexGroups_AndUrlsEqual() throws Exception { - final StubRequest expectedRequest = builder.withUrl("(.*)(/invoice/123)(.*)").withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/invoice/123").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("(.*)(/invoice/123)(.*)").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/invoice/123").withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -252,36 +305,35 @@ public void stubbedRequestNotEqualsAssertingRequest_WhenDifferentUri() throws Ex final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .build(); - final StubRequest assertingRequest = - builder.withUrl("/invoice/788") - .withMethodGet() - .withMethodHead() - .withQuery(paramTwo, paramTwoValue) - .withQuery(paramOne, paramOneValue).build(); + final StubRequest assertingRequest = builder.withUrl("/invoice/788") + .withMethodGet() + .withMethodHead() + .withQuery(paramTwo, paramTwoValue) + .withQuery(paramOne, paramOneValue) + .build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } - @Test public void stubbedRequestEqualsAssertingRequest_WhenMethodStubbed_ButLowerCasedMethodSubmitted() throws Exception { final String url = "/invoice/123"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl(url).withMethod("get").build(); + final StubRequest assertingRequest = + builder.withUrl(url).withMethod("get").build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } - @Test public void stubbedRequestNotEqualsAssertingRequest_WhenMethodStubbed_ButNoMethodSubmitted() throws Exception { @@ -299,7 +351,8 @@ public void stubbedRequestEqualsAssertingRequest_WhenNoMethodStubbed_ButMethodSu final String url = "/invoice/123"; final StubRequest expectedRequest = builder.withUrl(url).build(); - final StubRequest assertingRequest = builder.withUrl(url).withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl(url).withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -307,10 +360,8 @@ public void stubbedRequestEqualsAssertingRequest_WhenNoMethodStubbed_ButMethodSu @Test public void shouldAddMethod_WhenGivenMethodArgumentSet() throws Exception { - final StubRequest expectedRequest = builder - .withMethod("GET") - .withMethod("POST") - .withMethod("HEAD").build(); + final StubRequest expectedRequest = + builder.withMethod("GET").withMethod("POST").withMethod("HEAD").build(); assertThat(expectedRequest.getMethod().size()).isEqualTo(3); assertThat(expectedRequest.getMethod()).containsExactly("GET", "POST", "HEAD"); @@ -319,10 +370,8 @@ public void shouldAddMethod_WhenGivenMethodArgumentSet() throws Exception { @Test public void shouldAddMethod_WhenGivenMethodArgumentEmpty() throws Exception { - final StubRequest expectedRequest = builder - .withMethod("GET") - .withMethod("") - .withMethod("HEAD").build(); + final StubRequest expectedRequest = + builder.withMethod("GET").withMethod("").withMethod("HEAD").build(); assertThat(expectedRequest.getMethod().size()).isEqualTo(2); assertThat(expectedRequest.getMethod()).containsExactly("GET", "HEAD"); @@ -331,10 +380,8 @@ public void shouldAddMethod_WhenGivenMethodArgumentEmpty() throws Exception { @Test public void shouldAddMethod_WhenGivenMethodArgumentNull() throws Exception { - final StubRequest expectedRequest = builder - .withMethod("GET") - .withMethod(null) - .withMethod("HEAD").build(); + final StubRequest expectedRequest = + builder.withMethod("GET").withMethod(null).withMethod("HEAD").build(); assertThat(expectedRequest.getMethod().size()).isEqualTo(2); assertThat(expectedRequest.getMethod()).containsExactly("GET", "HEAD"); @@ -347,9 +394,7 @@ public void shouldGetPostBody_WhenPostProvided_ButFileIsNull() throws Exception final String postBody = "Hello"; final StubRequest expectedRequest = - builder.withUrl(url) - .withPost(postBody) - .withMethodPost().build(); + builder.withUrl(url).withPost(postBody).withMethodPost().build(); assertThat(expectedRequest.getPostBody()).isEqualTo(postBody); } @@ -360,11 +405,11 @@ public void shouldGetPostBody_WhenPostProvided_ButFileIsEmpty() throws Exception final String url = "/invoice/789"; final String postBody = "Hello"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withPost(postBody) - .withFile(FileUtils.tempFileFromString("")) - .withMethodPost().build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withPost(postBody) + .withFile(FileUtils.tempFileFromString("")) + .withMethodPost() + .build(); assertThat(expectedRequest.getPostBody()).isEqualTo(postBody); } @@ -375,22 +420,22 @@ public void shouldGetPostBody_WhenPostNotProvided_ButFileSet() throws Exception final String url = "/invoice/789"; final String fileContent = "Hello World!"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withFile(FileUtils.tempFileFromString(fileContent)) - .withMethodPost().build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withFile(FileUtils.tempFileFromString(fileContent)) + .withMethodPost() + .build(); assertThat(expectedRequest.getPostBody()).isEqualTo(fileContent); } - @Test public void stubbedRequestNotEqualsAssertingRequest_WhenDifferentHttpMethod() throws Exception { final String url = "/invoice/789"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl(url).withMethodPost().build(); + final StubRequest assertingRequest = + builder.withUrl(url).withMethodPost().build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } @@ -401,78 +446,72 @@ public void stubbedRequestNotEqualsAssertingRequest_WhenDifferentPostBody() thro final String url = "/invoice/789"; final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodPost() - .withPost("some post").build(); + builder.withUrl(url).withMethodPost().withPost("some post").build(); final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodPost() - .withPost("different post").build(); + builder.withUrl(url).withMethodPost().withPost("different post").build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } @Test - public void stubbedRequestNotEqualsAssertingRequest_WhenPostBodyWasStubbed_ButNoPostBodySubmitted() throws Exception { + public void stubbedRequestNotEqualsAssertingRequest_WhenPostBodyWasStubbed_ButNoPostBodySubmitted() + throws Exception { final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodPost() - .withPost("some stubbed post").build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodPost() + .withPost("some stubbed post") + .build(); final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodPost().build(); + builder.withUrl(url).withMethodPost().build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } @Test - public void stubbedRequestEqualsAssertingRequest_WhenNoPostBodyWasStubbed_ButPostBodyWasSubmitted() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenNoPostBodyWasStubbed_ButPostBodyWasSubmitted() + throws Exception { final String url = "/invoice/789"; final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodPost().build(); + builder.withUrl(url).withMethodPost().build(); final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodPost() - .withPost("some post").build(); + builder.withUrl(url).withMethodPost().withPost("some post").build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @Test public void isSecured_WhenAuthorizationBasicStubbed() throws Exception { - final StubRequest stubRequest = - builder.withUrl("/invoice/123") - .withMethodGet() - .withHeader(BASIC.asYAMLProp(), "123").build(); + final StubRequest stubRequest = builder.withUrl("/invoice/123") + .withMethodGet() + .withHeader(BASIC.asYAMLProp(), "123") + .build(); assertThat(stubRequest.isSecured()).isTrue(); } @Test public void isSecured_WhenAuthorizationBearerStubbed() throws Exception { - final StubRequest stubRequest = - builder.withUrl("/invoice/123") - .withMethodGet() - .withHeader(BEARER.asYAMLProp(), "123").build(); + final StubRequest stubRequest = builder.withUrl("/invoice/123") + .withMethodGet() + .withHeader(BEARER.asYAMLProp(), "123") + .build(); assertThat(stubRequest.isSecured()).isTrue(); } @Test public void isSecured_WhenAuthorizationCustomStubbed() throws Exception { - final StubRequest stubRequest = - builder.withUrl("/invoice/123") - .withMethodGet() - .withHeader(CUSTOM.asYAMLProp(), "Custom 123").build(); + final StubRequest stubRequest = builder.withUrl("/invoice/123") + .withMethodGet() + .withHeader(CUSTOM.asYAMLProp(), "Custom 123") + .build(); assertThat(stubRequest.isSecured()).isTrue(); } @@ -480,38 +519,37 @@ public void isSecured_WhenAuthorizationCustomStubbed() throws Exception { @Test public void isNotSecured_WhenNoAuthorizationStubbed() throws Exception { final StubRequest stubRequest = - builder.withUrl("/invoice/123") - .withMethodGet().build(); + builder.withUrl("/invoice/123").withMethodGet().build(); assertThat(stubRequest.isSecured()).isFalse(); } @Test public void shouldGetAuthorizationTypeBasic_WhenBasicAuthorizationStubbed() throws Exception { - final StubRequest stubRequest = - builder.withUrl("/invoice/123") - .withMethodGet() - .withHeader(BASIC.asYAMLProp(), "123").build(); + final StubRequest stubRequest = builder.withUrl("/invoice/123") + .withMethodGet() + .withHeader(BASIC.asYAMLProp(), "123") + .build(); assertThat(stubRequest.getStubbedAuthorizationType()).isEqualTo(BASIC); } @Test public void shouldGetAuthorizationTypeBearer_WhenBearerAuthorizationStubbed() throws Exception { - final StubRequest stubRequest = - builder.withUrl("/invoice/123") - .withMethodGet() - .withHeader(BEARER.asYAMLProp(), "123").build(); + final StubRequest stubRequest = builder.withUrl("/invoice/123") + .withMethodGet() + .withHeader(BEARER.asYAMLProp(), "123") + .build(); assertThat(stubRequest.getStubbedAuthorizationType()).isEqualTo(BEARER); } @Test public void shouldGetAuthorizationTypeCustom_WhenCustomAuthorizationStubbed() throws Exception { - final StubRequest stubRequest = - builder.withUrl("/invoice/123") - .withMethodGet() - .withHeader(CUSTOM.asYAMLProp(), "Custom 123").build(); + final StubRequest stubRequest = builder.withUrl("/invoice/123") + .withMethodGet() + .withHeader(CUSTOM.asYAMLProp(), "Custom 123") + .build(); assertThat(stubRequest.getStubbedAuthorizationType()).isEqualTo(CUSTOM); } @@ -522,64 +560,60 @@ public void stubbedRequestEqualsAssertingRequest_WhenAllHttpHeadersMatch() throw final String url = "/invoice/123"; final String contentLength = "30"; final String contentLanguage = "en-US"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withApplicationXmlContentType() - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withApplicationXmlContentType() + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withApplicationXmlContentType() - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withApplicationXmlContentType() + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } - @Test - public void stubbedRequestNotEqualsAssertingRequest_WhenHeadersWereStubbed_ButNoHeadersSetToAssert() throws Exception { + public void stubbedRequestNotEqualsAssertingRequest_WhenHeadersWereStubbed_ButNoHeadersSetToAssert() + throws Exception { final String url = "/invoice/123"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withApplicationXmlContentType() - .withHeaderContentLength("30") - .withHeaderContentLanguage("en-US").build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withApplicationXmlContentType() + .withHeaderContentLength("30") + .withHeaderContentLanguage("en-US") + .build(); final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet().build(); + builder.withUrl(url).withMethodGet().build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } - @Test - public void stubbedRequestEqualsAssertingRequest_WhenNoHeadersWereStubbed_ButHeadersWereSetToAssert() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenNoHeadersWereStubbed_ButHeadersWereSetToAssert() + throws Exception { final String url = "/invoice/123"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet().build(); + final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withApplicationXmlContentType() - .withHeaderContentLength("30") - .withHeaderContentLanguage("en-US").build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withApplicationXmlContentType() + .withHeaderContentLength("30") + .withHeaderContentLanguage("en-US") + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } - @Test public void stubbedRequestEqualsAssertingRequest_WhenAllHeadersSubmittedCamelCased() throws Exception { @@ -587,24 +621,23 @@ public void stubbedRequestEqualsAssertingRequest_WhenAllHeadersSubmittedCamelCas final String contentLanguage = "en-US"; final String url = "/invoice/123"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withApplicationXmlContentType() - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withApplicationXmlContentType() + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withApplicationXmlContentType() - .withHeader("Content-Length", contentLength) - .withHeader("Content-Language", contentLanguage).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withApplicationXmlContentType() + .withHeader("Content-Length", contentLength) + .withHeader("Content-Language", contentLanguage) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } - @Test public void stubbedRequestEqualsAssertingRequest_WhenAllHeadersStubbedCamelCased() throws Exception { @@ -612,25 +645,23 @@ public void stubbedRequestEqualsAssertingRequest_WhenAllHeadersStubbedCamelCased final String contentLanguage = "en-US"; final String url = "/invoice/123"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withApplicationXmlContentType() - .withHeader("Content-Length", contentLength) - .withHeader("Content-Language", contentLanguage).build(); - - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withApplicationXmlContentType() - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withApplicationXmlContentType() + .withHeader("Content-Length", contentLength) + .withHeader("Content-Language", contentLanguage) + .build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withApplicationXmlContentType() + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } - @Test public void stubbedRequestNotEqualsAssertingRequest_WhenSomeHeadersMismatches() throws Exception { @@ -638,19 +669,19 @@ public void stubbedRequestNotEqualsAssertingRequest_WhenSomeHeadersMismatches() final String contentLanguage = "en-US"; final String url = "/invoice/123"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withHeaderContentType("application/xml") - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withHeaderContentType("application/xml") + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withApplicationJsonContentType() - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withApplicationJsonContentType() + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } @@ -662,23 +693,22 @@ public void stubbedRequestNotEqualsAssertingRequest_WhenNotAllHeadersSetToAssert final String contentLanguage = "en-US"; final String url = "/invoice/123"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withApplicationXmlContentType() - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withApplicationXmlContentType() + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } - @Test public void stubbedRequestEqualsAssertingRequest_WhenAllStubbedHeadersMatch() throws Exception { @@ -686,28 +716,28 @@ public void stubbedRequestEqualsAssertingRequest_WhenAllStubbedHeadersMatch() th final String contentLanguage = "en-US"; final String url = "/invoice/123"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withApplicationXmlContentType() - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withApplicationXmlContentType() + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withApplicationXmlContentType() - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage) - .withHeaderContentEncoding("UTF-8") - .withHeaderPragma("no-cache").build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withApplicationXmlContentType() + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .withHeaderContentEncoding("UTF-8") + .withHeaderPragma("no-cache") + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } - @Test - public void stubbedRequestEqualsAssertingRequest_WhenNoQueryParamsWereStubbed_ButQueryParamsWereSetToAssert() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenNoQueryParamsWereStubbed_ButQueryParamsWereSetToAssert() + throws Exception { final String paramOne = "paramOne"; final String paramOneValue = "one"; @@ -718,22 +748,21 @@ public void stubbedRequestEqualsAssertingRequest_WhenNoQueryParamsWereStubbed_Bu final String url = "/invoice/789"; final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead().build(); + builder.withUrl(url).withMethodGet().withMethodHead().build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @Test - public void stubbedRequestNotEqualsAssertingRequest_WhenQueryParamsWereStubbed_ButNoQueryParamsWereSetToAssert() throws Exception { + public void stubbedRequestNotEqualsAssertingRequest_WhenQueryParamsWereStubbed_ButNoQueryParamsWereSetToAssert() + throws Exception { final String paramOne = "paramOne"; final String paramOneValue = "one"; @@ -743,22 +772,19 @@ public void stubbedRequestNotEqualsAssertingRequest_WhenQueryParamsWereStubbed_B final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .build(); final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead().build(); + builder.withUrl(url).withMethodGet().withMethodHead().build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } - @Test public void stubbedRequestEqualsAssertingRequest_WhenAllQueryParamsMatch() throws Exception { @@ -770,24 +796,23 @@ public void stubbedRequestEqualsAssertingRequest_WhenAllQueryParamsMatch() throw final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } - @Test public void stubbedRequestEqualsAssertingRequest_WhenAllStubbedQueryParamsMatch() throws Exception { @@ -799,25 +824,24 @@ public void stubbedRequestEqualsAssertingRequest_WhenAllStubbedQueryParamsMatch( final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue) - .withQuery("paramThree", "three").build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .withQuery("paramThree", "three") + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } - @Test public void stubbedRequestNotEqualsAssertingRequest_WhenNotAllQueryParamsSetToAssert() throws Exception { @@ -829,20 +853,20 @@ public void stubbedRequestNotEqualsAssertingRequest_WhenNotAllQueryParamsSetToAs final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue) - .withQuery("paramThree", "three").build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .withQuery("paramThree", "three") + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } @@ -858,19 +882,19 @@ public void stubbedRequestNotEqualsAssertingRequest_WhenQueryParamsMismatch() th final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, "three").build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, "three") + .build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } @@ -886,19 +910,19 @@ public void stubbedRequestEqualsAssertingRequest_WhenQueryParamsInDifferentOrder final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramTwo, paramTwoValue) - .withQuery(paramOne, paramOneValue).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramTwo, paramTwoValue) + .withQuery(paramOne, paramOneValue) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -914,19 +938,19 @@ public void stubbedRequestEqualsAssertingRequest_WhenQueryParamIsArray() throws final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -947,34 +971,33 @@ public void stubbedRequestEqualsAssertingRequest_WhenThereLargeSetupOfStubbedPro final String url = "/invoice/123"; final String postBody = "this is a post body"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodPost() - .withMethodPut() - .withPost(postBody) - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue) - .withHeaderContentType(contentType) - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage).build(); - - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodPost() - .withPost(postBody) - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue) - .withHeaderContentType(contentType) - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage) - .withHeaderContentEncoding("UTF-8") - .withHeaderPragma("no-cache").build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withMethodPost() + .withMethodPut() + .withPost(postBody) + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .withHeaderContentType(contentType) + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .build(); + + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodPost() + .withPost(postBody) + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .withHeaderContentType(contentType) + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .withHeaderContentEncoding("UTF-8") + .withHeaderPragma("no-cache") + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } - @Test public void stubbedRequestEqualsAssertingRequest_WhenQueryParamRegexIsMatching() throws Exception { @@ -987,19 +1010,19 @@ public void stubbedRequestEqualsAssertingRequest_WhenQueryParamRegexIsMatching() final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoRegex).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoRegex) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoAssertingValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoAssertingValue) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -1016,19 +1039,19 @@ public void stubbedRequestNotEqualsAssertingRequest_WhenQueryParamRegexDoesNotMa final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoRegex).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoRegex) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoAssertingValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoAssertingValue) + .build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } @@ -1045,19 +1068,19 @@ public void stubbedRequestEqualsAssertingRequest_WhenHeaderRegexIsMatching() thr final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withHeader(headerOne, headerOneValue) - .withHeader(headerTwo, headerTwoRegex).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withHeader(headerOne, headerOneValue) + .withHeader(headerTwo, headerTwoRegex) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withHeader(headerOne, headerOneValue) - .withHeader(headerTwo, headerTwoAssertingValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withHeader(headerOne, headerOneValue) + .withHeader(headerTwo, headerTwoAssertingValue) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -1074,51 +1097,51 @@ public void stubbedRequestNotEqualsAssertingRequest_WhenHeaderRegexDoesNotMatch( final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withHeader(headerOne, headerOneValue) - .withHeader(headerTwo, headerTwoRegex).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withHeader(headerOne, headerOneValue) + .withHeader(headerTwo, headerTwoRegex) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodHead() - .withHeader(headerOne, headerOneValue) - .withHeader(headerTwo, headerTwoAssertingValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodGet() + .withMethodHead() + .withHeader(headerOne, headerOneValue) + .withHeader(headerTwo, headerTwoAssertingValue) + .build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } @Test - public void stubbedRequestEqualsAssertingRequest_WhenPostRegexMatchingAnyPostWithoutNewLineCharacter() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenPostRegexMatchingAnyPostWithoutNewLineCharacter() + throws Exception { final String postRegex = ".*"; final String postAssertingValue = - "Here's the story of a lovely lady, " + - "Who was bringing up three very lovely girls. " + - "All of them had hair of gold, like their mother, " + - "The youngest one in curls. " + - "Here's the story, of a man named Brady, " + - "Who was busy with three boys of his own. " + - "They were four men, living all together, " + - "Yet they were all alone."; + "Here's the story of a lovely lady, " + "Who was bringing up three very lovely girls. " + + "All of them had hair of gold, like their mother, " + + "The youngest one in curls. " + + "Here's the story, of a man named Brady, " + + "Who was busy with three boys of his own. " + + "They were four men, living all together, " + + "Yet they were all alone."; final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodPost() - .withMethodHead() - .withPost(postRegex).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodPost() + .withMethodHead() + .withPost(postRegex) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodPost() - .withMethodHead() - .withPost(postAssertingValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodPost() + .withMethodHead() + .withPost(postAssertingValue) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -1129,28 +1152,27 @@ public void stubbedRequestEqualsAssertingRequest_WhenPostRegexMatchingPostWithLi final String postRegex = ".*"; final String postAssertingValue = - "Here's the story of a lovely lady,\n" + - "Who was bringing up three very lovely girls.\n" + - "All of them had hair of gold, like their mother,\n" + - "The youngest one in curls.\n" + - "Here's the story, of a man named Brady,\n" + - "Who was busy with three boys of his own.\n" + - "They were four men, living all together,\n" + - "Yet they were all alone."; + "Here's the story of a lovely lady,\n" + "Who was bringing up three very lovely girls.\n" + + "All of them had hair of gold, like their mother,\n" + + "The youngest one in curls.\n" + + "Here's the story, of a man named Brady,\n" + + "Who was busy with three boys of his own.\n" + + "They were four men, living all together,\n" + + "Yet they were all alone."; final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodPost() - .withMethodHead() - .withPost(postRegex).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodPost() + .withMethodHead() + .withPost(postRegex) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodPost() - .withMethodHead() - .withPost(postAssertingValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodPost() + .withMethodHead() + .withPost(postAssertingValue) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -1161,92 +1183,91 @@ public void stubbedRequestEqualsAssertingRequest_WhenPostRegexMatchingPostWithSy final String postRegex = ".*"; final String postAssertingValue = - "Here's the story of a lovely lady," + BR + - "Who was bringing up three very lovely girls." + BR + - "All of them had hair of gold, like their mother," + BR + - "The youngest one in curls." + BR + - "Here's the story, of a man named Brady," + BR + - "Who was busy with three boys of his own." + BR + - "They were four men, living all together," + BR + - "Yet they were all alone."; + "Here's the story of a lovely lady," + BR + "Who was bringing up three very lovely girls." + + BR + "All of them had hair of gold, like their mother," + + BR + "The youngest one in curls." + + BR + "Here's the story, of a man named Brady," + + BR + "Who was busy with three boys of his own." + + BR + "They were four men, living all together," + + BR + "Yet they were all alone."; final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodPost() - .withMethodHead() - .withPost(postRegex).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodPost() + .withMethodHead() + .withPost(postRegex) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodPost() - .withMethodHead() - .withPost(postAssertingValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodPost() + .withMethodHead() + .withPost(postAssertingValue) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @Test - public void stubbedRequestEqualsAssertingRequest_WhenPostRegexMatchingPostWithCarriageReturnChar() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenPostRegexMatchingPostWithCarriageReturnChar() + throws Exception { final String postRegex = ".*"; final String postAssertingValue = - "Here's the story of a lovely lady,\r" + - "Who was bringing up three very lovely girls.\r" + - "All of them had hair of gold, like their mother,\r" + - "The youngest one in curls.\r" + - "Here's the story, of a man named Brady,\r" + - "Who was busy with three boys of his own.\r" + - "They were four men, living all together,\r" + - "Yet they were all alone."; + "Here's the story of a lovely lady,\r" + "Who was bringing up three very lovely girls.\r" + + "All of them had hair of gold, like their mother,\r" + + "The youngest one in curls.\r" + + "Here's the story, of a man named Brady,\r" + + "Who was busy with three boys of his own.\r" + + "They were four men, living all together,\r" + + "Yet they were all alone."; final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodPost() - .withMethodHead() - .withPost(postRegex).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodPost() + .withMethodHead() + .withPost(postRegex) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodPost() - .withMethodHead() - .withPost(postAssertingValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodPost() + .withMethodHead() + .withPost(postAssertingValue) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @Test - public void stubbedRequestEqualsAssertingRequest_WhenPostRegexMatchingPostWithCarriageReturnLinefeedChars() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenPostRegexMatchingPostWithCarriageReturnLinefeedChars() + throws Exception { final String postRegex = ".*"; final String postAssertingValue = - "Here's the story of a lovely lady,\r\n" + - "Who was bringing up three very lovely girls.\r\n" + - "All of them had hair of gold, like their mother,\r\n" + - "The youngest one in curls.\r\n" + - "Here's the story, of a man named Brady,\r\n" + - "Who was busy with three boys of his own.\r\n" + - "They were four men, living all together,\r\n" + - "Yet they were all alone."; + "Here's the story of a lovely lady,\r\n" + "Who was bringing up three very lovely girls.\r\n" + + "All of them had hair of gold, like their mother,\r\n" + + "The youngest one in curls.\r\n" + + "Here's the story, of a man named Brady,\r\n" + + "Who was busy with three boys of his own.\r\n" + + "They were four men, living all together,\r\n" + + "Yet they were all alone."; final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodPost() - .withMethodHead() - .withPost(postRegex).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodPost() + .withMethodHead() + .withPost(postRegex) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodPost() - .withMethodHead() - .withPost(postAssertingValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodPost() + .withMethodHead() + .withPost(postAssertingValue) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -1259,14 +1280,12 @@ public void stubbedRequestEqualsAssertingRequest_WhenPlainPostRegexStubbedAndPla final String url = "/post"; final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodPost() - .withPost(postRegex).build(); + builder.withUrl(url).withMethodPost().withPost(postRegex).build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodPost() - .withPost(postAssertingValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodPost() + .withPost(postAssertingValue) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -1274,21 +1293,23 @@ public void stubbedRequestEqualsAssertingRequest_WhenPlainPostRegexStubbedAndPla @Test public void stubbedRequestEqualsAssertingRequest_WhenJsonPostRegexStubbedAndJsonPosted() throws Exception { - final String postRegex = "{\"userId\":\"19\",\"requestId\":\"(.*)\",\"transactionDate\":\"(.*)\",\"transactionTime\":\"(.*)\"}"; - final String postAssertingValue = "{\"userId\":\"19\",\"requestId\":\"12345\",\"transactionDate\":\"98765\",\"transactionTime\":\"11111\"}"; + final String postRegex = + "{\"userId\":\"19\",\"requestId\":\"(.*)\",\"transactionDate\":\"(.*)\",\"transactionTime\":\"(.*)\"}"; + final String postAssertingValue = + "{\"userId\":\"19\",\"requestId\":\"12345\",\"transactionDate\":\"98765\",\"transactionTime\":\"11111\"}"; final String url = "/post"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodPost() - .withApplicationJsonContentType() - .withPost(postRegex).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodPost() + .withApplicationJsonContentType() + .withPost(postRegex) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodPost() - .withApplicationJsonContentType() - .withPost(postAssertingValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodPost() + .withApplicationJsonContentType() + .withPost(postAssertingValue) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); @@ -1302,21 +1323,23 @@ public void stubbedRequestEqualsAssertingRequest_WhenJsonPostRegexStubbedAndJson @Test public void stubbedRequestEqualsAssertingRequest_WhenComplexJsonPostRegexStubbedAndJsonPosted() throws Exception { - final String postRegex = "{\"objects\": [{\"key\": \"value\"}, {\"key\": \"value\"}, {\"key\": {\"key\": \"(.*)\"}}]}"; - final String postAssertingValue = "{\"objects\": [{\"key\": \"value\"}, {\"key\": \"value\"}, {\"key\": {\"key\": \"12345\"}}]}"; + final String postRegex = + "{\"objects\": [{\"key\": \"value\"}, {\"key\": \"value\"}, {\"key\": {\"key\": \"(.*)\"}}]}"; + final String postAssertingValue = + "{\"objects\": [{\"key\": \"value\"}, {\"key\": \"value\"}, {\"key\": {\"key\": \"12345\"}}]}"; final String url = "/post"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodPost() - .withApplicationJsonContentType() - .withPost(postRegex).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodPost() + .withApplicationJsonContentType() + .withPost(postRegex) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodPost() - .withApplicationJsonContentType() - .withPost(postAssertingValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodPost() + .withApplicationJsonContentType() + .withPost(postAssertingValue) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); @@ -1329,48 +1352,48 @@ public void stubbedRequestEqualsAssertingRequest_WhenComplexJsonPostRegexStubbed public void shouldComputeRegexPatterns() throws Exception { final String url = "^/resources/asn/.*$"; - final String post = "{\"objects\": [{\"key\": \"value\"}, {\"key\": \"value\"}, {\"key\": {\"key\": \"(.*)\"}}]}"; - - final StubRequest stubRequest = - builder.withUrl(url) - .withMethodPost() - .withApplicationJsonContentType() - .withPost(post).build(); + final String post = + "{\"objects\": [{\"key\": \"value\"}, {\"key\": \"value\"}, {\"key\": {\"key\": \"(.*)\"}}]}"; + + final StubRequest stubRequest = builder.withUrl(url) + .withMethodPost() + .withApplicationJsonContentType() + .withPost(post) + .build(); stubRequest.compileRegexPatternsAndCache(); assertThat(RegexParser.REGEX_PATTERN_CACHE.size().get()).isEqualTo(3); } @Test - public void stubbedRequestEqualsAssertingRequest_WhenPostRegexMatchingSubsectionOfMultiLineJsonPost() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenPostRegexMatchingSubsectionOfMultiLineJsonPost() + throws Exception { final String postRegex = ".*(\"id\": \"123\").*"; - final String postAssertingValue = - "{" + - " \"products\": [" + - " {" + - " \"id\": \"123\"," + - " }," + - " {" + - " \"id\": \"789\"," + - " }" + - " ]" + - "}"; + final String postAssertingValue = "{" + " \"products\": [" + + " {" + + " \"id\": \"123\"," + + " }," + + " {" + + " \"id\": \"789\"," + + " }" + + " ]" + + "}"; final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodPost() - .withMethodHead() - .withPost(postRegex).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodPost() + .withMethodHead() + .withPost(postRegex) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodPost() - .withMethodHead() - .withPost(postAssertingValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodPost() + .withMethodHead() + .withPost(postAssertingValue) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @@ -1383,23 +1406,25 @@ public void stubbedRequestEqualsAssertingRequest_WhenPostRegexMatchingSingleLine final String url = "/invoice/789"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodPost() - .withMethodHead() - .withPost(postRegex).build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodPost() + .withMethodHead() + .withPost(postRegex) + .build(); - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodPost() - .withMethodHead() - .withPost(postValue).build(); + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodPost() + .withMethodHead() + .withPost(postValue) + .build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @Test - public void stubbedRequestEqualsAssertingRequest_WhenThereLargeSetupOfStubbedProperties_ButNotAllHeadersSetToAssert() throws Exception { + public void + stubbedRequestEqualsAssertingRequest_WhenThereLargeSetupOfStubbedProperties_ButNotAllHeadersSetToAssert() + throws Exception { final String paramOne = "paramOne"; final String paramOneValue = "one"; @@ -1413,91 +1438,102 @@ public void stubbedRequestEqualsAssertingRequest_WhenThereLargeSetupOfStubbedPro final String url = "/invoice/123"; final String postBody = "this is a post body"; - final StubRequest expectedRequest = - builder.withUrl(url) - .withMethodGet() - .withMethodPost() - .withMethodPut() - .withPost(postBody) - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue) - .withApplicationXmlContentType() - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage).build(); - - final StubRequest assertingRequest = - builder.withUrl(url) - .withMethodPost() - .withPost(postBody) - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue) - .withApplicationXmlContentType() - .withHeaderContentLength("888") - .withHeaderContentLanguage(contentLanguage) - .withHeaderContentEncoding("UTF-8") - .withHeaderPragma("no-cache").build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withMethodPost() + .withMethodPut() + .withPost(postBody) + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .withApplicationXmlContentType() + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .build(); + + final StubRequest assertingRequest = builder.withUrl(url) + .withMethodPost() + .withPost(postBody) + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .withApplicationXmlContentType() + .withHeaderContentLength("888") + .withHeaderContentLanguage(contentLanguage) + .withHeaderContentEncoding("UTF-8") + .withHeaderPragma("no-cache") + .build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } @Test - public void stubbedRequestEqualsAssertingRequest_WhenRegexifiedUrlDoesNotBeginWithRegexSign_ItsNotProcessedAsRegex() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenRegexifiedUrlDoesNotBeginWithRegexSign_ItsNotProcessedAsRegex() + throws Exception { final String url = ".*account.*"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/some/products/account/").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/some/products/account/").withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @Test - public void stubbedRequestEqualsAssertingRequest_WhenRegexifiedUrlBeginsWithRegexSign_ItsProcessedAsRegex() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenRegexifiedUrlBeginsWithRegexSign_ItsProcessedAsRegex() + throws Exception { final String url = "^.*account.*"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/some/products/account/").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/some/products/account/").withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @Test - public void stubbedRequestEqualsAssertingRequest_WhenUrlPartiallyRegexified_ButGoodAssertionUrlConfigured() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenUrlPartiallyRegexified_ButGoodAssertionUrlConfigured() + throws Exception { final String url = "^/products/[0-9]+/?$"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/products/12345/").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/products/12345/").withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @Test - public void stubbedRequestEqualsAssertingRequest_WhenUrlRegexified_ButGoodAssertionUrlConfigured() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenUrlRegexified_ButGoodAssertionUrlConfigured() + throws Exception { final String url = "^/[a-z]{3}/[0-9]+/?$"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/abc/12345/").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/abc/12345/").withMethodGet().build(); assertThat(assertingRequest).isEqualTo(expectedRequest); } @Test - public void stubbedRequestEqualsAssertingRequest_WhenUrlConditionallyRegexified_ButGoodAssertionUrlConfigured() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenUrlConditionallyRegexified_ButGoodAssertionUrlConfigured() + throws Exception { final String url = "^/(cats|dogs)/?(.*)"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final List assertingRequests = new LinkedList() {{ - add(builder.withUrl("/cats/blah/again/").withMethodGet().build()); - add(builder.withUrl("/cats/blah/").withMethodGet().build()); - add(builder.withUrl("/dogs/blah/").withMethodGet().build()); - add(builder.withUrl("/dogs/").withMethodGet().build()); - add(builder.withUrl("/dogs").withMethodGet().build()); - }}; + final List assertingRequests = new LinkedList() { + { + add(builder.withUrl("/cats/blah/again/").withMethodGet().build()); + add(builder.withUrl("/cats/blah/").withMethodGet().build()); + add(builder.withUrl("/dogs/blah/").withMethodGet().build()); + add(builder.withUrl("/dogs/").withMethodGet().build()); + add(builder.withUrl("/dogs").withMethodGet().build()); + } + }; for (final StubRequest assertingRequest : assertingRequests) { assertThat(assertingRequest).isEqualTo(expectedRequest); @@ -1505,49 +1541,65 @@ public void stubbedRequestEqualsAssertingRequest_WhenUrlConditionallyRegexified_ } @Test - public void stubbedRequestEqualsAssertingRequest_WhenUrlConditionallyRegexified_ButGoodAssertionUrlConfigured_v2() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenUrlConditionallyRegexified_ButGoodAssertionUrlConfigured_v2() + throws Exception { final String url = "^/(account|profile)/user/session/[a-zA-Z0-9]{32}/?"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final List assertingRequests = new LinkedList() {{ - add(builder.withUrl("/account/user/session/d41d8cd98f00b204e9800998ecf8427e").withMethodGet().build()); - add(builder.withUrl("/account/user/session/d41d8cd98f00b204e9800998ecf8427e/").withMethodGet().build()); - add(builder.withUrl("/profile/user/session/d41d8cd98f00b204e9800998ecf8427e").withMethodGet().build()); - add(builder.withUrl("/profile/user/session/d41d8cd98f00b204e9800998ecf8427e/").withMethodGet().build()); - }}; + final List assertingRequests = new LinkedList() { + { + add(builder.withUrl("/account/user/session/d41d8cd98f00b204e9800998ecf8427e") + .withMethodGet() + .build()); + add(builder.withUrl("/account/user/session/d41d8cd98f00b204e9800998ecf8427e/") + .withMethodGet() + .build()); + add(builder.withUrl("/profile/user/session/d41d8cd98f00b204e9800998ecf8427e") + .withMethodGet() + .build()); + add(builder.withUrl("/profile/user/session/d41d8cd98f00b204e9800998ecf8427e/") + .withMethodGet() + .build()); + } + }; for (final StubRequest assertingRequest : assertingRequests) { assertThat(assertingRequest).isEqualTo(expectedRequest); } } - @Test - public void stubbedRequestNotEqualsAssertingRequest_WhenUrlRegexified_ButBadAssertionUrlConfigured() throws Exception { + public void stubbedRequestNotEqualsAssertingRequest_WhenUrlRegexified_ButBadAssertionUrlConfigured() + throws Exception { final String url = "^/[a-z]{3}/[0-9]+/?$"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/abcm/12345/").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/abcm/12345/").withMethodGet().build(); assertThat(assertingRequest).isNotEqualTo(expectedRequest); } - @Test - public void stubbedRequestEqualsAssertingRequest_WhenComplexUrlRegexified_ButGoodAssertionUrlConfigured() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenComplexUrlRegexified_ButGoodAssertionUrlConfigured() + throws Exception { final String url = "^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+$"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final List assertingRequests = new LinkedList() {{ - add(builder.withUrl("/abc-efg/12/KM/jhgjkhg234234l2").withMethodGet().build()); - add(builder.withUrl("/abc-efg/12/KM/23423").withMethodGet().build()); - add(builder.withUrl("/aaa-aaa/00/AA/qwerty").withMethodGet().build()); - }}; + final List assertingRequests = new LinkedList() { + { + add(builder.withUrl("/abc-efg/12/KM/jhgjkhg234234l2") + .withMethodGet() + .build()); + add(builder.withUrl("/abc-efg/12/KM/23423").withMethodGet().build()); + add(builder.withUrl("/aaa-aaa/00/AA/qwerty").withMethodGet().build()); + } + }; for (final StubRequest assertingRequest : assertingRequests) { assertThat(assertingRequest).isEqualTo(expectedRequest); @@ -1555,20 +1607,25 @@ public void stubbedRequestEqualsAssertingRequest_WhenComplexUrlRegexified_ButGoo } @Test - public void stubbedRequestNotEqualsAssertingRequest_WhenComplexUrlRegexified_ButBadAssertionUrlConfigured() throws Exception { + public void stubbedRequestNotEqualsAssertingRequest_WhenComplexUrlRegexified_ButBadAssertionUrlConfigured() + throws Exception { final String url = "^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+$"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final List assertingRequests = new LinkedList() {{ - add(builder.withUrl("/abca-efg/12/KM/jhgjkhg234234l2").withMethodGet().build()); - add(builder.withUrl("/abcefg/12/KM/23423").withMethodGet().build()); - add(builder.withUrl("/aaa-aaa/00/Af/qwerty").withMethodGet().build()); - add(builder.withUrl("/aaa-aaa/00/AA/qwerTy").withMethodGet().build()); - add(builder.withUrl("/aaa-aaa/009/AA/qwerty").withMethodGet().build()); - add(builder.withUrl("/AAA-AAA/00/AA/qwerty").withMethodGet().build()); - }}; + final List assertingRequests = new LinkedList() { + { + add(builder.withUrl("/abca-efg/12/KM/jhgjkhg234234l2") + .withMethodGet() + .build()); + add(builder.withUrl("/abcefg/12/KM/23423").withMethodGet().build()); + add(builder.withUrl("/aaa-aaa/00/Af/qwerty").withMethodGet().build()); + add(builder.withUrl("/aaa-aaa/00/AA/qwerTy").withMethodGet().build()); + add(builder.withUrl("/aaa-aaa/009/AA/qwerty").withMethodGet().build()); + add(builder.withUrl("/AAA-AAA/00/AA/qwerty").withMethodGet().build()); + } + }; for (final StubRequest assertingRequest : assertingRequests) { assertThat(assertingRequest).isNotEqualTo(expectedRequest); @@ -1581,7 +1638,9 @@ public void stubbedRequestShouldReturnEmptyRegexGroup_WhenValidRegexHasNoMatcher final String url = "^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+$"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/abc-efg/12/KM/jhgjkhg234234l2").withMethodGet().build(); + final StubRequest assertingRequest = builder.withUrl("/abc-efg/12/KM/jhgjkhg234234l2") + .withMethodGet() + .build(); final boolean equals = assertingRequest.equals(expectedRequest); assertThat(equals).isTrue(); @@ -1595,13 +1654,16 @@ public void stubbedRequestShouldReturnOneRegexGroup_WhenValidRegexHasMatcherGrou final String url = "^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/([a-z0-9]+)$"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/abc-efg/12/KM/jhgjkhg234234l2").withMethodGet().build(); + final StubRequest assertingRequest = builder.withUrl("/abc-efg/12/KM/jhgjkhg234234l2") + .withMethodGet() + .build(); final boolean equals = assertingRequest.equals(expectedRequest); assertThat(equals).isTrue(); assertThat(assertingRequest.getRegexGroups().keySet().size()).isEqualTo(2); assertThat(assertingRequest.getRegexGroups().values().size()).isEqualTo(2); - assertThat(assertingRequest.getRegexGroups().toString()).isEqualTo("{url.0=/abc-efg/12/KM/jhgjkhg234234l2, url.1=jhgjkhg234234l2}"); + assertThat(assertingRequest.getRegexGroups().toString()) + .isEqualTo("{url.0=/abc-efg/12/KM/jhgjkhg234234l2, url.1=jhgjkhg234234l2}"); } @Test @@ -1610,22 +1672,27 @@ public void stubbedRequestShouldReturnMultipleRegexGroups_WhenValidRegexHasMatch final String url = "^/([a-z]{3}-[a-z]{3})/[0-9]{2}/[A-Z]{2}/([a-z0-9]+)$"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/abc-efg/12/KM/jhgjkhg234234l2").withMethodGet().build(); + final StubRequest assertingRequest = builder.withUrl("/abc-efg/12/KM/jhgjkhg234234l2") + .withMethodGet() + .build(); final boolean equals = assertingRequest.equals(expectedRequest); assertThat(equals).isTrue(); assertThat(assertingRequest.getRegexGroups().keySet().size()).isEqualTo(3); assertThat(assertingRequest.getRegexGroups().values().size()).isEqualTo(3); - assertThat(assertingRequest.getRegexGroups().toString()).isEqualTo("{url.0=/abc-efg/12/KM/jhgjkhg234234l2, url.1=abc-efg, url.2=jhgjkhg234234l2}"); + assertThat(assertingRequest.getRegexGroups().toString()) + .isEqualTo("{url.0=/abc-efg/12/KM/jhgjkhg234234l2, url.1=abc-efg, url.2=jhgjkhg234234l2}"); } @Test - public void stubbedRequestShouldReturnMultipleRegexGroups_WhenRegexHasCapturingGroupWhichIsAlsoFullRegex() throws Exception { + public void stubbedRequestShouldReturnMultipleRegexGroups_WhenRegexHasCapturingGroupWhichIsAlsoFullRegex() + throws Exception { final String url = "^([a-z]{3})$"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("abc").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("abc").withMethodGet().build(); final boolean equals = assertingRequest.equals(expectedRequest); assertThat(equals).isTrue(); @@ -1635,39 +1702,53 @@ public void stubbedRequestShouldReturnMultipleRegexGroups_WhenRegexHasCapturingG } @Test - public void stubbedRequestShouldReturnMultipleRegexGroups_WhenValidRegexHasCapturingGroupsInMultipleProperties() throws Exception { + public void stubbedRequestShouldReturnMultipleRegexGroups_WhenValidRegexHasCapturingGroupsInMultipleProperties() + throws Exception { final String url = "^/([a-z]{3}-[a-z]{3})/[0-9]{2}/[A-Z]{2}/([a-z0-9]+)$"; - final StubRequest expectedRequest = - builder.withUrl(url).withMethodGet().withQuery("paramOne", "(\\d{1,})").build(); - final StubRequest assertingRequest = - builder.withUrl("/abc-efg/12/KM/jhgjkhg234234l2").withQuery("paramOne", "12345").withMethodGet().build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withQuery("paramOne", "(\\d{1,})") + .build(); + final StubRequest assertingRequest = builder.withUrl("/abc-efg/12/KM/jhgjkhg234234l2") + .withQuery("paramOne", "12345") + .withMethodGet() + .build(); final boolean equals = assertingRequest.equals(expectedRequest); assertThat(equals).isTrue(); assertThat(assertingRequest.getRegexGroups().keySet().size()).isEqualTo(5); assertThat(assertingRequest.getRegexGroups().values().size()).isEqualTo(5); - assertThat(assertingRequest.getRegexGroups() - .toString()).isEqualTo("{query.paramOne.0=12345, query.paramOne.1=12345, url.0=/abc-efg/12/KM/jhgjkhg234234l2, url.1=abc-efg, url.2=jhgjkhg234234l2}"); + assertThat(assertingRequest.getRegexGroups().toString()) + .isEqualTo( + "{query.paramOne.0=12345, query.paramOne.1=12345, url.0=/abc-efg/12/KM/jhgjkhg234234l2, url.1=abc-efg, url.2=jhgjkhg234234l2}"); } @Test - public void stubbedRequestShouldReturnMultipleRegexGroups_WhenValidRegexHasCapturingGroupsInQuery() throws Exception { + public void stubbedRequestShouldReturnMultipleRegexGroups_WhenValidRegexHasCapturingGroupsInQuery() + throws Exception { final String url = "^/([a-z]{3}-[a-z]{3})/[0-9]{2}/[A-Z]{2}/([a-z0-9]+)$"; - final StubRequest expectedRequest = - builder.withUrl(url).withMethodGet().withQuery("paramOne", "(\\d{1,})").withQuery("paramTwo", "([A-Z]{5})").build(); - final StubRequest assertingRequest = - builder.withUrl("/abc-efg/12/KM/jhgjkhg234234l2").withQuery("paramOne", "12345").withQuery("paramTwo", "ABCDE").withMethodGet().build(); + final StubRequest expectedRequest = builder.withUrl(url) + .withMethodGet() + .withQuery("paramOne", "(\\d{1,})") + .withQuery("paramTwo", "([A-Z]{5})") + .build(); + final StubRequest assertingRequest = builder.withUrl("/abc-efg/12/KM/jhgjkhg234234l2") + .withQuery("paramOne", "12345") + .withQuery("paramTwo", "ABCDE") + .withMethodGet() + .build(); final boolean equals = assertingRequest.equals(expectedRequest); assertThat(equals).isTrue(); assertThat(assertingRequest.getRegexGroups().keySet().size()).isEqualTo(7); assertThat(assertingRequest.getRegexGroups().values().size()).isEqualTo(7); - assertThat(assertingRequest.getRegexGroups() - .toString()).isEqualTo("{query.paramOne.0=12345, query.paramOne.1=12345, query.paramTwo.0=ABCDE, query.paramTwo.1=ABCDE, url.0=/abc-efg/12/KM/jhgjkhg234234l2, url.1=abc-efg, url.2=jhgjkhg234234l2}"); + assertThat(assertingRequest.getRegexGroups().toString()) + .isEqualTo( + "{query.paramOne.0=12345, query.paramOne.1=12345, query.paramTwo.0=ABCDE, query.paramTwo.1=ABCDE, url.0=/abc-efg/12/KM/jhgjkhg234234l2, url.1=abc-efg, url.2=jhgjkhg234234l2}"); } @Test @@ -1675,8 +1756,7 @@ public void stubbedRequestShouldReturnMultipleRegexGroups_WhenValidRegexHasOneSu final String url = "^/([a-z]{3}-([a-z]{3}))/([a-z0-9]+)$"; - final StubRequest expectedRequest = - builder.withUrl(url).withMethodGet().build(); + final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); final StubRequest assertingRequest = builder.withUrl("/abc-efg/jhgjkhg234234l2").withMethodGet().build(); @@ -1684,17 +1764,17 @@ public void stubbedRequestShouldReturnMultipleRegexGroups_WhenValidRegexHasOneSu assertThat(equals).isTrue(); assertThat(assertingRequest.getRegexGroups().keySet().size()).isEqualTo(4); assertThat(assertingRequest.getRegexGroups().values().size()).isEqualTo(4); - assertThat(assertingRequest.getRegexGroups() - .toString()).isEqualTo("{url.0=/abc-efg/jhgjkhg234234l2, url.1=abc-efg, url.2=efg, url.3=jhgjkhg234234l2}"); + assertThat(assertingRequest.getRegexGroups().toString()) + .isEqualTo("{url.0=/abc-efg/jhgjkhg234234l2, url.1=abc-efg, url.2=efg, url.3=jhgjkhg234234l2}"); } @Test - public void stubbedRequestShouldReturnMultipleRegexGroups_WhenValidRegexHasMultipleSubCapturingGroups() throws Exception { + public void stubbedRequestShouldReturnMultipleRegexGroups_WhenValidRegexHasMultipleSubCapturingGroups() + throws Exception { final String url = "^/(([a-z]{3})-([a-z]{3}))/([a-z0-9]+)$"; - final StubRequest expectedRequest = - builder.withUrl(url).withMethodGet().build(); + final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); final StubRequest assertingRequest = builder.withUrl("/abc-efg/jhgjkhg234234l2").withMethodGet().build(); @@ -1702,32 +1782,38 @@ public void stubbedRequestShouldReturnMultipleRegexGroups_WhenValidRegexHasMulti assertThat(equals).isTrue(); assertThat(assertingRequest.getRegexGroups().keySet().size()).isEqualTo(5); assertThat(assertingRequest.getRegexGroups().values().size()).isEqualTo(5); - assertThat(assertingRequest.getRegexGroups() - .toString()).isEqualTo("{url.0=/abc-efg/jhgjkhg234234l2, url.1=abc-efg, url.2=abc, url.3=efg, url.4=jhgjkhg234234l2}"); + assertThat(assertingRequest.getRegexGroups().toString()) + .isEqualTo( + "{url.0=/abc-efg/jhgjkhg234234l2, url.1=abc-efg, url.2=abc, url.3=efg, url.4=jhgjkhg234234l2}"); } @Test - public void stubbedRequestEqualsAssertingRequest_WhenUrlRegexifiedDoesNotAccommodateForQueryString() throws Exception { + public void stubbedRequestEqualsAssertingRequest_WhenUrlRegexifiedDoesNotAccommodateForQueryString() + throws Exception { final String url = "^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final List assertingRequests = new LinkedList() {{ - add(builder - .withUrl("/abc-efg/12/KM/jhgjkhg234234l2") - .withMethodGet() - .withQuery("paramOne", "valueOne") - .withQuery("paramTwo", "valueTwo").build()); - add(builder.withUrl("/abc-efg/12/KM/23423") - .withMethodGet() - .withQuery("paramOne", "valueOne") - .withQuery("paramTwo", "valueTwo").build()); - add(builder.withUrl("/aaa-aaa/00/AA/qwerty") - .withMethodGet() - .withQuery("paramOne", "valueOne") - .withQuery("paramTwo", "valueTwo").build()); - }}; + final List assertingRequests = new LinkedList() { + { + add(builder.withUrl("/abc-efg/12/KM/jhgjkhg234234l2") + .withMethodGet() + .withQuery("paramOne", "valueOne") + .withQuery("paramTwo", "valueTwo") + .build()); + add(builder.withUrl("/abc-efg/12/KM/23423") + .withMethodGet() + .withQuery("paramOne", "valueOne") + .withQuery("paramTwo", "valueTwo") + .build()); + add(builder.withUrl("/aaa-aaa/00/AA/qwerty") + .withMethodGet() + .withQuery("paramOne", "valueOne") + .withQuery("paramTwo", "valueTwo") + .build()); + } + }; for (final StubRequest assertingRequest : assertingRequests) { assertThat(assertingRequest).isEqualTo(expectedRequest); @@ -1737,25 +1823,30 @@ public void stubbedRequestEqualsAssertingRequest_WhenUrlRegexifiedDoesNotAccommo @Test public void stubbedRequestNotEqualsAssertingRequest_WhenUrlRegexifiedHasQueryString() throws Exception { - final String url = "^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+\\?paramOne=[a-zA-Z]{8}¶mTwo=[a-zA-Z]{8}"; + final String url = + "^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+\\?paramOne=[a-zA-Z]{8}¶mTwo=[a-zA-Z]{8}"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final List assertingRequests = new LinkedList() {{ - add(builder - .withUrl("/abc-efg/12/KM/jhgjkhg234234l2") - .withMethodGet() - .withQuery("paramOne", "wqePwrew") - .withQuery("paramTwo", "valueTwo").build()); - add(builder.withUrl("/abc-efg/12/KM/23423") - .withMethodGet() - .withQuery("paramOne", "valueOne") - .withQuery("paramTwo", "valueTwo").build()); - add(builder.withUrl("/aaa-aaa/00/AA/qwerty") - .withMethodGet() - .withQuery("paramOne", "aaaaaaaa") - .withQuery("paramTwo", "QwErTyUi").build()); - }}; + final List assertingRequests = new LinkedList() { + { + add(builder.withUrl("/abc-efg/12/KM/jhgjkhg234234l2") + .withMethodGet() + .withQuery("paramOne", "wqePwrew") + .withQuery("paramTwo", "valueTwo") + .build()); + add(builder.withUrl("/abc-efg/12/KM/23423") + .withMethodGet() + .withQuery("paramOne", "valueOne") + .withQuery("paramTwo", "valueTwo") + .build()); + add(builder.withUrl("/aaa-aaa/00/AA/qwerty") + .withMethodGet() + .withQuery("paramOne", "aaaaaaaa") + .withQuery("paramTwo", "QwErTyUi") + .build()); + } + }; for (final StubRequest assertingRequest : assertingRequests) { assertThat(assertingRequest).isNotEqualTo(expectedRequest); @@ -1768,23 +1859,28 @@ public void stubbedRequestEqualsAssertingRequest_WhenStaticUrlHasRegexifiedQuery final StubRequest expectedRequest = builder.withUrl("/atom/feed") .withMethodGet() .withQuery("min-results", "\\d+") - .withQuery("max-results", "\\d+").build(); - - final List assertingRequests = new LinkedList() {{ - add(builder - .withUrl("/atom/feed") - .withMethodGet() - .withQuery("min-results", "0") - .withQuery("max-results", "0").build()); - add(builder.withUrl("/atom/feed") - .withMethodGet() - .withQuery("min-results", "1") - .withQuery("max-results", "5").build()); - add(builder.withUrl("/atom/feed") - .withMethodGet() - .withQuery("min-results", "4654645756756") - .withQuery("max-results", "5675675686786786785675464564564").build()); - }}; + .withQuery("max-results", "\\d+") + .build(); + + final List assertingRequests = new LinkedList() { + { + add(builder.withUrl("/atom/feed") + .withMethodGet() + .withQuery("min-results", "0") + .withQuery("max-results", "0") + .build()); + add(builder.withUrl("/atom/feed") + .withMethodGet() + .withQuery("min-results", "1") + .withQuery("max-results", "5") + .build()); + add(builder.withUrl("/atom/feed") + .withMethodGet() + .withQuery("min-results", "4654645756756") + .withQuery("max-results", "5675675686786786785675464564564") + .build()); + } + }; for (final StubRequest assertingRequest : assertingRequests) { assertThat(assertingRequest).isEqualTo(expectedRequest); @@ -1798,21 +1894,25 @@ public void stubbedRequestNotEqualsAssertingRequest_WhenUrlRegexifiedWithStaticQ final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final List assertingRequests = new LinkedList() {{ - add(builder - .withUrl("/abc-efg/12/KM/jhgjkhg234234l2") - .withMethodGet() - .withQuery("paramOne", "valueOne") - .withQuery("paramTwo", "valueTwo").build()); - add(builder.withUrl("/abc-efg/12/KM/23423") - .withMethodGet() - .withQuery("paramOne", "valueOne") - .withQuery("paramTwo", "valueTwo").build()); - add(builder.withUrl("/aaa-aaa/00/AA/qwerty") - .withMethodGet() - .withQuery("paramOne", "valueOne") - .withQuery("paramTwo", "valueTwo").build()); - }}; + final List assertingRequests = new LinkedList() { + { + add(builder.withUrl("/abc-efg/12/KM/jhgjkhg234234l2") + .withMethodGet() + .withQuery("paramOne", "valueOne") + .withQuery("paramTwo", "valueTwo") + .build()); + add(builder.withUrl("/abc-efg/12/KM/23423") + .withMethodGet() + .withQuery("paramOne", "valueOne") + .withQuery("paramTwo", "valueTwo") + .build()); + add(builder.withUrl("/aaa-aaa/00/AA/qwerty") + .withMethodGet() + .withQuery("paramOne", "valueOne") + .withQuery("paramTwo", "valueTwo") + .build()); + } + }; for (final StubRequest assertingRequest : assertingRequests) { assertThat(assertingRequest).isNotEqualTo(expectedRequest); @@ -1820,27 +1920,34 @@ public void stubbedRequestNotEqualsAssertingRequest_WhenUrlRegexifiedWithStaticQ } @Test - public void stubbedRequestNotEqualsAssertingRequest_WhenUrlRegexifiedAccomodatesForQueryString_ButBadAssertionUrlConfigured() throws Exception { + public void + stubbedRequestNotEqualsAssertingRequest_WhenUrlRegexifiedAccomodatesForQueryString_ButBadAssertionUrlConfigured() + throws Exception { - final String url = "^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+\\?paramOne=[a-zA-Z]{8}¶mTwo=[a-zA-Z]{8}"; + final String url = + "^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+\\?paramOne=[a-zA-Z]{8}¶mTwo=[a-zA-Z]{8}"; final StubRequest expectedRequest = builder.withUrl(url).withMethodGet().build(); - final List assertingRequests = new LinkedList() {{ - add(builder - .withUrl("/abc-efg/12/KM/jhgjkhg234234l2") - .withMethodGet() - .withQuery("paramSix", "wqePwrew") - .withQuery("paramTwo", "valueTwo").build()); - add(builder.withUrl("/abc-efg/12/KM/23423") - .withMethodGet() - .withQuery("paramOne", "12345678") - .withQuery("paramTwo", "valueTwo").build()); - add(builder.withUrl("/aaa-aaa/00/AA/qwerty") - .withMethodGet() - .withQuery("paramOne", "aaa7aaaa") - .withQuery("paramTwo", "QwErTyUi").build()); - }}; + final List assertingRequests = new LinkedList() { + { + add(builder.withUrl("/abc-efg/12/KM/jhgjkhg234234l2") + .withMethodGet() + .withQuery("paramSix", "wqePwrew") + .withQuery("paramTwo", "valueTwo") + .build()); + add(builder.withUrl("/abc-efg/12/KM/23423") + .withMethodGet() + .withQuery("paramOne", "12345678") + .withQuery("paramTwo", "valueTwo") + .build()); + add(builder.withUrl("/aaa-aaa/00/AA/qwerty") + .withMethodGet() + .withQuery("paramOne", "aaa7aaaa") + .withQuery("paramTwo", "QwErTyUi") + .build()); + } + }; for (final StubRequest assertingRequest : assertingRequests) { assertThat(assertingRequest).isNotEqualTo(expectedRequest); @@ -1849,14 +1956,16 @@ public void stubbedRequestNotEqualsAssertingRequest_WhenUrlRegexifiedAccomodates @Test public void shouldfindStubRequestNotEqual_WhenComparedToNull() throws Exception { - final StubRequest expectedRequest = builder.withUrl("/products/12345/").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("/products/12345/").withMethodGet().build(); assertThat(expectedRequest).isNotEqualTo(null); } @Test public void shouldfindStubRequestNotEqual_WhenComparedToDifferentInstanceClass() throws Exception { - final StubRequest expectedRequest = builder.withUrl("/products/12345/").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("/products/12345/").withMethodGet().build(); final Object assertingObject = StubResponse.okResponse(); final boolean assertionResult = expectedRequest.equals(assertingObject); @@ -1865,7 +1974,8 @@ public void shouldfindStubRequestNotEqual_WhenComparedToDifferentInstanceClass() @Test public void shouldfindStubRequestEqual_WhenComparedToSameInstanceClass() throws Exception { - final StubRequest expectedRequest = builder.withUrl("/products/12345/").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("/products/12345/").withMethodGet().build(); final Object assertingObject = builder.build(); final boolean assertionResult = assertingObject.equals(expectedRequest); @@ -1874,8 +1984,10 @@ public void shouldfindStubRequestEqual_WhenComparedToSameInstanceClass() throws @Test public void shouldfindStubRequestEqual_WhenComparedToDifferentObjectWithSameProperties() throws Exception { - final StubRequest expectedRequest = builder.withUrl("/products/12345/").withMethodGet().build(); - final StubRequest assertingRequest = builder.withUrl("/products/12345/").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("/products/12345/").withMethodGet().build(); + final StubRequest assertingRequest = + builder.withUrl("/products/12345/").withMethodGet().build(); final boolean assertionResultOne = assertingRequest.equals(expectedRequest); final boolean assertionResultTwo = expectedRequest.equals(assertingRequest); @@ -1886,12 +1998,12 @@ public void shouldfindStubRequestEqual_WhenComparedToDifferentObjectWithSameProp @Test public void shouldfindStubRequestEqual_WhenComparedToSameIdentity() throws Exception { - final StubRequest expectedRequest = builder.withUrl("/products/12345/").withMethodGet().build(); + final StubRequest expectedRequest = + builder.withUrl("/products/12345/").withMethodGet().build(); assertThat(expectedRequest).isEqualTo(expectedRequest); } - @Test public void shouldFindTwoHashCodesEqual_WhenTwoRequestAreTheSame() throws Exception { @@ -1907,31 +2019,31 @@ public void shouldFindTwoHashCodesEqual_WhenTwoRequestAreTheSame() throws Except final String url = "/invoice/123"; final String postBody = "this is a post body"; - final StubRequest requestOne = - builder.withUrl(url) - .withMethodGet() - .withMethodPost() - .withMethodPut() - .withPost(postBody) - .withFile(FileUtils.tempFileFromString("bytes")) - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue) - .withApplicationXmlContentType() - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage).build(); - - final StubRequest requestTwo = - builder.withUrl(url) - .withMethodGet() - .withMethodPost() - .withMethodPut() - .withPost(postBody) - .withFile(FileUtils.tempFileFromString("bytes")) - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue) - .withApplicationXmlContentType() - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage).build(); + final StubRequest requestOne = builder.withUrl(url) + .withMethodGet() + .withMethodPost() + .withMethodPut() + .withPost(postBody) + .withFile(FileUtils.tempFileFromString("bytes")) + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .withApplicationXmlContentType() + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .build(); + + final StubRequest requestTwo = builder.withUrl(url) + .withMethodGet() + .withMethodPost() + .withMethodPut() + .withPost(postBody) + .withFile(FileUtils.tempFileFromString("bytes")) + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .withApplicationXmlContentType() + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .build(); assertThat(requestOne.hashCode()).isEqualTo(requestTwo.hashCode()); } @@ -1951,29 +2063,29 @@ public void shouldNotFindTwoHashCodesEqual_WhenTwoRequestHaveDifferentAmdNullPos final String url = "/invoice/123"; final String postBody = "this is a post body"; - final StubRequest requestOne = - builder.withUrl(url) - .withMethodGet() - .withMethodPost() - .withMethodPut() - .withPost(null) - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue) - .withApplicationXmlContentType() - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage).build(); - - final StubRequest requestTwo = - builder.withUrl(url) - .withMethodGet() - .withMethodPost() - .withMethodPut() - .withPost(postBody) - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue) - .withApplicationXmlContentType() - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage).build(); + final StubRequest requestOne = builder.withUrl(url) + .withMethodGet() + .withMethodPost() + .withMethodPut() + .withPost(null) + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .withApplicationXmlContentType() + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .build(); + + final StubRequest requestTwo = builder.withUrl(url) + .withMethodGet() + .withMethodPost() + .withMethodPut() + .withPost(postBody) + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .withApplicationXmlContentType() + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .build(); assertThat(requestOne.hashCode()).isNotEqualTo(requestTwo.hashCode()); } @@ -1993,29 +2105,29 @@ public void shouldNotFindTwoHashCodesEqual_WhenTwoRequestHaveDifferentHeaderValu final String url = "/invoice/123"; final String postBody = "this is a post body"; - final StubRequest requestOne = - builder.withUrl(url) - .withMethodGet() - .withMethodPost() - .withMethodPut() - .withPost(postBody) - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue) - .withApplicationXmlContentType() - .withHeaderContentLength(contentLength) - .withHeaderContentLanguage(contentLanguage).build(); - - final StubRequest requestTwo = - builder.withUrl(url) - .withMethodGet() - .withMethodPost() - .withMethodPut() - .withPost(postBody) - .withQuery(paramOne, paramOneValue) - .withQuery(paramTwo, paramTwoValue) - .withApplicationXmlContentType() - .withHeaderContentLength("31") - .withHeaderContentLanguage(contentLanguage).build(); + final StubRequest requestOne = builder.withUrl(url) + .withMethodGet() + .withMethodPost() + .withMethodPut() + .withPost(postBody) + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .withApplicationXmlContentType() + .withHeaderContentLength(contentLength) + .withHeaderContentLanguage(contentLanguage) + .build(); + + final StubRequest requestTwo = builder.withUrl(url) + .withMethodGet() + .withMethodPost() + .withMethodPut() + .withPost(postBody) + .withQuery(paramOne, paramOneValue) + .withQuery(paramTwo, paramTwoValue) + .withApplicationXmlContentType() + .withHeaderContentLength("31") + .withHeaderContentLanguage(contentLanguage) + .build(); assertThat(requestOne.hashCode()).isNotEqualTo(requestTwo.hashCode()); } @@ -2023,13 +2135,9 @@ public void shouldNotFindTwoHashCodesEqual_WhenTwoRequestHaveDifferentHeaderValu @Test public void shouldFindTwoHashCodesEqual_WhenTwoRequestHaveMethodAndUrlNull() throws Exception { - final StubRequest requestOne = - builder.withUrl(null) - .withMethod(null).build(); + final StubRequest requestOne = builder.withUrl(null).withMethod(null).build(); - final StubRequest requestTwo = - builder.withUrl(null) - .withMethod(null).build(); + final StubRequest requestTwo = builder.withUrl(null).withMethod(null).build(); assertThat(requestOne.hashCode()).isEqualTo(requestTwo.hashCode()); } @@ -2037,13 +2145,9 @@ public void shouldFindTwoHashCodesEqual_WhenTwoRequestHaveMethodAndUrlNull() thr @Test public void shouldFindTwoHashCodesEqual_WhenTwoRequestHaveUrlNull() throws Exception { - final StubRequest requestOne = - builder.withUrl(null) - .withMethodGet().build(); + final StubRequest requestOne = builder.withUrl(null).withMethodGet().build(); - final StubRequest requestTwo = - builder.withUrl(null) - .withMethodGet().build(); + final StubRequest requestTwo = builder.withUrl(null).withMethodGet().build(); assertThat(requestOne.hashCode()).isEqualTo(requestTwo.hashCode()); } @@ -2051,25 +2155,23 @@ public void shouldFindTwoHashCodesEqual_WhenTwoRequestHaveUrlNull() throws Excep @Test public void shouldMatchExpectedToStringOutput_WhenActualRequestHasTheSameOutput() throws Exception { - final StubRequest actualRequest = - builder.withUrl("/invoice/123") - .withMethodGet() - .withMethodPost() - .withMethodPut() - .withPost("this is a post body") - .withQuery("paramOne", "paramOneValue") - .withQuery("paramTwo", "paramTwoValue") - .withHeader("headerThree", "headerThreeValue") - .withHeader("headerTwo", "headerTwoValue") - .withHeader("headerOne", "headerOneValue").build(); - - - final String expectedToStringOutput = "StubRequest{" + - "url=/invoice/123, " + - "method=[GET, POST, PUT], " + - "post=this is a post body, " + - "query={paramOne=paramOneValue, paramTwo=paramTwoValue}, " + - "headers={headerthree=headerThreeValue, headertwo=headerTwoValue, headerone=headerOneValue}}"; + final StubRequest actualRequest = builder.withUrl("/invoice/123") + .withMethodGet() + .withMethodPost() + .withMethodPut() + .withPost("this is a post body") + .withQuery("paramOne", "paramOneValue") + .withQuery("paramTwo", "paramTwoValue") + .withHeader("headerThree", "headerThreeValue") + .withHeader("headerTwo", "headerTwoValue") + .withHeader("headerOne", "headerOneValue") + .build(); + + final String expectedToStringOutput = "StubRequest{" + "url=/invoice/123, " + + "method=[GET, POST, PUT], " + + "post=this is a post body, " + + "query={paramOne=paramOneValue, paramTwo=paramTwoValue}, " + + "headers={headerthree=headerThreeValue, headertwo=headerTwoValue, headerone=headerOneValue}}"; assertThat(actualRequest.toString()).isEqualTo(expectedToStringOutput); } @@ -2077,23 +2179,22 @@ public void shouldMatchExpectedToStringOutput_WhenActualRequestHasTheSameOutput( @Test public void shouldMatchExpectedToStringOutput_WhenActualRequestHasNullBody() throws Exception { - final StubRequest actualRequest = - builder.withUrl("/invoice/123") - .withMethodGet() - .withMethodPost() - .withMethodPut() - .withPost(null) - .withQuery("paramOne", "paramOneValue") - .withQuery("paramTwo", "paramTwoValue") - .withHeader("headerThree", "headerThreeValue") - .withHeader("headerTwo", "headerTwoValue") - .withHeader("headerOne", "headerOneValue").build(); - - final String expectedToStringOutput = "StubRequest{" + - "url=/invoice/123, " + - "method=[GET, POST, PUT], " + - "query={paramOne=paramOneValue, paramTwo=paramTwoValue}, " + - "headers={headerthree=headerThreeValue, headertwo=headerTwoValue, headerone=headerOneValue}}"; + final StubRequest actualRequest = builder.withUrl("/invoice/123") + .withMethodGet() + .withMethodPost() + .withMethodPut() + .withPost(null) + .withQuery("paramOne", "paramOneValue") + .withQuery("paramTwo", "paramTwoValue") + .withHeader("headerThree", "headerThreeValue") + .withHeader("headerTwo", "headerTwoValue") + .withHeader("headerOne", "headerOneValue") + .build(); + + final String expectedToStringOutput = "StubRequest{" + "url=/invoice/123, " + + "method=[GET, POST, PUT], " + + "query={paramOne=paramOneValue, paramTwo=paramTwoValue}, " + + "headers={headerthree=headerThreeValue, headertwo=headerTwoValue, headerone=headerOneValue}}"; assertThat(actualRequest.toString()).isEqualTo(expectedToStringOutput); } @@ -2101,23 +2202,22 @@ public void shouldMatchExpectedToStringOutput_WhenActualRequestHasNullBody() thr @Test public void shouldMatchExpectedToStringOutput_WhenActualRequestHasNullHeaderValue() throws Exception { - final StubRequest actualRequest = - builder.withUrl("/invoice/123") - .withMethodGet() - .withMethodPost() - .withMethodPut() - .withPost(null) - .withQuery("paramOne", "paramOneValue") - .withQuery("paramTwo", "paramTwoValue") - .withHeader("headerThree", "headerThreeValue") - .withHeader("headerTwo", "headerTwoValue") - .withHeader("headerOne", null).build(); - - final String expectedToStringOutput = "StubRequest{" + - "url=/invoice/123, " + - "method=[GET, POST, PUT], " + - "query={paramOne=paramOneValue, paramTwo=paramTwoValue}, " + - "headers={headerthree=headerThreeValue, headertwo=headerTwoValue, headerone=null}}"; + final StubRequest actualRequest = builder.withUrl("/invoice/123") + .withMethodGet() + .withMethodPost() + .withMethodPut() + .withPost(null) + .withQuery("paramOne", "paramOneValue") + .withQuery("paramTwo", "paramTwoValue") + .withHeader("headerThree", "headerThreeValue") + .withHeader("headerTwo", "headerTwoValue") + .withHeader("headerOne", null) + .build(); + + final String expectedToStringOutput = "StubRequest{" + "url=/invoice/123, " + + "method=[GET, POST, PUT], " + + "query={paramOne=paramOneValue, paramTwo=paramTwoValue}, " + + "headers={headerthree=headerThreeValue, headertwo=headerTwoValue, headerone=null}}"; assertThat(actualRequest.toString()).isEqualTo(expectedToStringOutput); } @@ -2126,16 +2226,10 @@ public void shouldMatchExpectedToStringOutput_WhenActualRequestHasNullHeaderValu public void shouldMatchExpectedToStringOutput_WhenActualRequestHasAllNullFields() throws Exception { final StubRequest actualRequest = - builder.withUrl(null) - .withMethod(null) - .withPost(null).build(); + builder.withUrl(null).withMethod(null).withPost(null).build(); - - final String expectedToStringOutput = "StubRequest{" + - "url=null, " + - "method=[], " + - "query={}, " + - "headers={}}"; + final String expectedToStringOutput = + "StubRequest{" + "url=null, " + "method=[], " + "query={}, " + "headers={}}"; assertThat(actualRequest.toString()).isEqualTo(expectedToStringOutput); } @@ -2143,19 +2237,17 @@ public void shouldMatchExpectedToStringOutput_WhenActualRequestHasAllNullFields( @Test public void shouldFindPostNotStubbed_WhenPostNullAndMethodGet() throws Exception { final StubRequest stubRequest = - builder.withUrl("fssefewf") - .withMethod("GET") - .withPost(null).build(); + builder.withUrl("fssefewf").withMethod("GET").withPost(null).build(); assertThat(stubRequest.isRequestBodyStubbed()).isFalse(); } @Test public void shouldFindPostNotStubbed_WhenPostStubbedAndMethodGet() throws Exception { - final StubRequest stubRequest = - builder.withUrl("fssefewf") - .withMethod("GET") - .withPost("stubbed").build(); + final StubRequest stubRequest = builder.withUrl("fssefewf") + .withMethod("GET") + .withPost("stubbed") + .build(); assertThat(stubRequest.isRequestBodyStubbed()).isFalse(); } @@ -2163,9 +2255,7 @@ public void shouldFindPostNotStubbed_WhenPostStubbedAndMethodGet() throws Except @Test public void shouldFindPostNotStubbed_WhenPostNullAndMethodPut() throws Exception { final StubRequest stubRequest = - builder.withUrl("fssefewf") - .withMethod("PUT") - .withPost(null).build(); + builder.withUrl("fssefewf").withMethod("PUT").withPost(null).build(); assertThat(stubRequest.isRequestBodyStubbed()).isFalse(); } @@ -2173,39 +2263,37 @@ public void shouldFindPostNotStubbed_WhenPostNullAndMethodPut() throws Exception @Test public void shouldFindPostNotStubbed_WhenPostEmptyAndMethodPut() throws Exception { final StubRequest stubRequest = - builder.withUrl("fssefewf") - .withMethod("PUT") - .withPost("").build(); + builder.withUrl("fssefewf").withMethod("PUT").withPost("").build(); assertThat(stubRequest.isRequestBodyStubbed()).isFalse(); } @Test public void shouldFindRequestBodyStubbed_WhenPostStubbedAndMethodPut() throws Exception { - final StubRequest stubRequest = - builder.withUrl("fssefewf") - .withMethod("PUT") - .withPost("stubbed").build(); + final StubRequest stubRequest = builder.withUrl("fssefewf") + .withMethod("PUT") + .withPost("stubbed") + .build(); assertThat(stubRequest.isRequestBodyStubbed()).isTrue(); } @Test public void shouldFindRequestBodyStubbed_WhenPostStubbedAndMethodPatch() throws Exception { - final StubRequest stubRequest = - builder.withUrl("fssefewf") - .withMethod("PATCH") - .withPost("stubbed").build(); + final StubRequest stubRequest = builder.withUrl("fssefewf") + .withMethod("PATCH") + .withPost("stubbed") + .build(); assertThat(stubRequest.isRequestBodyStubbed()).isTrue(); } @Test public void shouldFindRequestBodyStubbed_WhenFileStubbedAndMethodPatch() throws Exception { - final StubRequest stubRequest = - builder.withUrl("fssefewf") - .withMethod("PATCH") - .withFile(FileUtils.tempFileFromString("hello")).build(); + final StubRequest stubRequest = builder.withUrl("fssefewf") + .withMethod("PATCH") + .withFile(FileUtils.tempFileFromString("hello")) + .build(); assertThat(stubRequest.isRequestBodyStubbed()).isTrue(); } @@ -2213,8 +2301,7 @@ public void shouldFindRequestBodyStubbed_WhenFileStubbedAndMethodPatch() throws @Test public void shouldFindRequestBodyNotStubbed_WhenJustMethodPatch() throws Exception { final StubRequest stubRequest = - builder.withUrl("fssefewf") - .withMethod("PATCH").build(); + builder.withUrl("fssefewf").withMethod("PATCH").build(); assertThat(stubRequest.isRequestBodyStubbed()).isFalse(); } @@ -2222,9 +2309,7 @@ public void shouldFindRequestBodyNotStubbed_WhenJustMethodPatch() throws Excepti @Test public void shouldFindPostNotStubbed_WhenPostNullAndMethodPost() throws Exception { final StubRequest stubRequest = - builder.withUrl("fssefewf") - .withMethod("POST") - .withPost(null).build(); + builder.withUrl("fssefewf").withMethod("POST").withPost(null).build(); assertThat(stubRequest.isRequestBodyStubbed()).isFalse(); } @@ -2232,40 +2317,37 @@ public void shouldFindPostNotStubbed_WhenPostNullAndMethodPost() throws Exceptio @Test public void shouldFindPostNotStubbed_WhenPostEmptyAndMethodPost() throws Exception { final StubRequest stubRequest = - builder.withUrl("fssefewf") - .withMethod("POST") - .withPost("").build(); + builder.withUrl("fssefewf").withMethod("POST").withPost("").build(); assertThat(stubRequest.isRequestBodyStubbed()).isFalse(); } @Test public void shouldFindRequestBodyStubbed_WhenPostStubbedAndMethodPost() throws Exception { - final StubRequest stubRequest = - builder.withUrl("fssefewf") - .withMethod("POST") - .withPost("stubbed").build(); + final StubRequest stubRequest = builder.withUrl("fssefewf") + .withMethod("POST") + .withPost("stubbed") + .build(); assertThat(stubRequest.isRequestBodyStubbed()).isTrue(); } @Test public void shouldGetStubbedRequestBodyTokenNameAsPost() throws Exception { - final StubRequest stubRequest = - builder.withUrl("fssefewf") - .withMethod("GET") - .withPost("") - .build(); + final StubRequest stubRequest = builder.withUrl("fssefewf") + .withMethod("GET") + .withPost("") + .build(); assertThat(stubRequest.getStubbedRequestBodyTokenName()).isEqualTo("post"); } @Test public void shouldGetStubbedRequestBodyTokenNameAsFile() throws Exception { - final StubRequest stubRequest = - builder.withUrl("fssefewf") - .withMethod("GET") - .withFile(FileUtils.tempFileFromString("hello")).build(); + final StubRequest stubRequest = builder.withUrl("fssefewf") + .withMethod("GET") + .withFile(FileUtils.tempFileFromString("hello")) + .build(); assertThat(stubRequest.getStubbedRequestBodyTokenName()).isEqualTo("file"); } diff --git a/src/test/java/io/github/azagniotov/stubby4j/stubs/StubResponseBuilderTest.java b/src/test/java/io/github/azagniotov/stubby4j/stubs/StubResponseBuilderTest.java index bc0df3389..237211a49 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/stubs/StubResponseBuilderTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/stubs/StubResponseBuilderTest.java @@ -1,18 +1,32 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.utils.FileUtils.tempFileFromString; +import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.BODY; import io.github.azagniotov.stubby4j.utils.StringUtils; +import java.io.File; +import java.util.Optional; import org.eclipse.jetty.http.HttpStatus.Code; import org.junit.Before; import org.junit.Test; -import java.io.File; -import java.util.Optional; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.utils.FileUtils.tempFileFromString; -import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.BODY; - public class StubResponseBuilderTest { private StubResponse.Builder builder; @@ -50,14 +64,14 @@ public void shouldReturnDefaultHttpStatusCode_WhenStatusFieldNull() throws Excep @Test public void shouldReturnRespectiveHttpStatusCode_WhenStatusFieldSet() throws Exception { - assertThat(Code.CREATED).isEqualTo(builder.withHttpStatusCode(Code.CREATED).getHttpStatusCode()); + assertThat(Code.CREATED) + .isEqualTo(builder.withHttpStatusCode(Code.CREATED).getHttpStatusCode()); } @Test public void shouldReturnBody_WhenFileIsNull() throws Exception { - final StubResponse stubResponse = builder - .withHttpStatusCode(Code.OK) + final StubResponse stubResponse = builder.withHttpStatusCode(Code.OK) .withBody("this is some body") .build(); @@ -68,8 +82,7 @@ public void shouldReturnBody_WhenFileIsNull() throws Exception { @Test public void shouldReturnBody_WhenFileIsEmpty() throws Exception { - final StubResponse stubResponse = builder - .withHttpStatusCode(Code.OK) + final StubResponse stubResponse = builder.withHttpStatusCode(Code.OK) .withBody("this is some body") .withFile(File.createTempFile("tmp", "tmp")) .build(); @@ -81,9 +94,7 @@ public void shouldReturnBody_WhenFileIsEmpty() throws Exception { @Test public void shouldReturnEmptyBody_WhenFileAndBodyAreNull() throws Exception { - final StubResponse stubResponse = builder - .withHttpStatusCode(Code.OK) - .build(); + final StubResponse stubResponse = builder.withHttpStatusCode(Code.OK).build(); final String actualResponseBody = StringUtils.newStringUtf8(stubResponse.getResponseBodyAsBytes()); assertThat("").isEqualTo(actualResponseBody); @@ -92,10 +103,8 @@ public void shouldReturnEmptyBody_WhenFileAndBodyAreNull() throws Exception { @Test public void shouldReturnEmptyBody_WhenBodyIsEmpty() throws Exception { - final StubResponse stubResponse = builder - .withHttpStatusCode(Code.OK) - .withBody("") - .build(); + final StubResponse stubResponse = + builder.withHttpStatusCode(Code.OK).withBody("").build(); final String actualResponseBody = StringUtils.newStringUtf8(stubResponse.getResponseBodyAsBytes()); assertThat("").isEqualTo(actualResponseBody); @@ -104,10 +113,8 @@ public void shouldReturnEmptyBody_WhenBodyIsEmpty() throws Exception { @Test public void shouldReturnEmptyBody_WhenBodyIsEmpty_AndFileIsEmpty() throws Exception { - final StubResponse stubResponse = builder - .withHttpStatusCode(Code.OK) - .withBody("") - .build(); + final StubResponse stubResponse = + builder.withHttpStatusCode(Code.OK).withBody("").build(); final String actualResponseBody = StringUtils.newStringUtf8(stubResponse.getResponseBodyAsBytes()); assertThat("").isEqualTo(actualResponseBody); @@ -117,8 +124,7 @@ public void shouldReturnEmptyBody_WhenBodyIsEmpty_AndFileIsEmpty() throws Except public void shouldReturnFile_WhenFileNotEmpty_AndRegardlessOfBody() throws Exception { final String expectedResponseBody = "content"; - final StubResponse stubResponse = builder - .withHttpStatusCode(Code.OK) + final StubResponse stubResponse = builder.withHttpStatusCode(Code.OK) .withBody("something") .withFile(tempFileFromString(expectedResponseBody)) .build(); @@ -131,8 +137,7 @@ public void shouldReturnFile_WhenFileNotEmpty_AndRegardlessOfBody() throws Excep public void shouldRequireRecording_WhenBodyStartsWithHttp() throws Exception { final String expectedResponseBody = "http://someurl.com"; - final StubResponse stubResponse = builder - .withHttpStatusCode(Code.OK) + final StubResponse stubResponse = builder.withHttpStatusCode(Code.OK) .withBody(expectedResponseBody) .build(); @@ -143,8 +148,7 @@ public void shouldRequireRecording_WhenBodyStartsWithHttp() throws Exception { public void shouldRequireRecording_WhenBodyStartsWithHttpUpperCase() throws Exception { final String expectedResponseBody = "HTtP://someurl.com"; - final StubResponse stubResponse = builder - .withHttpStatusCode(Code.OK) + final StubResponse stubResponse = builder.withHttpStatusCode(Code.OK) .withBody(expectedResponseBody) .build(); @@ -155,8 +159,7 @@ public void shouldRequireRecording_WhenBodyStartsWithHttpUpperCase() throws Exce public void shouldNotRequireRecording_WhenBodyStartsWithHtt() throws Exception { final String expectedResponseBody = "htt://someurl.com"; - final StubResponse stubResponse = builder - .withHttpStatusCode(Code.OK) + final StubResponse stubResponse = builder.withHttpStatusCode(Code.OK) .withBody(expectedResponseBody) .build(); @@ -167,8 +170,7 @@ public void shouldNotRequireRecording_WhenBodyStartsWithHtt() throws Exception { public void shouldNotRequireRecording_WhenBodyDoesnotStartWithHttp() throws Exception { final String expectedResponseBody = "some body content"; - final StubResponse stubResponse = builder - .withHttpStatusCode(Code.OK) + final StubResponse stubResponse = builder.withHttpStatusCode(Code.OK) .withBody(expectedResponseBody) .build(); @@ -179,10 +181,8 @@ public void shouldNotRequireRecording_WhenBodyDoesnotStartWithHttp() throws Exce public void shouldFindBodyTokenized_WhenBodyContainsTemplateTokens() throws Exception { final String body = "some body with a <% token %>"; - final StubResponse stubResponse = builder - .withHttpStatusCode(Code.OK) - .withBody(body) - .build(); + final StubResponse stubResponse = + builder.withHttpStatusCode(Code.OK).withBody(body).build(); assertThat(stubResponse.isBodyContainsTemplateTokens()).isTrue(); } @@ -191,8 +191,7 @@ public void shouldFindBodyTokenized_WhenBodyContainsTemplateTokens() throws Exce public void shouldFindBodyNotTokenized_WhenRawFileIsTemplateFile() throws Exception { final String body = "some body"; - final StubResponse stubResponse = builder - .withHttpStatusCode(Code.OK) + final StubResponse stubResponse = builder.withHttpStatusCode(Code.OK) .withBody(body) .withFile(tempFileFromString("file content with a <% token %>")) .build(); @@ -204,8 +203,7 @@ public void shouldFindBodyNotTokenized_WhenRawFileIsTemplateFile() throws Except public void shouldFindBodyNotTokenized_WhenRawFileNotTemplateFile() throws Exception { final String body = "some body"; - final StubResponse stubResponse = builder - .withHttpStatusCode(Code.OK) + final StubResponse stubResponse = builder.withHttpStatusCode(Code.OK) .withBody(body) .withFile(tempFileFromString("file content")) .build(); diff --git a/src/test/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketClientRequestTest.java b/src/test/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketClientRequestTest.java index 2570725b1..0133ee1ec 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketClientRequestTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketClientRequestTest.java @@ -1,15 +1,30 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.stubs.websocket; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.utils.FileUtils.tempFileFromString; +import static io.github.azagniotov.stubby4j.utils.StringUtils.getBytesUtf8; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.utils.FileUtils.tempFileFromString; -import static io.github.azagniotov.stubby4j.utils.StringUtils.getBytesUtf8; - @RunWith(MockitoJUnitRunner.class) public class StubWebSocketClientRequestTest { @@ -23,50 +38,42 @@ public void setUp() throws Exception { @Test public void returnsBodyAsExpectedBytesWhenOnlyBodyStubbed() throws Exception { final StubWebSocketClientRequest socketClientRequest = - builder.withBody("OK") - .build(); + builder.withBody("OK").build(); assertThat(socketClientRequest.getBodyAsBytes()).isEqualTo(getBytesUtf8("OK")); } @Test public void returnsBodyAsExpectedBytesWhenOnlyFileStubbed() throws Exception { final StubWebSocketClientRequest socketClientRequest = - builder.withFile(tempFileFromString("Apple")) - .build(); + builder.withFile(tempFileFromString("Apple")).build(); assertThat(socketClientRequest.getBodyAsBytes()).isEqualTo(getBytesUtf8("Apple")); } @Test public void returnsBodyAsExpectedFileBytesWhenBothBodyAndFileStubbed() throws Exception { final StubWebSocketClientRequest socketClientRequest = - builder.withBody("OK") - .withFile(tempFileFromString("Banana")) - .build(); + builder.withBody("OK").withFile(tempFileFromString("Banana")).build(); assertThat(socketClientRequest.getBodyAsBytes()).isEqualTo(getBytesUtf8("Banana")); } @Test public void returnsBodyAsExpectedStringWhenOnlyBodyStubbed() throws Exception { final StubWebSocketClientRequest socketClientRequest = - builder.withBody("OK") - .build(); + builder.withBody("OK").build(); assertThat(socketClientRequest.getBodyAsString()).isEqualTo("OK"); } @Test public void returnsBodyAsExpectedStringWhenOnlyFileStubbed() throws Exception { final StubWebSocketClientRequest socketClientRequest = - builder.withFile(tempFileFromString("Apple")) - .build(); + builder.withFile(tempFileFromString("Apple")).build(); assertThat(socketClientRequest.getBodyAsString()).isEqualTo("Apple"); } @Test public void returnsBodyAsExpectedStringWhenBothBodyAndFileStubbed() throws Exception { final StubWebSocketClientRequest socketClientRequest = - builder.withBody("OK") - .withFile(tempFileFromString("Banana")) - .build(); + builder.withBody("OK").withFile(tempFileFromString("Banana")).build(); assertThat(socketClientRequest.getBodyAsString()).isEqualTo("Banana"); } -} \ No newline at end of file +} diff --git a/src/test/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketMessageTypeTest.java b/src/test/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketMessageTypeTest.java index 6bf92c0f2..3016792e5 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketMessageTypeTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketMessageTypeTest.java @@ -1,9 +1,25 @@ -package io.github.azagniotov.stubby4j.stubs.websocket; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import org.junit.Test; +package io.github.azagniotov.stubby4j.stubs.websocket; import static com.google.common.truth.Truth.assertThat; +import org.junit.Test; + public class StubWebSocketMessageTypeTest { @Test public void returnsTrueOnKnownProperties() throws Exception { @@ -18,4 +34,4 @@ public void returnsFalseOnUnknownProperties() throws Exception { assertThat(StubWebSocketMessageType.isUnknownProperty("apple")).isTrue(); assertThat(StubWebSocketMessageType.isUnknownProperty("")).isTrue(); } -} \ No newline at end of file +} diff --git a/src/test/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketServerResponsePolicyTest.java b/src/test/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketServerResponsePolicyTest.java index 43cc7abb0..13e41dc5f 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketServerResponsePolicyTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketServerResponsePolicyTest.java @@ -1,9 +1,25 @@ -package io.github.azagniotov.stubby4j.stubs.websocket; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import org.junit.Test; +package io.github.azagniotov.stubby4j.stubs.websocket; import static com.google.common.truth.Truth.assertThat; +import org.junit.Test; + public class StubWebSocketServerResponsePolicyTest { @Test @@ -11,9 +27,11 @@ public void returnsTrueOnKnownProperties() throws Exception { // Double negative logic assertThat(StubWebSocketServerResponsePolicy.isUnknownProperty("once")).isFalse(); assertThat(StubWebSocketServerResponsePolicy.isUnknownProperty("push")).isFalse(); - assertThat(StubWebSocketServerResponsePolicy.isUnknownProperty("fragmentation")).isFalse(); + assertThat(StubWebSocketServerResponsePolicy.isUnknownProperty("fragmentation")) + .isFalse(); assertThat(StubWebSocketServerResponsePolicy.isUnknownProperty("ping")).isFalse(); - assertThat(StubWebSocketServerResponsePolicy.isUnknownProperty("disconnect")).isFalse(); + assertThat(StubWebSocketServerResponsePolicy.isUnknownProperty("disconnect")) + .isFalse(); } @Test @@ -22,4 +40,4 @@ public void returnsFalseOnUnknownProperties() throws Exception { assertThat(StubWebSocketServerResponsePolicy.isUnknownProperty("apple")).isTrue(); assertThat(StubWebSocketServerResponsePolicy.isUnknownProperty("")).isTrue(); } -} \ No newline at end of file +} diff --git a/src/test/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketServerResponseTest.java b/src/test/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketServerResponseTest.java index c25fc4951..52b39ee47 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketServerResponseTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/stubs/websocket/StubWebSocketServerResponseTest.java @@ -1,10 +1,20 @@ -package io.github.azagniotov.stubby4j.stubs.websocket; - +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +package io.github.azagniotov.stubby4j.stubs.websocket; import static com.google.common.truth.Truth.assertThat; import static io.github.azagniotov.stubby4j.stubs.websocket.StubWebSocketMessageType.TEXT; @@ -12,6 +22,11 @@ import static io.github.azagniotov.stubby4j.utils.FileUtils.tempFileFromString; import static io.github.azagniotov.stubby4j.utils.StringUtils.getBytesUtf8; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + @RunWith(MockitoJUnitRunner.class) public class StubWebSocketServerResponseTest { @@ -34,50 +49,42 @@ public void stubbedWebSocketServerResponseHasExpectedDefaults() throws Exception @Test public void returnsBodyAsExpectedBytesWhenOnlyBodyStubbed() throws Exception { final StubWebSocketServerResponse socketServerResponse = - builder.withBody("OK") - .build(); + builder.withBody("OK").build(); assertThat(socketServerResponse.getBodyAsBytes()).isEqualTo(getBytesUtf8("OK")); } @Test public void returnsBodyAsExpectedBytesWhenOnlyFileStubbed() throws Exception { final StubWebSocketServerResponse socketServerResponse = - builder.withFile(tempFileFromString("Apple")) - .build(); + builder.withFile(tempFileFromString("Apple")).build(); assertThat(socketServerResponse.getBodyAsBytes()).isEqualTo(getBytesUtf8("Apple")); } @Test public void returnsBodyAsExpectedFileBytesWhenBothBodyAndFileStubbed() throws Exception { final StubWebSocketServerResponse socketServerResponse = - builder.withBody("OK") - .withFile(tempFileFromString("Banana")) - .build(); + builder.withBody("OK").withFile(tempFileFromString("Banana")).build(); assertThat(socketServerResponse.getBodyAsBytes()).isEqualTo(getBytesUtf8("Banana")); } @Test public void returnsBodyAsExpectedStringWhenOnlyBodyStubbed() throws Exception { final StubWebSocketServerResponse socketServerResponse = - builder.withBody("OK") - .build(); + builder.withBody("OK").build(); assertThat(socketServerResponse.getBodyAsString()).isEqualTo("OK"); } @Test public void returnsBodyAsExpectedStringWhenOnlyFileStubbed() throws Exception { final StubWebSocketServerResponse socketServerResponse = - builder.withFile(tempFileFromString("Apple")) - .build(); + builder.withFile(tempFileFromString("Apple")).build(); assertThat(socketServerResponse.getBodyAsString()).isEqualTo("Apple"); } @Test public void returnsBodyAsExpectedStringWhenBothBodyAndFileStubbed() throws Exception { final StubWebSocketServerResponse socketServerResponse = - builder.withBody("OK") - .withFile(tempFileFromString("Banana")) - .build(); + builder.withBody("OK").withFile(tempFileFromString("Banana")).build(); assertThat(socketServerResponse.getBodyAsString()).isEqualTo("Banana"); } -} \ No newline at end of file +} diff --git a/src/test/java/io/github/azagniotov/stubby4j/utils/CollectionUtilsTest.java b/src/test/java/io/github/azagniotov/stubby4j/utils/CollectionUtilsTest.java index 07149152d..6f2d16a73 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/utils/CollectionUtilsTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/utils/CollectionUtilsTest.java @@ -1,6 +1,23 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.utils; -import org.junit.Test; +import static com.google.common.truth.Truth.assertThat; +import static io.github.azagniotov.stubby4j.utils.StringUtils.encodeBase16; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; @@ -8,10 +25,7 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.BlockingQueue; - -import static com.google.common.truth.Truth.assertThat; -import static io.github.azagniotov.stubby4j.utils.StringUtils.encodeBase16; - +import org.junit.Test; @SuppressWarnings("serial") public class CollectionUtilsTest { @@ -19,10 +33,12 @@ public class CollectionUtilsTest { @Test public void constructParamMap_ShouldConstructParamMap_WhenQueryStringGiven() throws Exception { - final Map expectedParams = new HashMap() {{ - put("paramTwo", "two"); - put("paramOne", "one"); - }}; + final Map expectedParams = new HashMap() { + { + put("paramTwo", "two"); + put("paramOne", "one"); + } + }; final Map actualParams = CollectionUtils.constructParamMap("paramOne=one¶mTwo=two"); @@ -32,10 +48,12 @@ public void constructParamMap_ShouldConstructParamMap_WhenQueryStringGiven() thr @Test public void constructParamMap_ShouldConstructParamMap_WhenQueryParamHasNoValue() throws Exception { - final Map expectedParams = new HashMap() {{ - put("paramTwo", "two"); - put("paramOne", ""); - }}; + final Map expectedParams = new HashMap() { + { + put("paramTwo", "two"); + put("paramOne", ""); + } + }; final Map actualParams = CollectionUtils.constructParamMap("paramOne=¶mTwo=two"); @@ -45,10 +63,12 @@ public void constructParamMap_ShouldConstructParamMap_WhenQueryParamHasNoValue() @Test public void constructParamMap_ShouldConstructParamMap_WhenQueryParamHasNoValueNorEqualSign() throws Exception { - final Map expectedParams = new HashMap() {{ - put("paramTwo", "two"); - put("paramOne", ""); - }}; + final Map expectedParams = new HashMap() { + { + put("paramTwo", "two"); + put("paramOne", ""); + } + }; final Map actualParams = CollectionUtils.constructParamMap("paramOne¶mTwo=two"); @@ -56,11 +76,14 @@ public void constructParamMap_ShouldConstructParamMap_WhenQueryParamHasNoValueNo } @Test - public void constructParamMap_ShouldConstructParamMap_WhenSingleQueryParamHasNoValueNorEqualSign() throws Exception { + public void constructParamMap_ShouldConstructParamMap_WhenSingleQueryParamHasNoValueNorEqualSign() + throws Exception { - final Map expectedParams = new HashMap() {{ - put("paramOne", ""); - }}; + final Map expectedParams = new HashMap() { + { + put("paramOne", ""); + } + }; final Map actualParams = CollectionUtils.constructParamMap("paramOne"); @@ -70,10 +93,12 @@ public void constructParamMap_ShouldConstructParamMap_WhenSingleQueryParamHasNoV @Test public void constructQueryString_ShouldConstructQueryString_WhenParamMapGiven() throws Exception { - final Map expectedParams = new LinkedHashMap() {{ - put("paramTwo", "two"); - put("paramOne", "one"); - }}; + final Map expectedParams = new LinkedHashMap() { + { + put("paramTwo", "two"); + put("paramOne", "one"); + } + }; final String actualQueryString = CollectionUtils.constructQueryString(expectedParams); final String expectedQueryString = "paramTwo=two¶mOne=one"; @@ -84,40 +109,52 @@ public void constructQueryString_ShouldConstructQueryString_WhenParamMapGiven() @Test public void constructParamMap_ShouldUrlDecodeQueryString_WhenQueryParamsAreAnArray() throws Exception { - final Map expectedParams = new HashMap() {{ - put("paramOne", "[id,uuid,created,lastUpdated,displayName,email,givenName,familyName]"); - }}; - + final Map expectedParams = new HashMap() { + { + put("paramOne", "[id,uuid,created,lastUpdated,displayName,email,givenName,familyName]"); + } + }; - final String queryString = String.format("paramOne=%s", "%5Bid,uuid,created,lastUpdated,displayName,email,givenName,familyName%5D"); + final String queryString = String.format( + "paramOne=%s", "%5Bid,uuid,created,lastUpdated,displayName,email,givenName,familyName%5D"); final Map actualParams = CollectionUtils.constructParamMap(queryString); assertThat(expectedParams).isEqualTo(actualParams); } @Test - public void constructParamMap_ShouldUrlDecodeQueryString_WhenQueryParamsAreAnArrayWithQuotedElements() throws Exception { - - final Map expectedParams = new HashMap() {{ - put("paramOne", "[\"id\",\"uuid\",\"created\",\"lastUpdated\",\"displayName\",\"email\",\"givenName\",\"familyName\"]"); - }}; - - - final String queryString = String.format("paramOne=%s", "%5B%22id%22,%22uuid%22,%22created%22,%22lastUpdated%22,%22displayName%22,%22email%22,%22givenName%22,%22familyName%22%5D"); + public void constructParamMap_ShouldUrlDecodeQueryString_WhenQueryParamsAreAnArrayWithQuotedElements() + throws Exception { + + final Map expectedParams = new HashMap() { + { + put( + "paramOne", + "[\"id\",\"uuid\",\"created\",\"lastUpdated\",\"displayName\",\"email\",\"givenName\",\"familyName\"]"); + } + }; + + final String queryString = String.format( + "paramOne=%s", + "%5B%22id%22,%22uuid%22,%22created%22,%22lastUpdated%22,%22displayName%22,%22email%22,%22givenName%22,%22familyName%22%5D"); final Map actualParams = CollectionUtils.constructParamMap(queryString); assertThat(expectedParams).isEqualTo(actualParams); } @Test - public void constructParamMap_ShouldUrlDecodeQueryString_WhenQueryParamsAreAnArrayWithSingleQuoteElements() throws Exception { - - final Map expectedParams = new HashMap() {{ - put("paramOne", "['id','uuid','created','lastUpdated','displayName','email','givenName','familyName']"); - }}; - - - final String queryString = String.format("paramOne=%s", "[%27id%27,%27uuid%27,%27created%27,%27lastUpdated%27,%27displayName%27,%27email%27,%27givenName%27,%27familyName%27]"); + public void constructParamMap_ShouldUrlDecodeQueryString_WhenQueryParamsAreAnArrayWithSingleQuoteElements() + throws Exception { + + final Map expectedParams = new HashMap() { + { + put("paramOne", "['id','uuid','created','lastUpdated','displayName','email','givenName','familyName']"); + } + }; + + final String queryString = String.format( + "paramOne=%s", + "[%27id%27,%27uuid%27,%27created%27,%27lastUpdated%27,%27displayName%27,%27email%27,%27givenName%27,%27familyName%27]"); final Map actualParams = CollectionUtils.constructParamMap(queryString); assertThat(expectedParams).isEqualTo(actualParams); @@ -125,10 +162,12 @@ public void constructParamMap_ShouldUrlDecodeQueryString_WhenQueryParamsAreAnArr @Test public void givenTwoStringArrays_whenConcatWithCopy_thenGetExpectedResult() { - final String[] args = new String[]{"-m", "-l", "127.0.0.1", "-s", "8882", "-a", "8889", "-t", "7443"}; - final String[] flags = new String[]{"enable_tls_with_alpn_and_http_2"}; + final String[] args = new String[] {"-m", "-l", "127.0.0.1", "-s", "8882", "-a", "8889", "-t", "7443"}; + final String[] flags = new String[] {"enable_tls_with_alpn_and_http_2"}; - final String[] expected = new String[]{"-m", "-l", "127.0.0.1", "-s", "8882", "-a", "8889", "-t", "7443", "enable_tls_with_alpn_and_http_2"}; + final String[] expected = new String[] { + "-m", "-l", "127.0.0.1", "-s", "8882", "-a", "8889", "-t", "7443", "enable_tls_with_alpn_and_http_2" + }; final String[] actual = CollectionUtils.concatWithArrayCopy(args, flags); assertThat(actual).isEqualTo(expected); @@ -136,10 +175,10 @@ public void givenTwoStringArrays_whenConcatWithCopy_thenGetExpectedResult() { @Test public void givenTwoStringArraysWithOneEmpty_whenConcatWithCopy_thenGetExpectedResult() { - final String[] args = new String[]{"-m", "-l", "127.0.0.1", "-s", "8882", "-a", "8889", "-t", "7443"}; - final String[] flags = new String[]{}; + final String[] args = new String[] {"-m", "-l", "127.0.0.1", "-s", "8882", "-a", "8889", "-t", "7443"}; + final String[] flags = new String[] {}; - final String[] expected = new String[]{"-m", "-l", "127.0.0.1", "-s", "8882", "-a", "8889", "-t", "7443"}; + final String[] expected = new String[] {"-m", "-l", "127.0.0.1", "-s", "8882", "-a", "8889", "-t", "7443"}; final String[] actual = CollectionUtils.concatWithArrayCopy(args, flags); assertThat(actual).isEqualTo(expected); @@ -147,13 +186,14 @@ public void givenTwoStringArraysWithOneEmpty_whenConcatWithCopy_thenGetExpectedR @Test public void chunkifyByteArrayAndQueue() { - final String originalString = "The Japanese raccoon dog is mainly nocturnal, but they are known to be active" + - "during daylight. They vocalize by growling or with groans that have pitches resembling those of" + - "domesticated cats. Like cats, the Japanese raccoon dog arches its back when it is trying to intimidate" + - "other animals; however, they assume a defensive posture similar to that of other canids, lowering their" + - "bodies and showing their bellies to submit."; + final String originalString = "The Japanese raccoon dog is mainly nocturnal, but they are known to be active" + + "during daylight. They vocalize by growling or with groans that have pitches resembling those of" + + "domesticated cats. Like cats, the Japanese raccoon dog arches its back when it is trying to intimidate" + + "other animals; however, they assume a defensive posture similar to that of other canids, lowering their" + + "bodies and showing their bellies to submit."; final byte[] originalStringBytes = originalString.getBytes(StandardCharsets.UTF_8); - final BlockingQueue byteArrayQueue = CollectionUtils.chunkifyByteArrayAndQueue(originalStringBytes, 100); + final BlockingQueue byteArrayQueue = + CollectionUtils.chunkifyByteArrayAndQueue(originalStringBytes, 100); ByteBuffer allocatedByteBuffer = ByteBuffer.allocate(originalStringBytes.length); while (!byteArrayQueue.isEmpty()) { @@ -170,7 +210,8 @@ public void chunkifyByteArrayAndQueue() { public void chunkifyTinyByteArrayAndQueue() { final String originalString = "The Japanese raccoon dog."; final byte[] originalStringBytes = originalString.getBytes(StandardCharsets.UTF_8); - final BlockingQueue byteArrayQueue = CollectionUtils.chunkifyByteArrayAndQueue(originalStringBytes, 100); + final BlockingQueue byteArrayQueue = + CollectionUtils.chunkifyByteArrayAndQueue(originalStringBytes, 100); ByteBuffer allocatedByteBuffer = ByteBuffer.allocate(originalStringBytes.length); while (!byteArrayQueue.isEmpty()) { diff --git a/src/test/java/io/github/azagniotov/stubby4j/utils/DateTimeUtilsTest.java b/src/test/java/io/github/azagniotov/stubby4j/utils/DateTimeUtilsTest.java index a0b9c2eb0..d83542371 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/utils/DateTimeUtilsTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/utils/DateTimeUtilsTest.java @@ -1,18 +1,32 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.utils; -import org.junit.Test; +import static com.google.common.truth.Truth.assertThat; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; - -import static com.google.common.truth.Truth.assertThat; +import org.junit.Test; public class DateTimeUtilsTest { - private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter - .ofPattern("yyyy-MM-dd HH:mm:ssZ") - .withZone(ZoneOffset.systemDefault()); + private static final DateTimeFormatter DATE_TIME_FORMATTER = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssZ").withZone(ZoneOffset.systemDefault()); @Test public void systemDefault() throws Exception { diff --git a/src/test/java/io/github/azagniotov/stubby4j/utils/FileUtilsTest.java b/src/test/java/io/github/azagniotov/stubby4j/utils/FileUtilsTest.java index e13534246..5f2296b12 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/utils/FileUtilsTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/utils/FileUtilsTest.java @@ -1,11 +1,26 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.utils; +import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.io.IOException; - public class FileUtilsTest { @Rule diff --git a/src/test/java/io/github/azagniotov/stubby4j/utils/HandlerUtilsTest.java b/src/test/java/io/github/azagniotov/stubby4j/utils/HandlerUtilsTest.java index caaad8d06..d1eacda47 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/utils/HandlerUtilsTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/utils/HandlerUtilsTest.java @@ -1,19 +1,36 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.utils; +import static com.google.common.truth.Truth.assertThat; + import org.eclipse.jetty.http.HttpScheme; import org.junit.Test; -import static com.google.common.truth.Truth.assertThat; - public class HandlerUtilsTest { - private final static int HOURS_IN_DAY = 24; - private final static int SECONDS_IN_MINUTE = 60; - private final static int MINUTES_IN_HOUR = 60; - private final static int MILLISECONDS_IN_SECOND = 1000; - private final static int MILLISECONDS_IN_MINUTE = SECONDS_IN_MINUTE * MILLISECONDS_IN_SECOND; - private final static int MILLISECONDS_IN_HOUR = MINUTES_IN_HOUR * SECONDS_IN_MINUTE * MILLISECONDS_IN_SECOND; - private final static int MILLISECONDS_IN_DAY = HOURS_IN_DAY * MINUTES_IN_HOUR * SECONDS_IN_MINUTE * MILLISECONDS_IN_SECOND; + private static final int HOURS_IN_DAY = 24; + private static final int SECONDS_IN_MINUTE = 60; + private static final int MINUTES_IN_HOUR = 60; + private static final int MILLISECONDS_IN_SECOND = 1000; + private static final int MILLISECONDS_IN_MINUTE = SECONDS_IN_MINUTE * MILLISECONDS_IN_SECOND; + private static final int MILLISECONDS_IN_HOUR = MINUTES_IN_HOUR * SECONDS_IN_MINUTE * MILLISECONDS_IN_SECOND; + private static final int MILLISECONDS_IN_DAY = + HOURS_IN_DAY * MINUTES_IN_HOUR * SECONDS_IN_MINUTE * MILLISECONDS_IN_SECOND; @Test public void shouldEscapeHtmlEntities() throws Exception { @@ -27,8 +44,10 @@ public void shouldEscapeHtmlEntities() throws Exception { @Test public void shouldLinkifyUriString() throws Exception { - final String actualLinkified = HandlerUtils.linkifyRequestUrl(HttpScheme.HTTP.asString(), "/google/1", "localhost", 8888); - final String expectedLinkified = "http://localhost:8888/google/1"; + final String actualLinkified = + HandlerUtils.linkifyRequestUrl(HttpScheme.HTTP.asString(), "/google/1", "localhost", 8888); + final String expectedLinkified = + "http://localhost:8888/google/1"; assertThat(actualLinkified).isEqualTo(expectedLinkified); } @@ -36,8 +55,10 @@ public void shouldLinkifyUriString() throws Exception { @Test public void shouldLinkifyUriStringForHttps() throws Exception { - final String actualLinkified = HandlerUtils.linkifyRequestUrl(HttpScheme.HTTPS.asString(), "/google/1", "localhost", 7443); - final String expectedLinkified = "https://localhost:7443/google/1"; + final String actualLinkified = + HandlerUtils.linkifyRequestUrl(HttpScheme.HTTPS.asString(), "/google/1", "localhost", 7443); + final String expectedLinkified = + "https://localhost:7443/google/1"; assertThat(actualLinkified).isEqualTo(expectedLinkified); } @@ -45,8 +66,10 @@ public void shouldLinkifyUriStringForHttps() throws Exception { @Test public void shouldLinkifyUriStringWithSingleQuotesInQueryString() throws Exception { - final String actualLinkified = HandlerUtils.linkifyRequestUrl(HttpScheme.HTTP.asString(), "/entity?client_secret=secret&attributes=['id','uuid']", "localhost", 8882); - final String expectedLinkified = "http://localhost:8882/entity?client_secret=secret&attributes=['id','uuid']"; + final String actualLinkified = HandlerUtils.linkifyRequestUrl( + HttpScheme.HTTP.asString(), "/entity?client_secret=secret&attributes=['id','uuid']", "localhost", 8882); + final String expectedLinkified = + "http://localhost:8882/entity?client_secret=secret&attributes=['id','uuid']"; assertThat(actualLinkified).isEqualTo(expectedLinkified); } @@ -54,7 +77,8 @@ public void shouldLinkifyUriStringWithSingleQuotesInQueryString() throws Excepti @Test public void shouldGenerateUpTime_OneDayOneHourOneMinuteOneSecond() throws Exception { - final long timestamp = MILLISECONDS_IN_DAY + MILLISECONDS_IN_HOUR + MILLISECONDS_IN_MINUTE + MILLISECONDS_IN_SECOND; + final long timestamp = + MILLISECONDS_IN_DAY + MILLISECONDS_IN_HOUR + MILLISECONDS_IN_MINUTE + MILLISECONDS_IN_SECOND; final String actualUpTime = HandlerUtils.calculateStubbyUpTime(timestamp); assertThat(actualUpTime).isEqualTo("1 day, 1 hour, 1 min, 1 sec"); @@ -63,7 +87,10 @@ public void shouldGenerateUpTime_OneDayOneHourOneMinuteOneSecond() throws Except @Test public void shouldGenerateUpTime_OneDay23Hours59Minutes59Seconds() throws Exception { - final long timestamp = MILLISECONDS_IN_DAY + (MILLISECONDS_IN_HOUR * 23) + (MILLISECONDS_IN_MINUTE * 59) + (MILLISECONDS_IN_SECOND * 59); + final long timestamp = MILLISECONDS_IN_DAY + + (MILLISECONDS_IN_HOUR * 23) + + (MILLISECONDS_IN_MINUTE * 59) + + (MILLISECONDS_IN_SECOND * 59); final String actualUpTime = HandlerUtils.calculateStubbyUpTime(timestamp); assertThat(actualUpTime).isEqualTo("1 day, 23 hours, 59 mins, 59 secs"); diff --git a/src/test/java/io/github/azagniotov/stubby4j/utils/ReflectionUtilsTest.java b/src/test/java/io/github/azagniotov/stubby4j/utils/ReflectionUtilsTest.java index 778a875f0..d178f9835 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/utils/ReflectionUtilsTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/utils/ReflectionUtilsTest.java @@ -1,15 +1,29 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.utils; +import static com.google.common.truth.Truth.assertThat; + import com.google.api.client.http.HttpMethods; import io.github.azagniotov.stubby4j.stubs.StubRequest; -import org.junit.Before; -import org.junit.Test; - import java.util.HashMap; import java.util.Map; - -import static com.google.common.truth.Truth.assertThat; - +import org.junit.Before; +import org.junit.Test; public class ReflectionUtilsTest { @@ -57,8 +71,7 @@ public void shouldNotSetValueOnObjectProperty_WhenIncorrectPropertyNameGiven() t @Test public void shouldReturnNullWhenClassHasNoDeclaredMethods() throws Exception { - final Object result = ReflectionUtils.getPropertyValue(new MethodLessInterface() { - }, "somePropertyName"); + final Object result = ReflectionUtils.getPropertyValue(new MethodLessInterface() {}, "somePropertyName"); assertThat(result).isNull(); } @@ -66,19 +79,19 @@ public void shouldReturnNullWhenClassHasNoDeclaredMethods() throws Exception { @Test public void shouldReturnPropertyValueWhenClassHasDeclaredMethods() throws Exception { final String expectedMethodValue = "cheburashka"; - final Object result = ReflectionUtils.getPropertyValue(new MethodFulInterface() { - @Override - public String getName() { - return expectedMethodValue; - } - }, "name"); + final Object result = ReflectionUtils.getPropertyValue( + new MethodFulInterface() { + @Override + public String getName() { + return expectedMethodValue; + } + }, + "name"); assertThat(result).isEqualTo(expectedMethodValue); } - private interface MethodLessInterface { - - } + private interface MethodLessInterface {} private interface MethodFulInterface { String getName(); diff --git a/src/test/java/io/github/azagniotov/stubby4j/utils/StringUtilsTest.java b/src/test/java/io/github/azagniotov/stubby4j/utils/StringUtilsTest.java index 0e2940a90..6fa4221ce 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/utils/StringUtilsTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/utils/StringUtilsTest.java @@ -1,8 +1,22 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.utils; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import static com.google.common.truth.Truth.assertThat; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; @@ -12,8 +26,9 @@ import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; - -import static com.google.common.truth.Truth.assertThat; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; public class StringUtilsTest { @@ -38,36 +53,51 @@ public void isNotSet() throws Exception { @Test public void isNumeric() throws Exception { - assertThat(StringUtils.isNumeric("9136d8b7-f7a7-478d-97a5-53292484aaf6")).isFalse(); + assertThat(StringUtils.isNumeric("9136d8b7-f7a7-478d-97a5-53292484aaf6")) + .isFalse(); assertThat(StringUtils.isNumeric("8-88")).isFalse(); assertThat(StringUtils.isNumeric("888")).isTrue(); } @Test public void encodeBase16() throws Exception { - assertThat(StringUtils.encodeBase16("".getBytes(StandardCharsets.UTF_8))).isEqualTo(""); - assertThat(StringUtils.encodeBase16(".".getBytes(StandardCharsets.UTF_8))).isEqualTo("2e"); - assertThat(StringUtils.encodeBase16("a".getBytes(StandardCharsets.UTF_8))).isEqualTo("61"); - - final String originalString = "The Japanese raccoon dog is mainly nocturnal, but they are known to be active " + - "during daylight. They vocalize by growling or with groans that have pitches resembling those of " + - "domesticated cats. Like cats, the Japanese raccoon dog arches its back when it is trying to intimidate " + - "other animals; however, they assume a defensive posture similar to that of other canids, lowering their " + - "bodies and showing their bellies to submit."; + assertThat(StringUtils.encodeBase16("".getBytes(StandardCharsets.UTF_8))) + .isEqualTo(""); + assertThat(StringUtils.encodeBase16(".".getBytes(StandardCharsets.UTF_8))) + .isEqualTo("2e"); + assertThat(StringUtils.encodeBase16("a".getBytes(StandardCharsets.UTF_8))) + .isEqualTo("61"); + + final String originalString = "The Japanese raccoon dog is mainly nocturnal, but they are known to be active " + + "during daylight. They vocalize by growling or with groans that have pitches resembling those of " + + "domesticated cats. Like cats, the Japanese raccoon dog arches its back when it is trying to intimidate " + + "other animals; however, they assume a defensive posture similar to that of other canids, lowering their " + + "bodies and showing their bellies to submit."; byte[] originalStringBytes = originalString.getBytes(StandardCharsets.UTF_8); - assertThat(StringUtils.encodeBase16(originalStringBytes)).isEqualTo("546865204a6170616e65736520726163636f6f6e20646f67206973206d61696e6c79206e6f637475726e616c2c20627574207468657920617265206b6e6f776e20746f2062652061637469766520647572696e67206461796c696768742e205468657920766f63616c697a652062792067726f776c696e67206f7220776974682067726f616e7320746861742068617665207069746368657320726573656d626c696e672074686f7365206f6620646f6d65737469636174656420636174732e204c696b6520636174732c20746865204a6170616e65736520726163636f6f6e20646f672061726368657320697473206261636b207768656e20697420697320747279696e6720746f20696e74696d6964617465206f7468657220616e696d616c733b20686f77657665722c207468657920617373756d65206120646566656e7369766520706f73747572652073696d696c617220746f2074686174206f66206f746865722063616e6964732c206c6f776572696e6720746865697220626f6469657320616e642073686f77696e672074686569722062656c6c69657320746f207375626d69742e"); + assertThat(StringUtils.encodeBase16(originalStringBytes)) + .isEqualTo( + "546865204a6170616e65736520726163636f6f6e20646f67206973206d61696e6c79206e6f637475726e616c2c20627574207468657920617265206b6e6f776e20746f2062652061637469766520647572696e67206461796c696768742e205468657920766f63616c697a652062792067726f776c696e67206f7220776974682067726f616e7320746861742068617665207069746368657320726573656d626c696e672074686f7365206f6620646f6d65737469636174656420636174732e204c696b6520636174732c20746865204a6170616e65736520726163636f6f6e20646f672061726368657320697473206261636b207768656e20697420697320747279696e6720746f20696e74696d6964617465206f7468657220616e696d616c733b20686f77657665722c207468657920617373756d65206120646566656e7369766520706f73747572652073696d696c617220746f2074686174206f66206f746865722063616e6964732c206c6f776572696e6720746865697220626f6469657320616e642073686f77696e672074686569722062656c6c69657320746f207375626d69742e"); } @Test public void removeValueFromCsv() throws Exception { - final String one = StringUtils.removeValueFromCsv("SLv3, RC4, DES, MD5withRSA, DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, include jdk.disabled.namedCurves", "SLv3"); - assertThat(one).isEqualTo("RC4, DES, MD5withRSA, DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, include jdk.disabled.namedCurves"); + final String one = StringUtils.removeValueFromCsv( + "SLv3, RC4, DES, MD5withRSA, DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, include jdk.disabled.namedCurves", + "SLv3"); + assertThat(one) + .isEqualTo( + "RC4, DES, MD5withRSA, DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, include jdk.disabled.namedCurves"); final String two = StringUtils.removeValueFromCsv("SLv3", "SLv3"); assertThat(two).isEqualTo(""); - final String three = StringUtils.removeValueFromCsv("SLv3, RC4, DES, MD5withRSA, DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, include jdk.disabled.namedCurves", "SLv3", "EC", "non-existent", "DES"); + final String three = StringUtils.removeValueFromCsv( + "SLv3, RC4, DES, MD5withRSA, DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, include jdk.disabled.namedCurves", + "SLv3", + "EC", + "non-existent", + "DES"); assertThat(three).isEqualTo("RC4, MD5withRSA, DH keySize < 1024, anon, NULL, include jdk.disabled.namedCurves"); final String four = StringUtils.removeValueFromCsv("", "SLv3", "EC", "non-existent", "DES"); @@ -164,7 +194,8 @@ public void shouldRemoveSquareBracketsFromString() throws Exception { @Test public void shouldReturnTrueWhenStringWithinSquareBrackets() throws Exception { - final String originalElements = "[%22id%22,%20%22uuid%22,%20%22created%22,%20%22lastUpdated%22,%20%22displayName%22,%20%22email%22,%20%22givenName%22,%20%22familyName%22]"; + final String originalElements = + "[%22id%22,%20%22uuid%22,%20%22created%22,%20%22lastUpdated%22,%20%22displayName%22,%20%22email%22,%20%22givenName%22,%20%22familyName%22]"; final boolean isWithinSquareBrackets = StringUtils.isWithinSquareBrackets(originalElements); @@ -181,7 +212,6 @@ public void shouldReturnTrueWhenStringWithinEncodedSquareBrackets() throws Excep assertThat(isWithinSquareBrackets).isTrue(); } - @Test public void shouldReturnFalseWhenStringWithinNotPairOfEscapedSquareBracket() throws Exception { @@ -233,12 +263,13 @@ public void shouldReturnErrorWhenTryingToConvertSpaceInputStreamToString() throw assertThat(StringUtils.inputStreamToString(byteArrayInputStream)).isEqualTo(""); } - @Test public void shouldCorrectlyEncodeSingleQuotesInURL() throws Exception { - final String originaUrl = "http://localhost:8882/entity.find.single.quote?client_secret=secret&attributes=['id','uuid','created','lastUpdated','displayName','email','givenName','familyName']"; - final String expectedEncodedUrl = "http://localhost:8882/entity.find.single.quote?client_secret=secret&attributes=[%27id%27,%27uuid%27,%27created%27,%27lastUpdated%27,%27displayName%27,%27email%27,%27givenName%27,%27familyName%27]"; + final String originaUrl = + "http://localhost:8882/entity.find.single.quote?client_secret=secret&attributes=['id','uuid','created','lastUpdated','displayName','email','givenName','familyName']"; + final String expectedEncodedUrl = + "http://localhost:8882/entity.find.single.quote?client_secret=secret&attributes=[%27id%27,%27uuid%27,%27created%27,%27lastUpdated%27,%27displayName%27,%27email%27,%27givenName%27,%27familyName%27]"; final String actualEncodedUrl = StringUtils.encodeSingleQuotes(originaUrl); assertThat(actualEncodedUrl).isEqualTo(expectedEncodedUrl); @@ -269,10 +300,12 @@ public void shouldReplaceTokensInATemplateWhenAllTokensPresent() throws Exceptio tokensAndValues.put("url.2", "JOHN"); tokensAndValues.put("url.3", "wendy"); tokensAndValues.put("query.1", "KOKO"); - final String template = "This is a response <% url.1 %> content <%url.2%> that going to be <%query.1 %> returned"; + final String template = + "This is a response <% url.1 %> content <%url.2%> that going to be <%query.1 %> returned"; final String replacedTemplate = StringUtils.replaceTokens(StringUtils.getBytesUtf8(template), tokensAndValues); - assertThat(replacedTemplate).isEqualTo("This is a response cheburashka content JOHN that going to be KOKO returned"); + assertThat(replacedTemplate) + .isEqualTo("This is a response cheburashka content JOHN that going to be KOKO returned"); } @Test @@ -281,10 +314,12 @@ public void shouldReplaceTokensInATemplateWhenNotAllTokenValuesPresent() throws final Map tokensAndValues = new HashMap(); tokensAndValues.put("url.1", "cheburashka"); tokensAndValues.put("url.2", "JOHN"); - final String template = "This is a response <% url.1 %> content <%url.2%> that going to be <% query.1 %> returned"; + final String template = + "This is a response <% url.1 %> content <%url.2%> that going to be <% query.1 %> returned"; final String replacedTemplate = StringUtils.replaceTokens(StringUtils.getBytesUtf8(template), tokensAndValues); - assertThat(replacedTemplate).isEqualTo("This is a response cheburashka content JOHN that going to be <% query.1 %> returned"); + assertThat(replacedTemplate) + .isEqualTo("This is a response cheburashka content JOHN that going to be <% query.1 %> returned"); } @Test diff --git a/src/test/java/io/github/azagniotov/stubby4j/yaml/YamlBuilderTest.java b/src/test/java/io/github/azagniotov/stubby4j/yaml/YamlBuilderTest.java index d0a7c3ab5..f88801eb6 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/yaml/YamlBuilderTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/yaml/YamlBuilderTest.java @@ -1,7 +1,20 @@ -package io.github.azagniotov.stubby4j.yaml; +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import io.github.azagniotov.stubby4j.common.Common; -import org.junit.Test; +package io.github.azagniotov.stubby4j.yaml; import static com.google.common.truth.Truth.assertThat; import static io.github.azagniotov.stubby4j.stubs.StubbableAuthorizationType.BASIC; @@ -9,34 +22,34 @@ import static io.github.azagniotov.stubby4j.stubs.StubbableAuthorizationType.CUSTOM; import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; +import io.github.azagniotov.stubby4j.common.Common; +import org.junit.Test; public class YamlBuilderTest { @Test public void shouldBuildStubbedResponseWithSequenceResponses() throws Exception { - final String expectedYaml = - "- description: Hello!" + BR + - " uuid: abc-123-def-456" + BR + - " request:" + BR + - " method: [PUT]" + BR + - " url: /invoice" + BR + - "" + BR + - " response:" + BR + - " - status: 200" + BR + - " headers: " + BR + - " content-type: application/json" + BR + - " body: OK" + BR + - "" + BR + - " - status: 200" + BR + - " headers: " + BR + - " content-type: application/json" + BR + - " body: Still going strong!" + BR + - "" + BR + - " - status: 500" + BR + - " headers: " + BR + - " content-type: application/json" + BR + - " body: OMFG!!!" + BR + - " file: ../../response.json"; + final String expectedYaml = "- description: Hello!" + BR + " uuid: abc-123-def-456" + + BR + " request:" + + BR + " method: [PUT]" + + BR + " url: /invoice" + + BR + "" + + BR + " response:" + + BR + " - status: 200" + + BR + " headers: " + + BR + " content-type: application/json" + + BR + " body: OK" + + BR + "" + + BR + " - status: 200" + + BR + " headers: " + + BR + " content-type: application/json" + + BR + " body: Still going strong!" + + BR + "" + + BR + " - status: 500" + + BR + " headers: " + + BR + " content-type: application/json" + + BR + " body: OMFG!!!" + + BR + " file: ../../response.json"; final YamlBuilder yamlBuilder = new YamlBuilder(); final String actualYaml = yamlBuilder @@ -63,36 +76,32 @@ public void shouldBuildStubbedResponseWithSequenceResponses() throws Exception { .build(); assertThat(actualYaml).isEqualTo(expectedYaml); - } @Test public void shouldBuildStubbedResponseWithSequenceResponsesFoldedBodyAndFile() throws Exception { - final String expectedYaml = - "- request:" + BR + - " method: [PUT]" + BR + - " url: /invoice" + BR + - "" + BR + - " response:" + BR + - " - status: 200" + BR + - " headers: " + BR + - " content-type: application/json" + BR + - " body: OK" + BR + - "" + BR + - " - status: 200" + BR + - " headers: " + BR + - " content-type: application/json" + BR + - " body: >" + BR + - " {\"status\", \"200\"}" + BR + - "" + BR + - " - status: 500" + BR + - " headers: " + BR + - " content-type: application/json" + BR + - " file: ../path/to/error.file"; + final String expectedYaml = "- request:" + BR + " method: [PUT]" + + BR + " url: /invoice" + + BR + "" + + BR + " response:" + + BR + " - status: 200" + + BR + " headers: " + + BR + " content-type: application/json" + + BR + " body: OK" + + BR + "" + + BR + " - status: 200" + + BR + " headers: " + + BR + " content-type: application/json" + + BR + " body: >" + + BR + " {\"status\", \"200\"}" + + BR + "" + + BR + " - status: 500" + + BR + " headers: " + + BR + " content-type: application/json" + + BR + " file: ../path/to/error.file"; final YamlBuilder YamlBuilder = new YamlBuilder(); - final String actualYaml = YamlBuilder - .newStubbedRequest() + final String actualYaml = YamlBuilder.newStubbedRequest() .withMethodPut() .withUrl("/invoice") .newStubbedResponse() @@ -111,173 +120,155 @@ public void shouldBuildStubbedResponseWithSequenceResponsesFoldedBodyAndFile() t .build(); assertThat(actualYaml).isEqualTo(expectedYaml); - } @Test public void shouldBuildStubbedRequestWithMultipleMethods() throws Exception { - final String expectedYaml = - "- request:" + BR + - " method: [HEAD, GET, PUT]" + BR + - " url: /invoice" + BR + - "" + BR + - " response:" + BR + - " status: 200" + BR + - " body: OK"; + final String expectedYaml = "- request:" + BR + " method: [HEAD, GET, PUT]" + + BR + " url: /invoice" + + BR + "" + + BR + " response:" + + BR + " status: 200" + + BR + " body: OK"; final YamlBuilder YamlBuilder = new YamlBuilder(); - final String actualYaml = YamlBuilder. - newStubbedRequest(). - withMethodHead(). - withMethodGet(). - withMethodPut(). - withUrl("/invoice"). - newStubbedResponse(). - withStatus("200"). - withLiteralBody("OK").build(); + final String actualYaml = YamlBuilder.newStubbedRequest() + .withMethodHead() + .withMethodGet() + .withMethodPut() + .withUrl("/invoice") + .newStubbedResponse() + .withStatus("200") + .withLiteralBody("OK") + .build(); assertThat(actualYaml).isEqualTo(expectedYaml); - } @Test public void shouldBuildStubbedRequestWithStubbedResponse() throws Exception { - final String expectedYaml = - "- request:" + BR + - " query:" + BR + - " status: active" + BR + - " type: full" + BR + - " method: [GET]" + BR + - " url: /invoice" + BR + - "" + BR + - " response:" + BR + - " headers:" + BR + - " content-type: application/json" + BR + - " pragma: no-cache" + BR + - " status: 200" + BR + - " file: ../json/systemtest-body-response-as-file.json"; + final String expectedYaml = "- request:" + BR + " query:" + + BR + " status: active" + + BR + " type: full" + + BR + " method: [GET]" + + BR + " url: /invoice" + + BR + "" + + BR + " response:" + + BR + " headers:" + + BR + " content-type: application/json" + + BR + " pragma: no-cache" + + BR + " status: 200" + + BR + " file: ../json/systemtest-body-response-as-file.json"; final YamlBuilder YamlBuilder = new YamlBuilder(); - final String actualYaml = YamlBuilder. - newStubbedRequest(). - withQuery("status", "active"). - withQuery("type", "full"). - withMethodGet(). - withUrl("/invoice"). - newStubbedResponse(). - withHeaders("content-type", Common.HEADER_APPLICATION_JSON). - withHeaders("pragma", "no-cache"). - withStatus("200"). - withFile("../json/systemtest-body-response-as-file.json").build(); + final String actualYaml = YamlBuilder.newStubbedRequest() + .withQuery("status", "active") + .withQuery("type", "full") + .withMethodGet() + .withUrl("/invoice") + .newStubbedResponse() + .withHeaders("content-type", Common.HEADER_APPLICATION_JSON) + .withHeaders("pragma", "no-cache") + .withStatus("200") + .withFile("../json/systemtest-body-response-as-file.json") + .build(); assertThat(actualYaml).isEqualTo(expectedYaml); - } - @Test public void shouldBuildStubbedRequestWithMultilineStubbedResponse() throws Exception { - final String expectedYaml = - "- request:" + BR + - " method: [PUT]" + BR + - " url: /invoice/123" + BR + - " headers:" + BR + - " content-type: application/json" + BR + - " post: >" + BR + - " {\"name\": \"milk\", \"description\": \"full\", \"department\": \"savoury\"}" + BR + - "" + BR + - " response:" + BR + - " headers:" + BR + - " content-type: application/json" + BR + - " pragma: no-cache" + BR + - " status: 200" + BR + - " body: >" + BR + - " {\"id\": \"123\", \"status\": \"updated\"}"; + final String expectedYaml = "- request:" + BR + " method: [PUT]" + + BR + " url: /invoice/123" + + BR + " headers:" + + BR + " content-type: application/json" + + BR + " post: >" + + BR + " {\"name\": \"milk\", \"description\": \"full\", \"department\": \"savoury\"}" + + BR + "" + + BR + " response:" + + BR + " headers:" + + BR + " content-type: application/json" + + BR + " pragma: no-cache" + + BR + " status: 200" + + BR + " body: >" + + BR + " {\"id\": \"123\", \"status\": \"updated\"}"; final YamlBuilder YamlBuilder = new YamlBuilder(); - final String actualYaml = YamlBuilder. - newStubbedRequest(). - withMethodPut(). - withUrl("/invoice/123"). - withHeaders("content-type", Common.HEADER_APPLICATION_JSON). - withFoldedPost("{\"name\": \"milk\", \"description\": \"full\", \"department\": \"savoury\"}"). - newStubbedResponse(). - withHeaders("content-type", Common.HEADER_APPLICATION_JSON). - withHeaders("pragma", "no-cache"). - withStatus("200"). - withFoldedBody("{\"id\": \"123\", \"status\": \"updated\"}").build(); + final String actualYaml = YamlBuilder.newStubbedRequest() + .withMethodPut() + .withUrl("/invoice/123") + .withHeaders("content-type", Common.HEADER_APPLICATION_JSON) + .withFoldedPost("{\"name\": \"milk\", \"description\": \"full\", \"department\": \"savoury\"}") + .newStubbedResponse() + .withHeaders("content-type", Common.HEADER_APPLICATION_JSON) + .withHeaders("pragma", "no-cache") + .withStatus("200") + .withFoldedBody("{\"id\": \"123\", \"status\": \"updated\"}") + .build(); assertThat(actualYaml).isEqualTo(expectedYaml); - } - @Test public void shouldBuildStubbedRequestWithStubbedResponseWhenBothHaveManyHeaders() throws Exception { - final String expectedYaml = - "- request:" + BR + - " headers:" + BR + - " content-type: application/json" + BR + - " content-language: US-en" + BR + - " content-encoding: gzip" + BR + - " content-length: 30" + BR + - " " + BASIC.asYAMLProp() + ": bob:secret" + BR + - " " + BEARER.asYAMLProp() + ": jkRUTBUjghbjtUGT==" + BR + - " " + CUSTOM.asYAMLProp() + ": Custom jkRUTBUjghbjtUGT==" + BR + - " method: [GET]" + BR + - " url: /invoice" + BR + - "" + BR + - " response:" + BR + - " headers:" + BR + - " content-type: application/json" + BR + - " content-language: US-en" + BR + - " content-encoding: gzip" + BR + - " content-length: 30" + BR + - " pragma: no-cache" + BR + - " location: /invoice/exit"; + final String expectedYaml = "- request:" + BR + " headers:" + + BR + " content-type: application/json" + + BR + " content-language: US-en" + + BR + " content-encoding: gzip" + + BR + " content-length: 30" + + BR + " " + + BASIC.asYAMLProp() + ": bob:secret" + BR + " " + + BEARER.asYAMLProp() + ": jkRUTBUjghbjtUGT==" + BR + " " + + CUSTOM.asYAMLProp() + ": Custom jkRUTBUjghbjtUGT==" + BR + " method: [GET]" + + BR + " url: /invoice" + + BR + "" + + BR + " response:" + + BR + " headers:" + + BR + " content-type: application/json" + + BR + " content-language: US-en" + + BR + " content-encoding: gzip" + + BR + " content-length: 30" + + BR + " pragma: no-cache" + + BR + " location: /invoice/exit"; final YamlBuilder YamlBuilder = new YamlBuilder(); - final String actualYaml = YamlBuilder. - newStubbedRequest(). - withHeaderContentType(Common.HEADER_APPLICATION_JSON). - withHeaderContentLanguage("US-en"). - withHeaderContentEncoding("gzip"). - withHeaderContentLength("30"). - withHeaderAuthorizationBasic("bob:secret"). - withHeaderAuthorizationBearer("jkRUTBUjghbjtUGT=="). - withHeaderAuthorizationCustom("Custom jkRUTBUjghbjtUGT=="). - withMethodGet(). - withUrl("/invoice"). - newStubbedResponse(). - withHeaderContentType(Common.HEADER_APPLICATION_JSON). - withHeaderContentLanguage("US-en"). - withHeaderContentEncoding("gzip"). - withHeaderContentLength("30"). - withHeaderPragma("no-cache"). - withHeaderLocation("/invoice/exit").build(); + final String actualYaml = YamlBuilder.newStubbedRequest() + .withHeaderContentType(Common.HEADER_APPLICATION_JSON) + .withHeaderContentLanguage("US-en") + .withHeaderContentEncoding("gzip") + .withHeaderContentLength("30") + .withHeaderAuthorizationBasic("bob:secret") + .withHeaderAuthorizationBearer("jkRUTBUjghbjtUGT==") + .withHeaderAuthorizationCustom("Custom jkRUTBUjghbjtUGT==") + .withMethodGet() + .withUrl("/invoice") + .newStubbedResponse() + .withHeaderContentType(Common.HEADER_APPLICATION_JSON) + .withHeaderContentLanguage("US-en") + .withHeaderContentEncoding("gzip") + .withHeaderContentLength("30") + .withHeaderPragma("no-cache") + .withHeaderLocation("/invoice/exit") + .build(); assertThat(actualYaml).isEqualTo(expectedYaml); - } @Test public void shouldBuildStubbedProxyConfig() throws Exception { - final String expectedYaml = - "- proxy-config:" + BR + - " description: very-interesting-description" + BR + - " uuid: very-unique-name" + BR + - " strategy: as-is" + BR + - " headers:" + BR + - " keyOne: valueOne" + BR + - " keyTwo: valueTwo" + BR + - " properties:" + BR + - " endpoint: http://google.com" + BR + - " key: value"; + final String expectedYaml = "- proxy-config:" + BR + " description: very-interesting-description" + + BR + " uuid: very-unique-name" + + BR + " strategy: as-is" + + BR + " headers:" + + BR + " keyOne: valueOne" + + BR + " keyTwo: valueTwo" + + BR + " properties:" + + BR + " endpoint: http://google.com" + + BR + " key: value"; final YamlBuilder YamlBuilder = new YamlBuilder(); - final String actualYaml = YamlBuilder - .newStubbedProxyConfig() + final String actualYaml = YamlBuilder.newStubbedProxyConfig() .withDescription("very-interesting-description") .withUuid("very-unique-name") .withProxyStrategyAsIs() @@ -285,9 +276,9 @@ public void shouldBuildStubbedProxyConfig() throws Exception { .withHeader("keyTwo", "valueTwo") .withPropertyEndpoint("http://google.com") .withProperty("key", "value") - .toString().trim(); + .toString() + .trim(); assertThat(actualYaml).isEqualTo(expectedYaml); - } } diff --git a/src/test/java/io/github/azagniotov/stubby4j/yaml/YamlParserTest.java b/src/test/java/io/github/azagniotov/stubby4j/yaml/YamlParserTest.java index c8ab2042f..a9d50fca4 100644 --- a/src/test/java/io/github/azagniotov/stubby4j/yaml/YamlParserTest.java +++ b/src/test/java/io/github/azagniotov/stubby4j/yaml/YamlParserTest.java @@ -1,13 +1,28 @@ +/* + * Copyright (c) 2012-2024 Alexander Zagniotov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.github.azagniotov.stubby4j.yaml; -import org.junit.Test; +import static com.google.common.truth.Truth.assertThat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - -import static com.google.common.truth.Truth.assertThat; +import org.junit.Test; public class YamlParserTest { @@ -37,4 +52,4 @@ public void isMainYamlHasIncludesFoundAsFalseWhenNotMap() { assertThat(yamlParser.isMainYamlHasIncludes(new ArrayList<>())).isFalse(); } -} \ No newline at end of file +}