├── .github ├── dependabot.yml └── workflows │ └── ci.yml ├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src ├── main ├── assembly │ └── jar-with-dependencies.xml ├── java │ └── org │ │ └── gaul │ │ └── httpbin │ │ ├── HttpBin.java │ │ ├── HttpBinHandler.java │ │ ├── Main.java │ │ └── Utils.java └── resources │ ├── checkstyle.xml │ ├── copyright_header.txt │ ├── home.html │ ├── image.jpg │ ├── image.png │ ├── logback.xml │ ├── text.html │ └── text.xml └── test └── java └── org └── gaul └── httpbin └── HttpBinTest.java /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "maven" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "monthly" 12 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Java CI 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - master 7 | push: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | strategy: 15 | matrix: 16 | java: [ '11' ] 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Set up JDK 20 | uses: actions/setup-java@v3 21 | with: 22 | distribution: 'zulu' 23 | java-version: ${{ matrix.java }} 24 | - name: Build with Maven 25 | run: mvn --no-transfer-progress -B clean package 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java httpbin 2 | 3 | [![Build Status](https://travis-ci.org/gaul/java-httpbin.svg?branch=master)](https://travis-ci.org/gaul/java-httpbin) 4 | [![Maven Central](https://img.shields.io/maven-central/v/org.gaul/httpbin.svg)](https://search.maven.org/#search%7Cga%7C1%7Ca%3A%22httpbin%22) 5 | 6 | A Java-based HTTP server that lets you locally test your HTTP client, retry 7 | logic, streaming behavior, timeouts, etc. with the endpoints of 8 | [httpbin.org](https://httpbin.org/). 9 | 10 | This way, you can write tests without relying on an external dependency like 11 | httpbin.org. 12 | 13 | ## Endpoints 14 | 15 | Java httpbin supports a subset of httpbin endpoints: 16 | 17 | - `/ip` Returns Origin IP. 18 | - `/user-agent` Returns user-agent. 19 | - `/headers` Returns headers. 20 | - `/delete` Returns DELETE data. 21 | - `/get` Returns GET data. 22 | - `/patch` Returns PATCH data. 23 | - `/post` Returns POST data. 24 | - `/put` Returns PUT data. 25 | - `/anything` Returns anything passed in request data. 26 | - `/status/:code` Returns given HTTP Status code. 27 | - `/redirect/:n` 302 Redirects _n_ times. 28 | - `/relative-redirect/:n` 302 Redirects _n_ times. 29 | - `/absolute-redirect/:n` 302 Absolute redirects _n_ times. 30 | - `/redirect-to?url=foo` 302 Redirects to the _foo_ URL. 31 | - `/stream/:n` Streams _n_ lines of JSON objects. 32 | - `/stream-bytes/:n?chunkSize=c&seed=s` Streams _n_ bytes. 33 | - `/delay/:n` Delays responding for _min(n, 10)_ seconds. 34 | - `/bytes/:n` Generates _n_ random bytes of binary data, accepts optional _seed_ integer parameter. 35 | - `/base64/:s` Returns a base64 decoded :s input 36 | - `/range/:s` Return a subset of data based on Content-range header. 37 | - `/cookies` Returns the cookies. 38 | - `/cookies/set?name=value` Sets one or more simple cookies. 39 | - `/cookies/delete?name` Deletes one or more simple cookies. 40 | - `/drip?numbytes=n&duration=s&delay=s&code=code` Drips data over a duration after 41 | an optional initial _delay_, then optionally returns with the given status _code_. 42 | - `/cache` Returns 200 unless an If-Modified-Since or If-None-Match header is provided, when it returns a 304. 43 | - `/cache/:n` Sets a Cache-Control header for _n_ seconds. 44 | - `/etag` Return 200 when If-Match or If-None-Match succeed. 45 | - `/gzip` Returns gzip-encoded data. 46 | - `/deflate` Returns deflate-encoded data. 47 | - `/robots.txt` Returns some robots.txt rules. 48 | - `/deny` Denied by robots.txt file. 49 | - `/basic-auth/:user/:passwd` Challenges HTTP Basic Auth. 50 | - `/hidden-basic-auth/:user/:passwd` Challenges HTTP Basic Auth and returns 404 on failure. 51 | - `/html` Returns some HTML. 52 | - `/xml` Returns some XML. 53 | - `/image/png` Returns page containing a PNG image. 54 | - `/image/jpeg` Returns page containing a JPEG image. 55 | 56 | ## Usage 57 | 58 | First add dependency to `pom.xml`: 59 | 60 | ```xml 61 | 62 | org.gaul 63 | httpbin 64 | 1.4.0 65 | 66 | ``` 67 | 68 | Then add to your test code: 69 | 70 | ```java 71 | private URI httpBinEndpoint = URI.create("http://127.0.0.1:0"); 72 | private final HttpBin httpBin = new HttpBin(httpBinEndpoint); 73 | 74 | @Before 75 | public void setUp() throws Exception { 76 | httpBin.start(); 77 | 78 | // reset endpoint to handle zero port 79 | httpBinEndpoint = new URI(httpBinEndpoint.getScheme(), 80 | httpBinEndpoint.getUserInfo(), httpBinEndpoint.getHost(), 81 | httpBin.getPort(), httpBinEndpoint.getPath(), 82 | httpBinEndpoint.getQuery(), httpBinEndpoint.getFragment()); 83 | } 84 | 85 | @After 86 | public void tearDown() throws Exception { 87 | httpBin.stop(); 88 | } 89 | 90 | @Test 91 | public void test() throws Exception { 92 | URI uri = URI.create(httpBinEndpoint + "/status/200"); 93 | HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection(); 94 | assert conn.getResponseCode() == 200; 95 | } 96 | ``` 97 | 98 | ## References 99 | 100 | * [httpbin](https://httpbin.org/) - original Python implementation 101 | * [go-httpbin](https://github.com/ahmetb/go-httpbin) - Go reimplementation 102 | 103 | ## License 104 | 105 | Copyright (C) 2018-2023 Andrew Gaul
106 | Copyright (C) 2015-2016 Bounce Storage 107 | 108 | Licensed under the Apache License, Version 2.0 109 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | 5 | org.sonatype.oss 6 | oss-parent 7 | 7 8 | 9 | 10 | org.gaul 11 | httpbin 12 | 1.5.0-SNAPSHOT 13 | jar 14 | 15 | Java httpbin 16 | https://github.com/gaul/java-httpbin 17 | A local HTTP server which allows testing clients with endpoints compatible with httpbin.org. 18 | 19 | 20 | 21 | The Apache Software License, Version 2.0 22 | https://www.apache.org/licenses/LICENSE-2.0.txt 23 | repo 24 | 25 | 26 | 27 | 28 | scm:git:git@github.com:gaul/java-httpbin.git 29 | scm:git:git@github.com:gaul/java-httpbin.git 30 | git@github.com:gaul/java-httpbin.git 31 | 32 | 33 | 34 | 35 | Andrew Gaul 36 | gaul 37 | andrew@gaul.org 38 | 39 | 40 | 41 | 42 | 43 | ossrh 44 | https://oss.sonatype.org/content/repositories/snapshots 45 | 46 | 47 | 48 | 49 | 50 | release 51 | 52 | 53 | 54 | org.apache.maven.plugins 55 | maven-gpg-plugin 56 | 3.2.7 57 | 58 | 59 | sign-artifacts 60 | verify 61 | 62 | sign 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | org.apache.maven.plugins 76 | maven-checkstyle-plugin 77 | 3.6.0 78 | 79 | 80 | check 81 | verify 82 | 83 | check 84 | 85 | 86 | 87 | 88 | src/main/resources/checkstyle.xml 89 | src/main/resources/copyright_header.txt 90 | true 91 | warning 92 | 93 | 94 | 95 | com.puppycrawl.tools 96 | checkstyle 97 | 10.25.0 98 | 99 | 100 | 101 | 102 | org.apache.maven.plugins 103 | maven-compiler-plugin 104 | 3.14.0 105 | 106 | true 107 | ${java.version} 108 | ${java.version} 109 | true 110 | true 111 | 112 | 113 | 114 | 115 | 116 | 117 | com.google.errorprone 118 | error_prone_core 119 | 2.38.0 120 | 121 | 122 | 123 | 124 | org.apache.maven.plugins 125 | maven-javadoc-plugin 126 | 3.11.2 127 | 128 | 129 | attach-javadocs 130 | 131 | jar 132 | 133 | 134 | 135 | 136 | 137 | org.apache.maven.plugins 138 | maven-assembly-plugin 139 | 3.7.1 140 | 141 | 142 | src/main/assembly/jar-with-dependencies.xml 143 | 144 | 145 | 146 | org.gaul.httpbin.Main 147 | true 148 | 149 | 150 | 151 | 152 | 153 | make-assembly 154 | package 155 | 156 | single 157 | 158 | 159 | 160 | 161 | 162 | org.apache.maven.plugins 163 | maven-source-plugin 164 | 3.3.1 165 | 166 | 167 | attach-sources 168 | 169 | jar-no-fork 170 | 171 | 172 | 173 | 174 | 175 | org.apache.maven.plugins 176 | maven-surefire-plugin 177 | 3.5.3 178 | 179 | classes 180 | 1 181 | -Xmx256m 182 | true 183 | 300 184 | 185 | 186 | 187 | org.skife.maven 188 | really-executable-jar-maven-plugin 189 | 2.1.1 190 | 191 | target/httpbin-${version}-jar-with-dependencies.jar 192 | httpbin 193 | 194 | 195 | 196 | package 197 | 198 | really-executable-jar 199 | 200 | 201 | 202 | 203 | 204 | org.gaul 205 | modernizer-maven-plugin 206 | 3.1.0 207 | 208 | 209 | modernizer 210 | verify 211 | 212 | modernizer 213 | 214 | 215 | 216 | 217 | ${java.version} 218 | 219 | 220 | 221 | org.sonatype.plugins 222 | nexus-staging-maven-plugin 223 | 1.7.0 224 | true 225 | 226 | ossrh 227 | https://oss.sonatype.org/ 228 | true 229 | 230 | 231 | 232 | com.github.spotbugs 233 | spotbugs-maven-plugin 234 | 4.9.3.0 235 | 236 | Max 237 | CrossSiteScripting 238 | 239 | 240 | 241 | org.apache.maven.plugins 242 | maven-enforcer-plugin 243 | 3.5.0 244 | 245 | 246 | enforce-maven 247 | 248 | enforce 249 | 250 | 251 | 252 | 253 | 3.0.5 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | UTF-8 265 | 11 266 | 11.0.25 267 | 268 | 269 | 270 | 271 | ch.qos.logback 272 | logback-classic 273 | 1.5.18 274 | 275 | 276 | commons-codec 277 | commons-codec 278 | 1.18.0 279 | 280 | 281 | junit 282 | junit 283 | 4.13.2 284 | test 285 | 286 | 287 | org.assertj 288 | assertj-core 289 | test 290 | 3.27.3 291 | 292 | 293 | org.eclipse.jetty 294 | jetty-client 295 | ${jetty.version} 296 | 297 | 298 | org.eclipse.jetty 299 | jetty-servlet 300 | ${jetty.version} 301 | 302 | 303 | org.json 304 | json 305 | 20250517 306 | 307 | 308 | org.slf4j 309 | slf4j-api 310 | 2.0.17 311 | 312 | 313 | 314 | -------------------------------------------------------------------------------- /src/main/assembly/jar-with-dependencies.xml: -------------------------------------------------------------------------------- 1 | 4 | jar-with-dependencies 5 | 6 | jar 7 | 8 | false 9 | 10 | 11 | metaInf-services 12 | 13 | 14 | 15 | 16 | / 17 | true 18 | true 19 | runtime 20 | 21 | 22 | 23 | 24 | ${project.basedir}/src/main/config 25 | / 26 | 27 | logback.xml 28 | 29 | true 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/main/java/org/gaul/httpbin/HttpBin.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2023 Andrew Gaul 3 | * Copyright 2015-2016 Bounce Storage, Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * https://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package org.gaul.httpbin; 19 | 20 | import static java.util.Objects.requireNonNull; 21 | 22 | import java.net.URI; 23 | 24 | import org.eclipse.jetty.server.HttpConnectionFactory; 25 | import org.eclipse.jetty.server.Server; 26 | import org.eclipse.jetty.server.ServerConnector; 27 | 28 | /** 29 | * Reimplementation of HttpBin https://httpbin.org/ suitable for offline unit 30 | * tests. 31 | */ 32 | public final class HttpBin { 33 | private final Server server; 34 | 35 | public HttpBin(URI endpoint) throws Exception { 36 | this(endpoint, new HttpBinHandler()); 37 | } 38 | 39 | public HttpBin(URI endpoint, HttpBinHandler handler) throws Exception { 40 | requireNonNull(endpoint); 41 | 42 | server = new Server(); 43 | HttpConnectionFactory httpConnectionFactory = 44 | new HttpConnectionFactory(); 45 | ServerConnector connector = new ServerConnector(server, 46 | httpConnectionFactory); 47 | connector.setHost(endpoint.getHost()); 48 | connector.setPort(endpoint.getPort()); 49 | server.addConnector(connector); 50 | server.setHandler(handler); 51 | } 52 | 53 | public void start() throws Exception { 54 | server.start(); 55 | } 56 | 57 | public void stop() throws Exception { 58 | server.stop(); 59 | } 60 | 61 | public int getPort() { 62 | return ((ServerConnector) server.getConnectors()[0]).getLocalPort(); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/org/gaul/httpbin/HttpBinHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2023 Andrew Gaul 3 | * Copyright 2015-2016 Bounce Storage, Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * https://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package org.gaul.httpbin; 19 | 20 | import java.io.ByteArrayOutputStream; 21 | import java.io.IOException; 22 | import java.io.InputStream; 23 | import java.io.OutputStream; 24 | import java.nio.charset.StandardCharsets; 25 | import java.util.Arrays; 26 | import java.util.Base64; 27 | import java.util.Collections; 28 | import java.util.List; 29 | import java.util.Map; 30 | import java.util.Random; 31 | import java.util.concurrent.TimeUnit; 32 | import java.util.zip.Deflater; 33 | import java.util.zip.DeflaterOutputStream; 34 | import java.util.zip.GZIPOutputStream; 35 | 36 | import org.eclipse.jetty.server.MultiPartFormInputStream; 37 | import org.eclipse.jetty.server.Request; 38 | import org.eclipse.jetty.server.handler.AbstractHandler; 39 | import org.json.JSONArray; 40 | import org.json.JSONException; 41 | import org.json.JSONObject; 42 | import org.slf4j.Logger; 43 | import org.slf4j.LoggerFactory; 44 | 45 | import jakarta.servlet.http.Cookie; 46 | import jakarta.servlet.http.HttpServletRequest; 47 | import jakarta.servlet.http.HttpServletResponse; 48 | import jakarta.servlet.http.Part; 49 | 50 | public class HttpBinHandler extends AbstractHandler { 51 | private static final Logger logger = LoggerFactory.getLogger( 52 | HttpBinHandler.class); 53 | private static final int MAX_DELAY_MS = 10 * 1000; 54 | 55 | @Override 56 | public void handle(String target, Request baseRequest, 57 | HttpServletRequest request, HttpServletResponse servletResponse) 58 | throws IOException { 59 | logger.trace("request: {}", request); 60 | for (String headerName : Collections.list( 61 | request.getHeaderNames())) { 62 | logger.trace("header: {}: {}", headerName, 63 | request.getHeader(headerName)); 64 | } 65 | try (InputStream is = request.getInputStream(); 66 | OutputStream os = servletResponse.getOutputStream()) { 67 | handleHelper(baseRequest, request, servletResponse, is, os); 68 | } 69 | } 70 | 71 | private void handleHelper(Request baseRequest, HttpServletRequest request, 72 | HttpServletResponse servletResponse, InputStream is, 73 | OutputStream os) throws IOException { 74 | String method = request.getMethod(); 75 | String uri = request.getRequestURI(); 76 | try { 77 | if (uri.equals("/")) { 78 | servletResponse.setStatus(HttpServletResponse.SC_OK); 79 | servletResponse.addHeader("Content-Type", 80 | "text/html; charset=utf-8"); 81 | copyResource(servletResponse, "/home.html"); 82 | baseRequest.setHandled(true); 83 | return; 84 | } else if (uri.startsWith("/status/")) { 85 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 86 | int status; 87 | try { 88 | status = Integer.parseInt(uri.substring( 89 | "/status/".length())); 90 | } catch (NumberFormatException nfe) { 91 | servletResponse.setStatus( 92 | HttpServletResponse.SC_BAD_REQUEST); 93 | baseRequest.setHandled(true); 94 | return; 95 | } 96 | servletResponse.setStatus(status); 97 | if (status >= 300 && status < 400) { 98 | servletResponse.setHeader("Location", "/redirect/1"); 99 | } 100 | baseRequest.setHandled(true); 101 | return; 102 | } else if (method.equals("GET") && uri.equals("/headers")) { 103 | JSONObject headers = new JSONObject(); 104 | for (String headerName : Collections.list( 105 | request.getHeaderNames())) { 106 | headers.put(headerName, request.getHeader(headerName)); 107 | } 108 | 109 | JSONObject response = new JSONObject(); 110 | response.put("headers", headers); 111 | respondJSON(servletResponse, os, response); 112 | baseRequest.setHandled(true); 113 | return; 114 | } else if (method.equals("GET") && uri.equals("/ip")) { 115 | JSONObject response = new JSONObject(); 116 | response.put("origin", request.getRemoteAddr()); 117 | respondJSON(servletResponse, os, response); 118 | baseRequest.setHandled(true); 119 | return; 120 | } else if (method.equals("GET") && uri.equals("/user-agent")) { 121 | JSONObject response = new JSONObject(); 122 | response.put("user-agent", request.getHeader("User-Agent")); 123 | respondJSON(servletResponse, os, response); 124 | baseRequest.setHandled(true); 125 | return; 126 | } else if (method.equals("GET") && uri.equals("/gzip")) { 127 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 128 | 129 | JSONObject response = new JSONObject(); 130 | response.put("args", mapParametersToJSON(request)); 131 | response.put("headers", mapHeadersToJSON(request)); 132 | response.put("origin", request.getRemoteAddr()); 133 | response.put("url", getFullURL(request)); 134 | response.put("gzipped", true); 135 | 136 | byte[] uncompressed = response.toString(/*indent=*/ 2).getBytes( 137 | StandardCharsets.UTF_8); 138 | ByteArrayOutputStream baos = new ByteArrayOutputStream( 139 | uncompressed.length); 140 | try (GZIPOutputStream gzipos = new GZIPOutputStream(baos)) { 141 | gzipos.write(uncompressed); 142 | } 143 | byte[] compressed = baos.toByteArray(); 144 | 145 | servletResponse.setContentLength(compressed.length); 146 | servletResponse.setHeader("Content-Encoding", "gzip"); 147 | servletResponse.setContentType("application/json"); 148 | servletResponse.setStatus(HttpServletResponse.SC_OK); 149 | os.write(compressed); 150 | os.flush(); 151 | baseRequest.setHandled(true); 152 | return; 153 | } else if (method.equals("GET") && uri.equals("/deflate")) { 154 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 155 | 156 | JSONObject response = new JSONObject(); 157 | response.put("args", mapParametersToJSON(request)); 158 | response.put("headers", mapHeadersToJSON(request)); 159 | response.put("origin", request.getRemoteAddr()); 160 | response.put("url", getFullURL(request)); 161 | response.put("deflated", true); 162 | 163 | byte[] uncompressed = response.toString(/*indent=*/ 2).getBytes( 164 | StandardCharsets.UTF_8); 165 | ByteArrayOutputStream baos = new ByteArrayOutputStream( 166 | uncompressed.length); 167 | try (DeflaterOutputStream dos = new DeflaterOutputStream( 168 | baos, new Deflater(Deflater.DEFAULT_COMPRESSION, 169 | /*nowrap=*/ true))) { 170 | dos.write(uncompressed); 171 | } 172 | byte[] compressed = baos.toByteArray(); 173 | 174 | servletResponse.setContentLength(compressed.length); 175 | servletResponse.setHeader("Content-Encoding", "deflate"); 176 | servletResponse.setContentType("application/json"); 177 | servletResponse.setStatus(HttpServletResponse.SC_OK); 178 | os.write(compressed); 179 | os.flush(); 180 | baseRequest.setHandled(true); 181 | return; 182 | } else if (method.equals("GET") && uri.equals("/cache")) { 183 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 184 | 185 | if (request.getHeader("If-Modified-Since") != null || 186 | request.getHeader("If-None-Match") != null) { 187 | servletResponse.setStatus( 188 | HttpServletResponse.SC_NOT_MODIFIED); 189 | baseRequest.setHandled(true); 190 | return; 191 | } 192 | 193 | JSONObject response = new JSONObject(); 194 | response.put("args", mapParametersToJSON(request)); 195 | response.put("headers", mapHeadersToJSON(request)); 196 | response.put("origin", request.getRemoteAddr()); 197 | response.put("url", getFullURL(request)); 198 | 199 | respondJSON(servletResponse, os, response); 200 | baseRequest.setHandled(true); 201 | return; 202 | } else if (method.equals("GET") && uri.startsWith("/cache/")) { 203 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 204 | 205 | int seconds = Integer.parseInt(uri.substring( 206 | "/cache/".length())); 207 | 208 | JSONObject response = new JSONObject(); 209 | response.put("args", mapParametersToJSON(request)); 210 | response.put("headers", mapHeadersToJSON(request)); 211 | response.put("origin", request.getRemoteAddr()); 212 | response.put("url", getFullURL(request)); 213 | 214 | servletResponse.setHeader("Cache-Control", 215 | "public, max-age=" + seconds); 216 | respondJSON(servletResponse, os, response); 217 | baseRequest.setHandled(true); 218 | return; 219 | } else if (method.equals("GET") && uri.startsWith("/delay/")) { 220 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 221 | 222 | int delayMs = (int) (1000 * Double.parseDouble(uri.substring( 223 | "/delay/".length()))); 224 | try { 225 | Thread.sleep(Math.min(delayMs, MAX_DELAY_MS)); 226 | } catch (InterruptedException ie) { 227 | // ignore 228 | } 229 | 230 | JSONObject response = new JSONObject(); 231 | response.put("args", mapParametersToJSON(request)); 232 | response.put("headers", mapHeadersToJSON(request)); 233 | response.put("origin", request.getRemoteAddr()); 234 | response.put("url", getFullURL(request)); 235 | 236 | respondJSON(servletResponse, os, response); 237 | baseRequest.setHandled(true); 238 | return; 239 | } else if (method.equals("GET") && uri.startsWith("/etag/")) { 240 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 241 | 242 | String eTag = uri.substring("/etag/".length()); 243 | 244 | String ifMatch = request.getHeader("If-Match"); 245 | if (ifMatch == null) { 246 | // nothing 247 | } else if (ifMatch.equals("*") || ifMatch.equals(eTag)) { 248 | servletResponse.setStatus(HttpServletResponse.SC_OK); 249 | servletResponse.setHeader("ETag", eTag); 250 | baseRequest.setHandled(true); 251 | return; 252 | } else { 253 | servletResponse.setStatus( 254 | HttpServletResponse.SC_PRECONDITION_FAILED); 255 | baseRequest.setHandled(true); 256 | return; 257 | } 258 | 259 | String ifNoneMatch = request.getHeader("If-None-Match"); 260 | if (ifNoneMatch == null) { 261 | // nothing 262 | } else if (ifNoneMatch.equals("*") || ifNoneMatch.equals( 263 | eTag)) { 264 | servletResponse.setStatus( 265 | HttpServletResponse.SC_NOT_MODIFIED); 266 | servletResponse.setHeader("ETag", eTag); 267 | baseRequest.setHandled(true); 268 | return; 269 | } 270 | 271 | servletResponse.setHeader("ETag", eTag); 272 | baseRequest.setHandled(true); 273 | return; 274 | } else if (method.equals("GET") && uri.equals("/drip")) { 275 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 276 | 277 | long durationMs = (long) (1000 * Utils.getDoubleParameter( 278 | request, "duration", 0.0)); 279 | int numBytes = Utils.getIntParameter(request, "numbytes", 10); 280 | if (numBytes <= 0) { 281 | servletResponse.setStatus( 282 | HttpServletResponse.SC_BAD_REQUEST); 283 | baseRequest.setHandled(true); 284 | return; 285 | } 286 | int code = Utils.getIntParameter(request, "code", 200); 287 | int delay = Utils.getIntParameter(request, "delay", 0); 288 | 289 | servletResponse.setStatus(code); 290 | Utils.sleepUninterruptibly(delay, TimeUnit.SECONDS); 291 | 292 | for (int i = 0; i < numBytes; ++i) { 293 | Utils.sleepUninterruptibly(durationMs / numBytes, 294 | TimeUnit.MILLISECONDS); 295 | os.write('*'); 296 | } 297 | 298 | baseRequest.setHandled(true); 299 | return; 300 | } else if (method.equals("GET") && uri.startsWith("/stream/")) { 301 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 302 | 303 | int responses = Integer.parseInt(uri.substring( 304 | "/stream/".length())); 305 | 306 | servletResponse.setContentType("application/json"); 307 | servletResponse.setStatus(HttpServletResponse.SC_OK); 308 | 309 | for (int i = 0; i < responses; ++i) { 310 | Utils.sleepUninterruptibly(1, TimeUnit.SECONDS); 311 | 312 | JSONObject response = new JSONObject(); 313 | response.put("args", mapParametersToJSON(request)); 314 | response.put("headers", mapHeadersToJSON(request)); 315 | response.put("origin", request.getRemoteAddr()); 316 | response.put("url", getFullURL(request)); 317 | response.put("id", i); 318 | 319 | byte[] body = response.toString().getBytes( 320 | StandardCharsets.UTF_8); 321 | os.write(body); 322 | os.write('\n'); 323 | os.flush(); 324 | } 325 | 326 | baseRequest.setHandled(true); 327 | return; 328 | } else if (method.equals("GET") && uri.startsWith( 329 | "/stream-bytes/")) { 330 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 331 | 332 | long numBytes = Long.parseLong(uri.substring( 333 | "/stream-bytes/".length())); 334 | 335 | int seed = Utils.getIntParameter(request, "seed", -1); 336 | int chunkSize = Utils.getIntParameter(request, "chunkSize", 337 | 200); 338 | byte[] buf = new byte[chunkSize]; 339 | Random random = seed == -1 ? new Random() : new Random(seed); 340 | 341 | servletResponse.setStatus(HttpServletResponse.SC_OK); 342 | 343 | for (long i = 0; i < numBytes; i += chunkSize) { 344 | random.nextBytes(buf); 345 | os.write(buf, 0, i + chunkSize > numBytes ? 346 | (int) (numBytes - i) : chunkSize); 347 | } 348 | 349 | baseRequest.setHandled(true); 350 | return; 351 | } else if ((method.equals("DELETE") && uri.equals("/delete")) || 352 | (method.equals("GET") && uri.equals("/get")) || 353 | (method.equals("PATCH") && uri.equals("/patch")) || 354 | (method.equals("POST") && uri.equals("/post")) || 355 | (method.equals("PUT") && uri.equals("/put"))) { 356 | JSONObject response = new JSONObject(); 357 | 358 | String contentType = request.getContentType(); 359 | if (contentType != null && contentType.startsWith( 360 | "multipart/form-data")) { 361 | MultiPartFormInputStream parser = 362 | new MultiPartFormInputStream( 363 | is, contentType, null, null); 364 | 365 | JSONObject data = new JSONObject(); 366 | for (Part part : parser.getParts()) { 367 | ByteArrayOutputStream baos = 368 | new ByteArrayOutputStream(); 369 | try (InputStream pis = part.getInputStream()) { 370 | Utils.copy(pis, baos); 371 | } 372 | data.put(part.getName(), new String(baos.toByteArray(), 373 | StandardCharsets.UTF_8)); 374 | } 375 | response.put("data", ""); 376 | response.put("form", data); 377 | response.put("json", JSONObject.NULL); 378 | } else { 379 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 380 | Utils.copy(is, baos); 381 | String string = new String( 382 | baos.toByteArray(), StandardCharsets.UTF_8); 383 | response.put("data", string); 384 | try { 385 | response.put("json", new JSONObject(string)); 386 | } catch (JSONException e) { 387 | // client can provide non-JSON data 388 | } 389 | } 390 | 391 | response.put("args", mapParametersToJSON(request)); 392 | response.put("headers", mapHeadersToJSON(request)); 393 | response.put("origin", request.getRemoteAddr()); 394 | response.put("url", getFullURL(request)); 395 | 396 | respondJSON(servletResponse, os, response); 397 | baseRequest.setHandled(true); 398 | return; 399 | } else if (uri.equals("/redirect-to")) { 400 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 401 | int statusCode = Utils.getIntParameter(request, "status_code", 402 | HttpServletResponse.SC_MOVED_TEMPORARILY); 403 | redirectTo(servletResponse, request.getParameter("url"), 404 | statusCode); 405 | baseRequest.setHandled(true); 406 | return; 407 | } else if (uri.startsWith("/redirect/") || 408 | uri.startsWith("/relative-redirect/")) { 409 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 410 | 411 | int count = Integer.parseInt(uri.substring( 412 | uri.startsWith("/redirect/") ? 413 | "/redirect/".length() : 414 | "/relative-redirect/".length())) - 1; 415 | if (count > 0) { 416 | StringBuilder path = new StringBuilder(); 417 | if ("true".equals(request.getParameter("absolute"))) { 418 | path.append(request.getRequestURL()); 419 | path.setLength(path.length() - uri.length()); 420 | path.append("/absolute-redirect/"); 421 | } else { 422 | path.append("/relative-redirect/"); 423 | } 424 | path.append(count); 425 | redirectTo(servletResponse, path.toString()); 426 | } else { 427 | redirectTo(servletResponse, "/get"); 428 | } 429 | 430 | baseRequest.setHandled(true); 431 | return; 432 | } else if (uri.startsWith("/absolute-redirect/")) { 433 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 434 | 435 | int count = Integer.parseInt(uri.substring( 436 | "/absolute-redirect/".length())) - 1; 437 | StringBuffer path = request.getRequestURL(); 438 | path.setLength(path.length() - uri.length()); 439 | if (count > 0) { 440 | path.append("/absolute-redirect/") 441 | .append(count); 442 | redirectTo(servletResponse, path.toString()); 443 | } else { 444 | path.append("/get"); 445 | redirectTo(servletResponse, path.toString()); 446 | } 447 | 448 | baseRequest.setHandled(true); 449 | return; 450 | } else if (method.equals("GET") && 451 | uri.equals("/response-headers")) { 452 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 453 | for (String paramName : Collections.list( 454 | request.getParameterNames())) { 455 | servletResponse.addHeader(paramName, request.getParameter( 456 | paramName)); 457 | } 458 | servletResponse.setStatus(HttpServletResponse.SC_OK); 459 | baseRequest.setHandled(true); 460 | return; 461 | } else if (uri.equals("/cookies")) { 462 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 463 | 464 | JSONObject cookies = new JSONObject(); 465 | 466 | if (request.getCookies() != null) { 467 | for (Cookie cookie : request.getCookies()) { 468 | cookies.put(cookie.getName(), cookie.getValue()); 469 | } 470 | } 471 | 472 | JSONObject response = new JSONObject(); 473 | response.put("cookies", cookies); 474 | 475 | respondJSON(servletResponse, os, response); 476 | baseRequest.setHandled(true); 477 | return; 478 | } else if (uri.startsWith("/cookies/set")) { 479 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 480 | 481 | for (Map.Entry entry : 482 | request.getParameterMap().entrySet()) { 483 | for (String value : entry.getValue()) { 484 | servletResponse.addHeader("Set-Cookie", String.format( 485 | "%s=%s; Path=/", entry.getKey(), value)); 486 | } 487 | } 488 | 489 | servletResponse.setHeader("Location", "/cookies"); 490 | servletResponse.setStatus( 491 | HttpServletResponse.SC_MOVED_TEMPORARILY); 492 | baseRequest.setHandled(true); 493 | return; 494 | } else if (uri.startsWith("/cookies/delete")) { 495 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 496 | 497 | for (Map.Entry entry : 498 | request.getParameterMap().entrySet()) { 499 | servletResponse.addHeader("Set-Cookie", String.format( 500 | "%s=; Path=/", entry.getKey())); 501 | } 502 | 503 | servletResponse.setHeader("Location", "/cookies"); 504 | servletResponse.setStatus( 505 | HttpServletResponse.SC_MOVED_TEMPORARILY); 506 | baseRequest.setHandled(true); 507 | return; 508 | } else if (uri.startsWith("/basic-auth/")) { 509 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 510 | handleBasicAuth(request, servletResponse, os, 511 | uri.substring("/basic-auth/".length()), 512 | HttpServletResponse.SC_UNAUTHORIZED); 513 | baseRequest.setHandled(true); 514 | return; 515 | } else if (uri.startsWith("/hidden-basic-auth/")) { 516 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 517 | handleBasicAuth(request, servletResponse, os, 518 | uri.substring("/hidden-basic-auth/".length()), 519 | HttpServletResponse.SC_NOT_FOUND); 520 | baseRequest.setHandled(true); 521 | return; 522 | } else if (uri.startsWith("/anything")) { 523 | servletResponse.setStatus(HttpServletResponse.SC_OK); 524 | 525 | final JSONObject response = new JSONObject(); 526 | 527 | // Method 528 | response.put("method", method); 529 | response.put("args", mapParametersToJSON(request)); 530 | response.put("headers", mapHeadersToJSON(request)); 531 | response.put("origin", request.getRemoteAddr()); 532 | response.put("url", getFullURL(request)); 533 | 534 | // Body data 535 | final ByteArrayOutputStream data = new ByteArrayOutputStream(); 536 | Utils.copy(is, data); 537 | 538 | response.put("data", data.toString(StandardCharsets.UTF_8)); 539 | respondJSON(servletResponse, os, response); 540 | baseRequest.setHandled(true); 541 | return; 542 | } else if (method.equals("GET") && uri.startsWith("/bytes/")) { 543 | long length = Long.parseLong(uri.substring( 544 | "/bytes/".length())); 545 | int seed = Utils.getIntParameter(request, "seed", -1); 546 | Random random = seed != -1 ? new Random(seed) : new Random(); 547 | 548 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 549 | servletResponse.setStatus(HttpServletResponse.SC_OK); 550 | servletResponse.setContentLengthLong(length); 551 | byte[] buffer = new byte[4096]; 552 | for (long i = 0; i < length;) { 553 | int count = (int) Math.min(buffer.length, length - i); 554 | random.nextBytes(buffer); 555 | os.write(buffer, 0, count); 556 | i += count; 557 | } 558 | baseRequest.setHandled(true); 559 | return; 560 | } else if (method.equals("GET") && uri.startsWith("/base64/")) { 561 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 562 | byte[] body = Base64.getDecoder().decode( 563 | uri.substring("/base64/".length())); 564 | servletResponse.setStatus(HttpServletResponse.SC_OK); 565 | os.write(body); 566 | os.flush(); 567 | baseRequest.setHandled(true); 568 | return; 569 | } else if (method.equals("GET") && uri.startsWith("/range/")) { 570 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 571 | 572 | long size = Long.parseLong(uri.substring("/range/".length())); 573 | long start; 574 | long end; 575 | String range = request.getHeader("Range"); 576 | if (range != null && range.startsWith("bytes=")) { 577 | range = range.substring("bytes=".length()); 578 | String[] ranges = range.split("-", 2); 579 | if (ranges[0].isEmpty()) { 580 | start = size - Long.parseLong(ranges[1]); 581 | end = size - 1; 582 | } else if (ranges[1].isEmpty()) { 583 | start = Long.parseLong(ranges[0]); 584 | end = size - 1; 585 | } else { 586 | start = Long.parseLong(ranges[0]); 587 | end = Long.parseLong(ranges[1]); 588 | } 589 | if (end + 1 > size || start > end) { 590 | servletResponse.setStatus(HttpServletResponse. 591 | SC_REQUESTED_RANGE_NOT_SATISFIABLE); 592 | servletResponse.addHeader("ETag", "range" + size); 593 | servletResponse.addHeader("Content-Range", 594 | "bytes */" + size); 595 | baseRequest.setHandled(true); 596 | return; 597 | } 598 | servletResponse.setStatus( 599 | HttpServletResponse.SC_PARTIAL_CONTENT); 600 | } else { 601 | start = 0; 602 | end = size - 1; 603 | servletResponse.setStatus(HttpServletResponse.SC_OK); 604 | } 605 | 606 | servletResponse.addHeader("ETag", "range" + size); 607 | servletResponse.addHeader("Content-Length", 608 | String.valueOf(end - start + 1)); 609 | servletResponse.addHeader("Content-Range", 610 | "bytes " + start + "-" + end + "/" + size); 611 | servletResponse.addHeader("Accept-ranges", "bytes"); 612 | 613 | for (long i = start; i <= end; ++i) { 614 | os.write((char) ('a' + (i % 26))); 615 | } 616 | os.flush(); 617 | 618 | baseRequest.setHandled(true); 619 | return; 620 | } else if (method.equals("GET") && uri.equals("/image/jpeg")) { 621 | Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 622 | servletResponse.setStatus(HttpServletResponse.SC_OK); 623 | servletResponse.addHeader("Content-Type", "image/jpeg"); 624 | copyResource(servletResponse, "/image.jpg"); 625 | baseRequest.setHandled(true); 626 | return; 627 | } else if (method.equals("GET") && uri.equals("/image/png")) { 628 | servletResponse.setStatus(HttpServletResponse.SC_OK); 629 | servletResponse.addHeader("Content-Type", "image/png"); 630 | copyResource(servletResponse, "/image.png"); 631 | baseRequest.setHandled(true); 632 | return; 633 | } else if (method.equals("GET") && uri.equals("/html")) { 634 | servletResponse.setStatus(HttpServletResponse.SC_OK); 635 | servletResponse.addHeader("Content-Type", 636 | "text/html; charset=utf-8"); 637 | copyResource(servletResponse, "/text.html"); 638 | baseRequest.setHandled(true); 639 | return; 640 | } else if (method.equals("GET") && uri.equals("/xml")) { 641 | servletResponse.setStatus(HttpServletResponse.SC_OK); 642 | servletResponse.addHeader("Content-Type", "application/xml"); 643 | copyResource(servletResponse, "/text.xml"); 644 | baseRequest.setHandled(true); 645 | return; 646 | } else if (method.equals("GET") && uri.equals("/robots.txt")) { 647 | byte[] output = "User-agent: *\nDisallow: /deny\n".getBytes( 648 | StandardCharsets.UTF_8); 649 | 650 | servletResponse.setStatus(HttpServletResponse.SC_OK); 651 | servletResponse.setContentType("text/plain"); 652 | os.write(output); 653 | baseRequest.setHandled(true); 654 | return; 655 | } else if (method.equals("GET") && uri.equals("/deny")) { 656 | byte[] output = ( 657 | " .-''''''-." + 658 | " .' _ _ '." + 659 | " / O O \"" + 660 | ": :" + 661 | "| |" + 662 | ": __ :" + 663 | " \\ .-\"' '\"-. /" + 664 | " '. .'" + 665 | " '-......-'" + 666 | "YOU SHOULDN'T BE HERE").getBytes( 667 | StandardCharsets.UTF_8); 668 | 669 | servletResponse.setStatus(HttpServletResponse.SC_OK); 670 | servletResponse.setContentType("text/plain"); 671 | os.write(output); 672 | baseRequest.setHandled(true); 673 | return; 674 | } 675 | servletResponse.setStatus(501); 676 | baseRequest.setHandled(true); 677 | } catch (JSONException e) { 678 | logger.trace("JSONException", e); 679 | servletResponse.setStatus(500); 680 | baseRequest.setHandled(true); 681 | } 682 | } 683 | 684 | private static void respondJSON(HttpServletResponse response, 685 | OutputStream os, JSONObject obj) throws IOException { 686 | byte[] body = obj.toString(/*indent=*/ 2).getBytes( 687 | StandardCharsets.UTF_8); 688 | 689 | response.setContentLength(body.length); 690 | response.setContentType("application/json"); 691 | response.setStatus(HttpServletResponse.SC_OK); 692 | os.write(body); 693 | os.flush(); 694 | } 695 | 696 | private static void redirectTo(HttpServletResponse response, 697 | String location, int statusCode) { 698 | response.setHeader("Location", location); 699 | response.setStatus(statusCode); 700 | } 701 | 702 | private static void redirectTo(HttpServletResponse response, 703 | String location) { 704 | redirectTo(response, location, 705 | HttpServletResponse.SC_MOVED_TEMPORARILY); 706 | } 707 | 708 | private void copyResource(HttpServletResponse response, String resource) 709 | throws IOException { 710 | try (InputStream is = getClass().getResourceAsStream(resource)) { 711 | long length = Utils.copy(is, Utils.NULL_OUTPUT_STREAM); 712 | response.setContentLength((int) length); 713 | } 714 | try (InputStream is = getClass().getResourceAsStream(resource)) { 715 | Utils.copy(is, response.getOutputStream()); 716 | } 717 | } 718 | 719 | private static JSONObject mapHeadersToJSON(HttpServletRequest request) { 720 | JSONObject headers = new JSONObject(); 721 | 722 | for (String name : Collections.list(request.getHeaderNames())) { 723 | List values = Collections.list(request.getHeaders(name)); 724 | if (values.size() == 1) { 725 | headers.put(name, values.get(0)); 726 | } else { 727 | headers.put(name, new JSONArray(values)); 728 | } 729 | } 730 | 731 | return headers; 732 | } 733 | 734 | private static JSONObject mapParametersToJSON(HttpServletRequest request) { 735 | JSONObject headers = new JSONObject(); 736 | 737 | for (String name : Collections.list(request.getParameterNames())) { 738 | String[] values = request.getParameterValues(name); 739 | if (values.length == 1) { 740 | headers.put(name, values[0]); 741 | } else { 742 | headers.put(name, new JSONArray(values)); 743 | } 744 | } 745 | 746 | return headers; 747 | } 748 | 749 | private static String getFullURL(HttpServletRequest request) { 750 | StringBuilder requestURL = new StringBuilder( 751 | request.getRequestURL().toString()); 752 | String queryString = request.getQueryString(); 753 | if (queryString == null) { 754 | return requestURL.toString(); 755 | } else { 756 | return requestURL.append('?').append(queryString).toString(); 757 | } 758 | } 759 | 760 | private static void handleBasicAuth(HttpServletRequest request, 761 | HttpServletResponse servletResponse, OutputStream os, 762 | String suffix, int failureStatus) throws IOException { 763 | String header = request.getHeader("Authorization"); 764 | if (header == null || !header.startsWith("Basic ")) { 765 | servletResponse.setStatus(failureStatus); 766 | return; 767 | } 768 | 769 | byte[] bytes = Base64.getDecoder().decode( 770 | header.substring("Basic ".length())); 771 | String[] parts = new String( 772 | bytes, StandardCharsets.UTF_8).split(":", 2); 773 | String[] auth = suffix.split("/", 2); 774 | if (auth.length != 2 || !Arrays.equals(auth, parts)) { 775 | servletResponse.setStatus(failureStatus); 776 | return; 777 | } 778 | 779 | JSONObject response = new JSONObject(); 780 | response.put("authenticated", true); 781 | response.put("user", parts[0]); 782 | respondJSON(servletResponse, os, response); 783 | } 784 | } 785 | -------------------------------------------------------------------------------- /src/main/java/org/gaul/httpbin/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2023 Andrew Gaul 3 | * Copyright 2015-2016 Bounce Storage, Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * https://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package org.gaul.httpbin; 19 | 20 | import java.net.URI; 21 | 22 | public final class Main { 23 | private Main() { 24 | throw new AssertionError("intentionally not implemented"); 25 | } 26 | 27 | public static void main(String[] args) throws Exception { 28 | // TODO: configurable 29 | URI httpBinEndpoint = URI.create("http://127.0.0.1:8080"); 30 | 31 | HttpBin httpBin = new HttpBin(httpBinEndpoint); 32 | httpBin.start(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/gaul/httpbin/Utils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2023 Andrew Gaul 3 | * Copyright 2015-2016 Bounce Storage, Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * https://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package org.gaul.httpbin; 19 | 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | import java.io.OutputStream; 23 | import java.util.concurrent.TimeUnit; 24 | 25 | import jakarta.servlet.http.HttpServletRequest; 26 | 27 | final class Utils { 28 | static final OutputStream NULL_OUTPUT_STREAM = new OutputStream() { 29 | @Override 30 | public void write(int b) { 31 | } 32 | 33 | @Override 34 | public void write(byte[] b) { 35 | } 36 | 37 | @Override 38 | public void write(byte[] b, int off, int len) { 39 | } 40 | }; 41 | 42 | private Utils() { 43 | throw new AssertionError("intentionally not implemented"); 44 | } 45 | 46 | static long copy(InputStream from, OutputStream to) throws IOException { 47 | byte[] buf = new byte[4096]; 48 | long total = 0; 49 | while (true) { 50 | int r = from.read(buf); 51 | if (r == -1) { 52 | break; 53 | } 54 | to.write(buf, 0, r); 55 | total += r; 56 | } 57 | return total; 58 | } 59 | 60 | static void sleepUninterruptibly(long sleepFor, TimeUnit unit) { 61 | boolean interrupted = false; 62 | try { 63 | long remainingNanos = unit.toNanos(sleepFor); 64 | long end = System.nanoTime() + remainingNanos; 65 | while (true) { 66 | try { 67 | // TimeUnit.sleep() treats negative timeouts just like zero. 68 | TimeUnit.NANOSECONDS.sleep(remainingNanos); 69 | return; 70 | } catch (InterruptedException e) { 71 | interrupted = true; 72 | remainingNanos = end - System.nanoTime(); 73 | } 74 | } 75 | } finally { 76 | if (interrupted) { 77 | Thread.currentThread().interrupt(); 78 | } 79 | } 80 | } 81 | 82 | static int getIntParameter(HttpServletRequest request, String name, 83 | int defaultValue) { 84 | String value = request.getParameter(name); 85 | if (value == null) { 86 | return defaultValue; 87 | } 88 | return Integer.parseInt(value); 89 | } 90 | 91 | static double getDoubleParameter(HttpServletRequest request, String name, 92 | double defaultValue) { 93 | String value = request.getParameter(name); 94 | if (value == null) { 95 | return defaultValue; 96 | } 97 | return Double.parseDouble(value); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/resources/checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | -------------------------------------------------------------------------------- /src/main/resources/copyright_header.txt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2023 Andrew Gaul 3 | * Copyright 2015-2016 Bounce Storage, Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * https://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | -------------------------------------------------------------------------------- /src/main/resources/home.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | java-httpbin 5 | 6 | 7 |

java-httpbin

8 |

9 | 10 | Read documentation → 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/main/resources/image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gaul/java-httpbin/e6f2010114be4399f5f8a73c5b05c1d37889e30d/src/main/resources/image.jpg -------------------------------------------------------------------------------- /src/main/resources/image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gaul/java-httpbin/e6f2010114be4399f5f8a73c5b05c1d37889e30d/src/main/resources/image.png -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | %.-1p %d{MM-dd HH:mm:ss.SSS} %t %c{30}:%L %X{clientId}|%X{sessionId}:%X{messageId}:%X{fileId}] %m%n 5 | 6 | 7 | ${LOG_LEVEL:-info} 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/main/resources/text.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |

Herman Melville - Moby-Dick

7 | 8 |
9 |

10 | Availing himself of the mild, summer-cool weather that now reigned in these latitudes, and in preparation for the peculiarly active pursuits shortly to be anticipated, Perth, the begrimed, blistered old blacksmith, had not removed his portable forge to the hold again, after concluding his contributory work for Ahab's leg, but still retained it on deck, fast lashed to ringbolts by the foremast; being now almost incessantly invoked by the headsmen, and harpooneers, and bowsmen to do some little job for them; altering, or repairing, or new shaping their various weapons and boat furniture. Often he would be surrounded by an eager circle, all waiting to be served; holding boat-spades, pike-heads, harpoons, and lances, and jealously watching his every sooty movement, as he toiled. Nevertheless, this old man's was a patient hammer wielded by a patient arm. No murmur, no impatience, no petulance did come from him. Silent, slow, and solemn; bowing over still further his chronically broken back, he toiled away, as if toil were life itself, and the heavy beating of his hammer the heavy beating of his heart. And so it was.—Most miserable! A peculiar walk in this old man, a certain slight but painful appearing yawing in his gait, had at an early period of the voyage excited the curiosity of the mariners. And to the importunity of their persisted questionings he had finally given in; and so it came to pass that every one now knew the shameful story of his wretched fate. Belated, and not innocently, one bitter winter's midnight, on the road running between two country towns, the blacksmith half-stupidly felt the deadly numbness stealing over him, and sought refuge in a leaning, dilapidated barn. The issue was, the loss of the extremities of both feet. Out of this revelation, part by part, at last came out the four acts of the gladness, and the one long, and as yet uncatastrophied fifth act of the grief of his life's drama. He was an old man, who, at the age of nearly sixty, had postponedly encountered that thing in sorrow's technicals called ruin. He had been an artisan of famed excellence, and with plenty to do; owned a house and garden; embraced a youthful, daughter-like, loving wife, and three blithe, ruddy children; every Sunday went to a cheerful-looking church, planted in a grove. But one night, under cover of darkness, and further concealed in a most cunning disguisement, a desperate burglar slid into his happy home, and robbed them all of everything. And darker yet to tell, the blacksmith himself did ignorantly conduct this burglar into his family's heart. It was the Bottle Conjuror! Upon the opening of that fatal cork, forth flew the fiend, and shrivelled up his home. Now, for prudent, most wise, and economic reasons, the blacksmith's shop was in the basement of his dwelling, but with a separate entrance to it; so that always had the young and loving healthy wife listened with no unhappy nervousness, but with vigorous pleasure, to the stout ringing of her young-armed old husband's hammer; whose reverberations, muffled by passing through the floors and walls, came up to her, not unsweetly, in her nursery; and so, to stout Labor's iron lullaby, the blacksmith's infants were rocked to slumber. Oh, woe on woe! Oh, Death, why canst thou not sometimes be timely? Hadst thou taken this old blacksmith to thyself ere his full ruin came upon him, then had the young widow had a delicious grief, and her orphans a truly venerable, legendary sire to dream of in their after years; and all of them a care-killing competency. 11 |

12 |
13 | 14 | -------------------------------------------------------------------------------- /src/main/resources/text.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 10 | 11 | 12 | 13 | Wake up to WonderWidgets! 14 | 15 | 16 | 17 | 18 | Overview 19 | Why WonderWidgets are great 20 | 21 | Who buys WonderWidgets 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/test/java/org/gaul/httpbin/HttpBinTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2023 Andrew Gaul 3 | * Copyright 2015-2016 Bounce Storage, Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * https://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package org.gaul.httpbin; 19 | 20 | import static org.assertj.core.api.Assertions.assertThat; 21 | 22 | import java.net.URI; 23 | 24 | import org.eclipse.jetty.client.HttpClient; 25 | import org.eclipse.jetty.client.api.ContentResponse; 26 | import org.eclipse.jetty.client.util.MultiPartContentProvider; 27 | import org.eclipse.jetty.client.util.StringContentProvider; 28 | import org.json.JSONObject; 29 | import org.junit.After; 30 | import org.junit.Before; 31 | import org.junit.Test; 32 | import org.slf4j.Logger; 33 | import org.slf4j.LoggerFactory; 34 | 35 | public final class HttpBinTest { 36 | private static final Logger logger = LoggerFactory.getLogger( 37 | HttpBinTest.class); 38 | 39 | private URI httpBinEndpoint = URI.create("http://127.0.0.1:0"); 40 | 41 | private HttpBin httpBin; 42 | private HttpClient client; 43 | 44 | @Before 45 | public void setUp() throws Exception { 46 | httpBin = new HttpBin(httpBinEndpoint); 47 | httpBin.start(); 48 | 49 | // reset endpoint to handle zero port 50 | httpBinEndpoint = new URI(httpBinEndpoint.getScheme(), 51 | httpBinEndpoint.getUserInfo(), httpBinEndpoint.getHost(), 52 | httpBin.getPort(), httpBinEndpoint.getPath(), 53 | httpBinEndpoint.getQuery(), httpBinEndpoint.getFragment()); 54 | logger.debug("HttpBin listening on {}", httpBinEndpoint); 55 | 56 | client = new HttpClient(); 57 | client.start(); 58 | } 59 | 60 | @After 61 | public void tearDown() throws Exception { 62 | if (client != null) { 63 | client.stop(); 64 | } 65 | if (httpBin != null) { 66 | httpBin.stop(); 67 | } 68 | } 69 | 70 | @Test 71 | public void testPostData() throws Exception { 72 | String input = "{\"foo\": 42}"; 73 | ContentResponse response = client.POST(httpBinEndpoint + "/post") 74 | .content(new StringContentProvider(input), "application/json") 75 | .send(); 76 | assertThat(response.getStatus()).as("status").isEqualTo(200); 77 | JSONObject object = new JSONObject(response.getContentAsString()); 78 | assertThat(object.getString("data")).isEqualTo(input); 79 | } 80 | 81 | @Test 82 | public void testPostDataMultipartContent() throws Exception { 83 | JSONObject input = new JSONObject(); 84 | input.put("field1", "foo"); 85 | input.put("field2", "bar"); 86 | MultiPartContentProvider multiPart = new MultiPartContentProvider(); 87 | multiPart.addFieldPart("field1", new StringContentProvider("foo"), 88 | null); 89 | multiPart.addFieldPart("field2", new StringContentProvider("bar"), 90 | null); 91 | multiPart.close(); 92 | 93 | ContentResponse response = client.POST(httpBinEndpoint + "/post") 94 | .content(multiPart) 95 | .send(); 96 | assertThat(response.getStatus()).as("status").isEqualTo(200); 97 | JSONObject object = new JSONObject(response.getContentAsString()); 98 | assertThat(object.getJSONObject("form").similar(input)).isTrue(); 99 | } 100 | 101 | @Test 102 | public void testPutData() throws Exception { 103 | String input = "{\"foo\": 42}"; 104 | ContentResponse response = client.newRequest(httpBinEndpoint + "/put") 105 | .method("PUT") 106 | .content(new StringContentProvider(input), "application/json") 107 | .send(); 108 | assertThat(response.getStatus()).as("status").isEqualTo(200); 109 | JSONObject object = new JSONObject(response.getContentAsString()); 110 | assertThat(object.getString("data")).isEqualTo(input); 111 | } 112 | } 113 | --------------------------------------------------------------------------------