From 9cde171935cff004ea1462d53d8d2ee827fe69d2 Mon Sep 17 00:00:00 2001 From: "James R. Perkins" Date: Wed, 11 Sep 2024 13:57:05 -0700 Subject: [PATCH] Initial commit Signed-off-by: James R. Perkins --- .github/dependabot.yml | 18 + .github/workflows/ci.yml | 55 +++ .gitignore | 47 +++ CODEOWNERS | 1 + CODE_OF_CONDUCT.md | 133 +++++++ CONTRIBUTING.adoc | 69 ++++ LICENSE | 201 ++++++++++ README.adoc | 31 ++ SECURITY.md | 21 + bom/bom/pom.xml | 28 ++ bom/project-bom/pom.xml | 84 ++++ bom/test-bom/pom.xml | 104 +++++ client/pom.xml | 110 ++++++ .../engines/jetty/JettyClientEngine.java | 344 +++++++++++++++++ .../engines/jetty/JettyClientResponse.java | 21 + .../client/jetty/JettyClientEngineTest.java | 362 ++++++++++++++++++ .../test/client/jetty/MultipartTest.java | 204 ++++++++++ client/src/test/resources/META-INF/beans.xml | 23 ++ dco.txt | 37 ++ pom.xml | 290 ++++++++++++++ 20 files changed, 2183 insertions(+) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 CODEOWNERS create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.adoc create mode 100644 LICENSE create mode 100644 README.adoc create mode 100644 SECURITY.md create mode 100644 bom/bom/pom.xml create mode 100644 bom/project-bom/pom.xml create mode 100644 bom/test-bom/pom.xml create mode 100644 client/pom.xml create mode 100644 client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyClientEngine.java create mode 100644 client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyClientResponse.java create mode 100644 client/src/test/java/org/jboss/resteasy/test/client/jetty/JettyClientEngineTest.java create mode 100644 client/src/test/java/org/jboss/resteasy/test/client/jetty/MultipartTest.java create mode 100644 client/src/test/resources/META-INF/beans.xml create mode 100644 dco.txt create mode 100644 pom.xml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..f36d7df --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,18 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "maven" + directory: "/" + schedule: + interval: "daily" + open-pull-requests-limit: 10 + - package-ecosystem: "github-actions" + # Workflow files stored in the + # default location of `.github/workflows` + directory: "/" + schedule: + interval: "daily" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..9d7893b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,55 @@ +# This workflow will build a Java project with Maven +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven + +name: Build and Test RESTEasy Jetty + +on: + push: + branches-ignore: + - 'dependabot/**' + pull_request: + branches: + - '**' + +jobs: + format-check: + runs-on: ubuntu-latest + timeout-minutes: 30 + + steps: + - uses: actions/checkout@v4 + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: 17 + distribution: 'temurin' + cache: 'maven' + - name: Validate Formatting + run: | + mvn -B validate formatter:validate -Denforcer.skip=true + mvn -B validate impsort:check -Denforcer.skip=true + build: + runs-on: ${{ matrix.os }} + needs: format-check + timeout-minutes: 90 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest ] + java: ['17', '21'] + + steps: + - uses: actions/checkout@v4 + - name: Set up JDK ${{ matrix.java }} + uses: actions/setup-java@v4 + with: + java-version: ${{ matrix.java }} + distribution: 'temurin' + cache: 'maven' + - name: Build with Maven - ${{ matrix.os }} - JDK ${{ matrix.java }} + run: mvn -B -ntp clean install -fae + - uses: actions/upload-artifact@v4 + if: failure() + with: + name: surefire-reports-${{ matrix.os }}-jdk-${{ matrix.java }} + path: '**/surefire-reports/' diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0b0caf9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,47 @@ +target +.cache + +# Intellij +################### +*.iml +*.ipr +*.iws +.idea + +# Eclipse +################### +**/.settings +**/.project +**/.classpath +**/.checkstyle +**/.factorypath + +# VS Code +################### +**/.vscode/ + +# Packages # +############ +# it's better to unpack these files and commit the raw source +# git has its own built in compression methods +*.7z +*.dmg +*.gz +*.iso +*.jar +*.rar +*.tar +*.zip + +# Logs and databases # +###################### +*.log + + +# files generated by test # +########################### +jaxrs/security/resteasy-crypto/*signed*.txt +myDB.script +myDB.properties + +.DS_Store diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..e454986 --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1 @@ +* @resteasy/reviewers \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..dee1f2d --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,133 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +James Perkins , Ron Sigal , +Rebecca Searls , Jim Ma and/or Li Wei Nan . +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations \ No newline at end of file diff --git a/CONTRIBUTING.adoc b/CONTRIBUTING.adoc new file mode 100644 index 0000000..b188816 --- /dev/null +++ b/CONTRIBUTING.adoc @@ -0,0 +1,69 @@ +:toc: + += Contributing Guide + +Want to contribute to the RESTEasy? We try to make it easy, and all contributions, even the smaller ones, +are more than welcome. This includes bug reports, fixes, documentation, etc. First though, please read this page +(including the small print at the end). + +== Legal + +All original contributions to RESTEasy are licensed under the +https://www.apache.org/licenses/LICENSE-2.0[ASL - Apache License], version 2.0 or later, or, if another license is +specified as governing the file or directory being modified, such other license. + +All contributions are subject to the https://developercertificate.org/[Developer Certificate of Origin (DCO)]. +The DCO text is also included verbatim in the [dco.txt](dco.txt) file in the root directory of the repository. + +== Reporting an issue + +This project uses https://github.com/resteasy/resteasy-jetty/issues[GitHub Issues] for filing issues. An account is required, However, +if you do not wish to signup for an account, you can open a https://github.com/resteasy/resteasy/discussions[discussion] +and we will assist you in filing an issue. + +If you believe you found a bug, and it's likely possible, please indicate a way to reproduce it, what you are seeing and +what you would expect to see. + +== Before you contribute + +To contribute, use GitHub Pull Requests, from your **own** fork. + +Also, make sure you have set up your Git authorship correctly: + +---- +git config --global user.name "Your Full Name" +git config --global user.email your.email@example.com +---- + +If you use different computers to contribute, please make sure the name is the same on all your computers. + +We use this information to acknowledge your contributions in release announcements. + +== Setup + +If you have not done so on this machine, you need to: + +* Install Git and configure your GitHub access +* Install Java SDK 11+ (OpenJDK recommended) + +=== IDE Config and Code Style + +RESTEasy has a strictly enforced code style. Code formatting is done by the Eclipse code formatter, using the config files +found in the https://github.com/resteasy/resteasy-dev-tools/tree/main/ide-config/src/main/resources[eclipse-code-formatter.xml] +file. By default, when you run `./mvnw install`, the code will be formatted automatically. +When submitting a pull request the CI build will fail if running the formatter results in any code changes, so it is +recommended that you always run a full Maven build before submitting a pull request. + +If you want to run the formatting without doing a full build, you can run `./mvnw process-sources`. + +==== Eclipse Setup + +Open the *Preferences* window, and then navigate to _Java_ -> _Code Style_ -> _Formatter_. Click _Import_ and then +select the `eclipse-code-formatter.xml` downloaded from the above link or clone the repository and navigate to the file. + +Next navigate to _Java_ -> _Code Style_ -> _Organize Imports_. Click _Import_ and select the `eclipse.importorder` file. + +==== IDEA Setup + +Install the https://plugins.jetbrains.com/plugin/6546-adapter-for-eclipse-code-formatter/[Adapter for Eclipse Code Formatter]. +See the https://github.com/krasa/EclipseCodeFormatter#instructions[documentation] on how to configure the plugin. \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + 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/README.adoc b/README.adoc new file mode 100644 index 0000000..e8d1270 --- /dev/null +++ b/README.adoc @@ -0,0 +1,31 @@ += RESTEasy + +image:https://github.com/resteasy/resteasy-jetty/actions/workflows/maven.yml/badge.svg[Github CI,link=https://github.com/resteasy/resteasy-jetty/actions] + +RESTEasy Jetty is a RESTEasy project aimed to provide integration with https://jetty.org[Eclipse Jetty]. + +== Documentation + +To read the documentation you can https://resteasy.dev/docs[read it online]. + +== Issues + +Issues are kept in https://github.com/resteasy/resteasy-jetty/issues[GitHub Issues]. + +== Build + +Currently, RESTEasy Jetty requires JDK 17+. + +If you want to build the project without running the tests, you need to pull down a clone of the RESTEasy repository and +run: + +[source,bash] +---- +$ mvn clean install +---- + +== Contribute + +You are most welcome to contribute to RESTEasy! + +Read the link:./CONTRIBUTING.adoc[Contribution guidelines] \ No newline at end of file diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..9c8895e --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,21 @@ +# Reporting of CVEs and Security Issues + +## The RESTEasy community and our sponsor, Red Hat, take security bugs very seriously + +We aim to take immediate action to address serious security-related problems that involve our projects. + +## Reporting of Security Issues + +When reporting a security vulnerability it is important to not accidentally broadcast to the world that the issue exists, as this makes it easier for people to exploit it. The software industry uses the term embargo to describe the time a security issue is known internally until it is public knowledge. + +Our preferred way of reporting security issues in RESTEasy and its related projects is listed below. + +### Email the mailing list + +The list at resteasy-security@redhat.com is the preferred mechanism for outside users to report security issues. A member of the RESTEasy team will open the required issues. + +### Other considerations + +If you would like to work with us on a fix for the security vulnerability, please include your GitHub username in the above email, and we will provide you access to a temporary private fork where we can collaborate on a fix without it being disclosed publicly, **including in your own publicly visible git repository**. + +Do not open a public issue, send a pull request, or disclose any information about the suspected vulnerability publicly, **including in your own publicly visible git repository**. If you discover any publicly disclosed security vulnerabilities, please notify us immediately through resteasy-security@redhat.com diff --git a/bom/bom/pom.xml b/bom/bom/pom.xml new file mode 100644 index 0000000..0b88c7a --- /dev/null +++ b/bom/bom/pom.xml @@ -0,0 +1,28 @@ + + 4.0.0 + + + dev.resteasy.jetty + resteasy-jetty-parent + 1.0.0.Final-SNAPSHOT + ../../pom.xml + + + resteasy-jetty-bom + pom + + RESTEasy Jetty Maven (BOM) + + + + + + dev.resteasy.jetty + resteasy-jetty-client + ${project.version + + + + + diff --git a/bom/project-bom/pom.xml b/bom/project-bom/pom.xml new file mode 100644 index 0000000..57f17d0 --- /dev/null +++ b/bom/project-bom/pom.xml @@ -0,0 +1,84 @@ + + + + + + + dev.resteasy.jetty + resteasy-jetty-parent + 1.0.0.Final-SNAPSHOT + ../../pom.xml + + 4.0.0 + + resteasy-jetty-project-bom + pom + RESTEasy Jetty: BOM for Project Dependencies + + + + 10.0.0 + 12.0.13 + 3.6.1.Final + 6.2.10.Final + + + + + + jakarta.platform + jakarta.jakartaee-bom + ${version.jakarta.ee} + import + pom + + + org.eclipse.jetty + jetty-bom + ${version.org.eclipse.jetty} + import + pom + + + dev.resteasy.jetty + resteasy-jetty-bom + ${project.version} + pom + import + + + org.jboss.resteasy + resteasy-bom + ${version.org.jboss.resteasy} + import + pom + + + + org.jboss.logging + jboss-logging + ${version.org.jboss.logging} + + + + + \ No newline at end of file diff --git a/bom/test-bom/pom.xml b/bom/test-bom/pom.xml new file mode 100644 index 0000000..2dc6899 --- /dev/null +++ b/bom/test-bom/pom.xml @@ -0,0 +1,104 @@ + + + + + + + dev.resteasy.jetty + resteasy-jetty-parent + 1.0.0.Final-SNAPSHOT + ../../pom.xml + + 4.0.0 + + resteasy-jetty-test-bom + pom + RESTEasy Jetty: Test BOM + + + 1.0.0.Alpha2 + + 1.9.1.Final + 4.0.0.Final + 1.7.0.Final + 3.3.1 + + 5.11.0 + + 5.1.0.Beta4 + + + + + + + ${project.groupId} + resteasy-jetty-project-bom + ${project.version} + pom + import + + + org.junit + junit-bom + ${version.org.junit} + pom + import + + + org.jboss.arquillian + arquillian-bom + ${version.org.jboss.arquillian} + import + pom + + + org.wildfly.arquillian + wildfly-arquillian-bom + ${version.org.wildfly.arquillian} + import + pom + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-depchain + ${version.org.jboss.shrinkwrap.resolver} + pom + import + + + javax.enterprise + cdi-api + + + + + + dev.resteasy.junit.extension + resteasy-junit-extension + ${version.dev.resteasy.junit.extension} + test + + + + + \ No newline at end of file diff --git a/client/pom.xml b/client/pom.xml new file mode 100644 index 0000000..72f0c93 --- /dev/null +++ b/client/pom.xml @@ -0,0 +1,110 @@ + + + 4.0.0 + + dev.resteasy.jetty + resteasy-jetty-parent + 1.0.0.Final-SNAPSHOT + ../pom.xml + + + resteasy-client-jetty + RESTEasy Client - Jetty Engine + + + + + ${project.groupId} + resteasy-jetty-project-bom + ${project.version} + pom + import + + + ${project.groupId} + resteasy-jetty-test-bom + ${project.version} + pom + import + + + + + + + jakarta.ws.rs + jakarta.ws.rs-api + + + + org.jboss.resteasy + resteasy-client + + + + org.jboss.logging + jboss-logging + + + org.eclipse.jetty + jetty-client + + + + + jakarta.servlet + jakarta.servlet-api + test + + + jakarta.json + jakarta.json-api + test + + + dev.resteasy.junit.extension + resteasy-junit-extension + test + + + + + org.junit.jupiter + junit-jupiter + test + + + + + org.jboss.resteasy + resteasy-json-binding-provider + test + + + org.jboss.resteasy + resteasy-multipart-provider + test + + + + + org.jboss.resteasy + resteasy-undertow-cdi + test + + + org.eclipse.jetty + jetty-server + test + + + diff --git a/client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyClientEngine.java b/client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyClientEngine.java new file mode 100644 index 0000000..190fdae --- /dev/null +++ b/client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyClientEngine.java @@ -0,0 +1,344 @@ +package org.jboss.resteasy.client.jaxrs.engines.jetty; + +import java.io.InputStream; +import java.io.OutputStream; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.time.Duration; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; + +import jakarta.ws.rs.ProcessingException; +import jakarta.ws.rs.WebApplicationException; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.client.InvocationCallback; +import jakarta.ws.rs.client.ResponseProcessingException; +import jakarta.ws.rs.core.EntityPart; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.MultivaluedMap; + +import org.eclipse.jetty.client.HttpClient; +import org.eclipse.jetty.client.InputStreamResponseListener; +import org.eclipse.jetty.client.OutputStreamRequestContent; +import org.eclipse.jetty.client.Request; +import org.eclipse.jetty.client.Response; +import org.eclipse.jetty.http.HttpFields; +import org.jboss.logging.Logger; +import org.jboss.resteasy.client.jaxrs.engines.AsyncClientHttpEngine; +import org.jboss.resteasy.client.jaxrs.internal.ClientInvocation; +import org.jboss.resteasy.client.jaxrs.internal.ClientResponse; + +public class JettyClientEngine implements AsyncClientHttpEngine { + + private static final Logger LOGGER = Logger.getLogger(JettyClientEngine.class); + private static final MediaType MULTIPART_WILDCARD = new MediaType("multipart", "*"); + private static final Class MULTIPART_OUTPUT; + + static { + // Check if the org.jboss.resteasy.plugins.providers.multipart.MultipartOutput is on the class path + final String className = "org.jboss.resteasy.plugins.providers.multipart.MultipartOutput"; + Class multipartOutput = null; + try { + multipartOutput = Class.forName(className, false, resolveClassLoader()); + } catch (ClassNotFoundException e) { + LOGGER.tracef(e, "Failed to load %s", className); + } + + MULTIPART_OUTPUT = multipartOutput; + } + public static final String REQUEST_TIMEOUT_MS = JettyClientEngine.class + "$RequestTimeout"; + public static final String IDLE_TIMEOUT_MS = JettyClientEngine.class + "$IdleTimeout"; + // Yeah, this is the Jersey one, but there's no standard one and it makes more sense to reuse than make our own... + public static final String FOLLOW_REDIRECTS = "jersey.config.client.followRedirects"; + + private static final InvocationCallback NOP = new InvocationCallback() { + @Override + public void completed(ClientResponse response) { + } + + @Override + public void failed(Throwable throwable) { + } + }; + + private final HttpClient client; + + public JettyClientEngine(final HttpClient client) { + if (!client.isStarted()) { + try { + client.start(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + this.client = client; + } + + @Override + public SSLContext getSslContext() { + return client.getSslContextFactory().getSslContext(); + } + + @Override + public HostnameVerifier getHostnameVerifier() { + throw new UnsupportedOperationException(); + } + + @Override + public ClientResponse invoke(Invocation invocation) { + Future future = submit((ClientInvocation) invocation, false, NOP, null); + try { + return future.get(1, TimeUnit.HOURS); // There's already an idle and connect timeout, do we need one here? + } catch (InterruptedException e) { + future.cancel(true); + Thread.currentThread().interrupt(); + throw clientException(e, null); + } catch (TimeoutException | ExecutionException e) { + future.cancel(true); + throw clientException(e.getCause(), null); + } + } + + @Override + public Future submit(ClientInvocation invocation, boolean bufIn, InvocationCallback callback, + ResultExtractor extractor) { + return doSubmit(invocation, bufIn, callback, extractor); + } + + @Override + public CompletableFuture submit(ClientInvocation request, boolean buffered, ResultExtractor extractor, + ExecutorService executorService) { + return doSubmit(request, buffered, null, extractor); + } + + private CompletableFuture doSubmit(ClientInvocation invocation, boolean buffered, InvocationCallback callback, + ResultExtractor extractor) { + final ExecutorService asyncExecutor = invocation.asyncInvocationExecutor(); + + final Request request = client.newRequest(invocation.getUri()); + final CompletableFuture future = new RequestFuture(request); + + // Determine if this is a multipart request + final Object entity = invocation.getEntity(); + final boolean addBoundary = isMultipart(invocation) && canSetBoundary(entity); + + invocation.getMutableProperties().forEach(request::attribute); + request.method(invocation.getMethod()); + request.headers(mutableHeaders -> invocation.getHeaders().asMap() + .forEach((h, vs) -> vs.forEach(v -> { + String headerValue = v; + if (addBoundary && h.equalsIgnoreCase("content-type")) { + final MediaType mediaType = MediaType.valueOf(v); + // Set the boundary if needed + if (mediaType.getParameters().get("boundary") == null) { + headerValue = headerValue + "; boundary=" + UUID.randomUUID(); + // Replace the MediaType on the invocation if we've added a boundary + invocation.getHeaders().setMediaType(MediaType.valueOf(headerValue)); + } + } + mutableHeaders.add(h, headerValue); + }))); + configureTimeout(request); + if (request.getAttributes().get(FOLLOW_REDIRECTS) == Boolean.FALSE) { + request.followRedirects(false); + } + + if (entity != null) { + final OutputStreamRequestContent contentOut = new OutputStreamRequestContent( + Objects.toString(invocation.getHeaders().getMediaType(), null)); + asyncExecutor.execute(() -> { + try { + try (OutputStream bodyOut = contentOut.getOutputStream()) { + invocation.writeRequestBody(bodyOut); + } + } catch (Exception e) { // Also catch any exception thrown from close + future.completeExceptionally(e); + if (callback != null) { + callback.failed(e); + } + } + }); + request.body(contentOut); + } + + request.send(new InputStreamResponseListener() { + private ClientResponse cr; + + @Override + @SuppressWarnings("unchecked") + public void onHeaders(Response response) { + super.onHeaders(response); + InputStream inputStream = getInputStream(); + cr = new JettyClientResponse(invocation.getClientConfiguration(), inputStream); + cr.setProperties(invocation.getMutableProperties()); + cr.setStatus(response.getStatus()); + cr.setHeaders(extract(response.getHeaders())); + asyncExecutor.submit(() -> { + try { + if (buffered) { + cr.bufferEntity(); + } + complete(extractor == null ? (T) cr : extractor.extractResult(cr)); + } catch (Exception e) { + try { + inputStream.close(); + } catch (Exception e1) { + e.addSuppressed(e1); + } + onFailure(response, e); + } + }); + } + + @Override + public void onFailure(Response response, Throwable failure) { + super.onFailure(response, failure); + failed(failure); + } + + private void complete(T result) { + future.complete(result); + if (callback != null) { + callback.completed(result); + } + } + + private void failed(Throwable t) { + final RuntimeException x = clientException(t, cr); + future.completeExceptionally(x); + if (callback != null) { + callback.failed(x); + } + } + }); + return future; + } + + private void configureTimeout(final Request request) { + final Object timeout = request.getAttributes().get(REQUEST_TIMEOUT_MS); + final Object idleTimeout = request.getAttributes().get(IDLE_TIMEOUT_MS); + final long timeoutMs = parseTimeoutMs(timeout); + final long idleTimeoutMs = parseTimeoutMs(idleTimeout); + if (timeoutMs > 0) { + request.timeout(timeoutMs, TimeUnit.MILLISECONDS); + } + + if (idleTimeoutMs > 0) { + request.idleTimeout(idleTimeoutMs, TimeUnit.MILLISECONDS); + } + } + + private long parseTimeoutMs(final Object timeout) { + final long timeoutMs; + if (timeout instanceof Duration) { + timeoutMs = ((Duration) timeout).toMillis(); + } else if (timeout instanceof Number) { + timeoutMs = ((Number) timeout).intValue(); + } else if (timeout != null) { + timeoutMs = Integer.parseInt(timeout.toString()); + } else { + timeoutMs = -1; + } + return timeoutMs; + } + + @Override + public void close() { + try { + client.stop(); + } catch (Exception e) { + throw new RuntimeException("Unable to close JettyHttpEngine", e); + } + } + + MultivaluedMap extract(HttpFields headers) { + final MultivaluedMap extracted = new MultivaluedHashMap<>(); + headers.forEach(h -> extracted.add(h.getName(), h.getValue())); + return extracted; + } + + private static RuntimeException clientException(Throwable ex, jakarta.ws.rs.core.Response clientResponse) { + RuntimeException ret; + if (ex == null) { + final NullPointerException e = new NullPointerException(); + e.fillInStackTrace(); + ret = new ProcessingException(e); + } else if (ex instanceof WebApplicationException) { + ret = (WebApplicationException) ex; + } else if (ex instanceof ProcessingException) { + ret = (ProcessingException) ex; + } else if (clientResponse != null) { + ret = new ResponseProcessingException(clientResponse, ex); + } else { + ret = new ProcessingException(ex); + } + ret.fillInStackTrace(); + return ret; + } + + private static ClassLoader resolveClassLoader() { + if (System.getSecurityManager() == null) { + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + if (cl == null) { + cl = JettyClientEngine.class.getClassLoader(); + } + return cl == null ? ClassLoader.getSystemClassLoader() : cl; + } + return AccessController.doPrivileged((PrivilegedAction) () -> { + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + if (cl == null) { + cl = JettyClientEngine.class.getClassLoader(); + } + return cl == null ? ClassLoader.getSystemClassLoader() : cl; + }); + } + + private static boolean isMultipart(final ClientInvocation invocation) { + return MULTIPART_WILDCARD.isCompatible(invocation.getHeaders().getMediaType()); + } + + private static boolean canSetBoundary(final Object entity) { + if (MULTIPART_OUTPUT != null && MULTIPART_OUTPUT.isInstance(entity)) { + return true; + } + if (entity instanceof EntityPart) { + return true; + } + if (entity instanceof final List list) { + // We're a list, if we're not empty check the first type to see if it's an entity part + if (!list.isEmpty()) { + return list.get(0) instanceof EntityPart; + } + } + return false; + } + + static class RequestFuture extends CompletableFuture { + private final Request request; + + RequestFuture(final Request request) { + this.request = request; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + final boolean cancelled = super.cancel(mayInterruptIfRunning); + if (mayInterruptIfRunning && cancelled) { + request.abort(new CancellationException()); + } + return cancelled; + } + } +} diff --git a/client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyClientResponse.java b/client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyClientResponse.java new file mode 100644 index 0000000..f2e0c64 --- /dev/null +++ b/client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyClientResponse.java @@ -0,0 +1,21 @@ +package org.jboss.resteasy.client.jaxrs.engines.jetty; + +import java.io.InputStream; + +import org.jboss.resteasy.client.jaxrs.internal.ClientConfiguration; +import org.jboss.resteasy.client.jaxrs.internal.ClientResponse; +import org.jboss.resteasy.tracing.RESTEasyTracingLogger; + +class JettyClientResponse extends ClientResponse { + + JettyClientResponse(final ClientConfiguration configuration, final InputStream stream) { + super(configuration, RESTEasyTracingLogger.empty()); + setInputStream(stream); + } + + @Override + protected void setInputStream(final InputStream is) { + this.is = is; + resetEntity(); + } +} diff --git a/client/src/test/java/org/jboss/resteasy/test/client/jetty/JettyClientEngineTest.java b/client/src/test/java/org/jboss/resteasy/test/client/jetty/JettyClientEngineTest.java new file mode 100644 index 0000000..ba20bd1 --- /dev/null +++ b/client/src/test/java/org/jboss/resteasy/test/client/jetty/JettyClientEngineTest.java @@ -0,0 +1,362 @@ +package org.jboss.resteasy.test.client.jetty; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Random; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import jakarta.ws.rs.ProcessingException; +import jakarta.ws.rs.WebApplicationException; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import jakarta.ws.rs.client.ClientRequestContext; +import jakarta.ws.rs.client.ClientResponseContext; +import jakarta.ws.rs.client.ClientResponseFilter; +import jakarta.ws.rs.client.CompletionStageRxInvoker; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.StreamingOutput; + +import org.apache.http.entity.ContentType; +import org.eclipse.jetty.client.HttpClient; +import org.eclipse.jetty.http.HttpField; +import org.eclipse.jetty.http.HttpFields; +import org.eclipse.jetty.io.Content; +import org.eclipse.jetty.server.Handler; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.util.Callback; +import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; +import org.jboss.resteasy.client.jaxrs.engines.jetty.JettyClientEngine; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +public class JettyClientEngineTest { + Server server = new Server(0); + Client client; + + @AfterEach + public void stop() throws Exception { + if (client != null) { + client.close(); + } + server.stop(); + } + + private Client client() throws Exception { + if (!server.isStarted()) { + server.start(); + } + if (client == null) { + final HttpClient hc = new HttpClient(); + client = ((ResteasyClientBuilder) ClientBuilder.newBuilder()).httpEngine(new JettyClientEngine(hc)).build(); + } + return client; + } + + @Test + public void testSimple() throws Exception { + server.setHandler(new Handler.Abstract() { + @Override + public boolean handle(final Request request, final org.eclipse.jetty.server.Response response, + final Callback callback) throws Exception { + + if (request.getHeaders().get("User-Agent").contains("Apache")) { + response.setStatus(503); + } else if (!"abracadabra".equals(request.getHeaders().get("Password"))) { + response.setStatus(403); + } else { + response.setStatus(200); + Content.Sink.write(response, true, "Success", callback); + } + + return true; + } + }); + + final Response response = client().target(baseUri()).request() + .header("Password", "abracadabra") + .get(); + + assertEquals(200, response.getStatus()); + assertEquals("Success", response.readEntity(String.class)); + } + + @Test + public void testSimpleResponseRx() throws Exception { + server.setHandler(new Handler.Abstract() { + @Override + public boolean handle(final Request request, final org.eclipse.jetty.server.Response response, + final Callback callback) throws Exception { + + if (request.getHeaders().get("User-Agent").contains("Apache")) { + response.setStatus(503); + } else if (!"abracadabra".equals(request.getHeaders().get("Password"))) { + response.setStatus(403); + } else { + response.setStatus(200); + response.getHeaders().put(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType()); + Content.Sink.write(response, true, "Success", callback); + } + return true; + } + }); + + final CompletionStage cs = client().target(baseUri()).request() + .header("Password", "abracadabra").rx(CompletionStageRxInvoker.class) + .get(); + + Response response = cs.toCompletableFuture().get(); + assertEquals(200, response.getStatus()); + assertEquals("Success", response.readEntity(String.class)); + } + + @Test + public void testSimpleStringRx() throws Exception { + server.setHandler(new Handler.Abstract() { + @Override + public boolean handle(final Request request, final org.eclipse.jetty.server.Response response, + final Callback callback) throws Exception { + + if (request.getHeaders().get("User-Agent").contains("Apache")) { + response.setStatus(503); + } else if (!"abracadabra".equals(request.getHeaders().get("Password"))) { + response.setStatus(403); + } else { + response.setStatus(200); + response.getHeaders().put(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType()); + Content.Sink.write(response, true, "Success", callback); + } + return true; + } + }); + + final CompletionStage cs = client().target(baseUri()).request() + .header("Password", "abracadabra").rx(CompletionStageRxInvoker.class) + .get(String.class); + + String response = cs.toCompletableFuture().get(); + assertEquals("Success", response); + } + + @Test + public void testBigly() throws Exception { + server.setHandler(new EchoHandler()); + final byte[] valuableData = randomAlpha().getBytes(StandardCharsets.UTF_8); + final Response response = client().target(baseUri()).request() + .post(Entity.entity(valuableData, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + + assertEquals(200, response.getStatus()); + assertArrayEquals(valuableData, response.readEntity(byte[].class)); + } + + @Test + public void testFutureResponse() throws Exception { + server.setHandler(new EchoHandler()); + final String valuableData = randomAlpha(); + final Future response = client().target(baseUri()).request() + .buildPost(Entity.entity(valuableData, MediaType.APPLICATION_OCTET_STREAM_TYPE)) + .submit(); + + final Response resp = response.get(10, TimeUnit.SECONDS); + assertEquals(200, resp.getStatus()); + assertEquals(valuableData, resp.readEntity(String.class)); + } + + @Test + public void testFutureString() throws Exception { + server.setHandler(new EchoHandler()); + final String valuableData = randomAlpha(); + final Future response = client().target(baseUri()).request() + .buildPost(Entity.entity(valuableData, MediaType.APPLICATION_OCTET_STREAM_TYPE)) + .submit(String.class); + + final String result = response.get(10, TimeUnit.SECONDS); + assertEquals(valuableData.length(), result.length()); + assertEquals(valuableData, result); + } + + private String randomAlpha() { + final StringBuilder builder = new StringBuilder(); + final Random r = new Random(); + for (int i = 0; i < 20 * 1024 * 1024; i++) { + builder.append((char) ('a' + (char) r.nextInt('z' - 'a'))); + if (i % 100 == 0) + builder.append('\n'); + } + return builder.toString(); + } + + @Test + public void testTimeout() throws Exception { + server.setHandler(new Handler.Abstract() { + @Override + public boolean handle(final Request request, final org.eclipse.jetty.server.Response response, + final Callback callback) throws Exception { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + callback.failed(e); + Thread.currentThread().interrupt(); + throw new AssertionError(e); + } + return true; + } + }); + + try { + client().target(baseUri()).request() + .property(JettyClientEngine.REQUEST_TIMEOUT_MS, Duration.ofMillis(500)) + .get(); + fail(); + } catch (ProcessingException e) { + assertTrue(e.getCause() instanceof TimeoutException); + } + } + + @Test + public void testIdleTimeout() throws Exception { + server.setHandler(new Handler.Abstract() { + @Override + public boolean handle(final Request request, final org.eclipse.jetty.server.Response response, + final Callback callback) throws Exception { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError(e); + } + response.setStatus(200); + Content.Sink.write(response, true, "Success", callback); + return true; + } + }); + + try { + client().target(baseUri()).request() + .property(JettyClientEngine.REQUEST_TIMEOUT_MS, Duration.ofMillis(2000)) + .property(JettyClientEngine.IDLE_TIMEOUT_MS, Duration.ofMillis(500)) + .get(); + fail(); + } catch (ProcessingException e) { + assertTrue(e.getCause() instanceof TimeoutException); + } + + final Response response = client().target(baseUri()).request() + .property(JettyClientEngine.REQUEST_TIMEOUT_MS, Duration.ofMillis(2000)) + .property(JettyClientEngine.IDLE_TIMEOUT_MS, Duration.ofMillis(1500)) + .get(); + + assertEquals(200, response.getStatus()); + assertEquals("Success", response.readEntity(String.class)); + + } + + @Test + public void testDeferContent() throws Exception { + server.setHandler(new EchoHandler()); + final byte[] valuableData = randomAlpha().getBytes(StandardCharsets.UTF_8); + final Response response = client().target(baseUri()).request() + .post(Entity.entity(new StreamingOutput() { + @Override + public void write(OutputStream output) throws IOException, WebApplicationException { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError(e); + } + output.write(valuableData); + } + }, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + + assertEquals(200, response.getStatus()); + assertArrayEquals(valuableData, response.readEntity(byte[].class)); + } + + @Test + public void testFilterBufferReplay() throws Exception { + final String greeting = "Success"; + final byte[] expected = (greeting).getBytes(StandardCharsets.UTF_8); + server.setHandler(new Handler.Abstract() { + @Override + public boolean handle(final Request request, final org.eclipse.jetty.server.Response response, + final Callback callback) throws Exception { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError(e); + } + response.setStatus(200); + response.getHeaders().put(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType()); + Content.Sink.write(response, true, greeting, callback); + return true; + } + }); + + final byte[] content = new byte[expected.length]; + final ClientResponseFilter capturer = new ClientResponseFilter() { + @Override + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { + responseContext.getEntityStream().read(content); + } + }; + + try ( + InputStream response = client().register(capturer).target(baseUri()).request() + .get(InputStream.class)) { + // ignored, we are checking filter + } + + assertArrayEquals(expected, content); + } + + public URI baseUri() { + return URI.create("http://localhost:" + ((ServerConnector) server.getConnectors()[0]).getLocalPort()); + } + + static class EchoHandler extends Handler.Abstract { + + @Override + public boolean handle(final Request request, final org.eclipse.jetty.server.Response response, final Callback callback) + throws Exception { + response.setStatus(200); + long contentLength = -1; + for (HttpField field : request.getHeaders()) { + if (field.getHeader() != null) { + switch (field.getHeader()) { + case CONTENT_LENGTH -> { + response.getHeaders().add(field); + contentLength = field.getLongValue(); + } + case CONTENT_TYPE -> response.getHeaders().add(field); + case TRAILER -> response.setTrailersSupplier(HttpFields.build()); + case TRANSFER_ENCODING -> contentLength = Long.MAX_VALUE; + } + } + } + if (contentLength > 0) + Content.copy(request, response, org.eclipse.jetty.server.Response.newTrailersChunkProcessor(response), + callback); + else + callback.succeeded(); + return true; + } + } +} diff --git a/client/src/test/java/org/jboss/resteasy/test/client/jetty/MultipartTest.java b/client/src/test/java/org/jboss/resteasy/test/client/jetty/MultipartTest.java new file mode 100644 index 0000000..feb4db5 --- /dev/null +++ b/client/src/test/java/org/jboss/resteasy/test/client/jetty/MultipartTest.java @@ -0,0 +1,204 @@ +/* + * JBoss, Home of Professional Open Source. + * + * Copyright 2024 Red Hat, Inc., and individual contributors + * as indicated by the @author tags. + * + * 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 org.jboss.resteasy.test.client.jetty; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.context.RequestScoped; +import jakarta.inject.Inject; +import jakarta.json.Json; +import jakarta.json.JsonObject; +import jakarta.json.JsonObjectBuilder; +import jakarta.ws.rs.ApplicationPath; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.FormParam; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.ServerErrorException; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.core.Application; +import jakarta.ws.rs.core.EntityPart; +import jakarta.ws.rs.core.GenericEntity; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriBuilder; + +import org.eclipse.jetty.client.HttpClient; +import org.jboss.resteasy.client.jaxrs.engines.jetty.JettyClientEngine; +import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput; +import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import dev.resteasy.junit.extension.annotations.RestBootstrap; +import dev.resteasy.junit.extension.annotations.RestClientConfig; +import dev.resteasy.junit.extension.api.RestClientBuilderProvider; + +/** + * @author James R. Perkins + */ +@RestBootstrap(MultipartTest.TestApplication.class) +public class MultipartTest { + + public static class JettyClientBuilder implements RestClientBuilderProvider { + @Override + public ClientBuilder getClientBuilder() { + return ClientBuilder.newBuilder().register(new JettyClientEngine(new HttpClient())); + } + } + + @Inject + @RestClientConfig(JettyClientBuilder.class) + private Client client; + + @Test + public void checkEntityPart(final UriBuilder uriBuilder) throws IOException { + // Create the entity parts for the request + final List multipart = List.of( + EntityPart.withName("name") + .content("RESTEasy") + .mediaType(MediaType.TEXT_PLAIN_TYPE) + .build(), + EntityPart.withName("entity") + .content("entity-part") + .mediaType(MediaType.TEXT_PLAIN_TYPE) + .build(), + EntityPart.withName("data") + .content("test-data".getBytes(StandardCharsets.UTF_8)) + .mediaType(MediaType.APPLICATION_OCTET_STREAM_TYPE) + .build()); + try ( + Response response = client.target(uriBuilder.path("/echo/entity-parts")) + .request(MediaType.APPLICATION_JSON_TYPE) + .post(Entity.entity(new GenericEntity<>(multipart) { + }, MediaType.MULTIPART_FORM_DATA_TYPE))) { + assertResponse(response); + } + } + + @Test + public void checkMultipartFormData(final UriBuilder uriBuilder) { + final var multipart = new MultipartFormDataOutput(); + multipart.addFormData("name", "RESTEasy", MediaType.TEXT_PLAIN_TYPE); + multipart.addFormData("entity", "plain text", MediaType.APPLICATION_OCTET_STREAM_TYPE); + multipart.addFormData("data", "test", MediaType.APPLICATION_OCTET_STREAM_TYPE, "data.txt"); + final var multipartEntity = Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA); + final Invocation invocation = client.target(uriBuilder.path("/echo/multipart-form-data")) + .request() + .buildPost(multipartEntity); + try (Response response = invocation.invoke()) { + assertResponse(response); + } + } + + private static void assertResponse(final Response response) { + Assertions.assertEquals(200, response.getStatus(), + () -> String.format("Expected status of 200 got %d. Response: %s", response.getStatus(), + response.readEntity(String.class))); + final var json = response.readEntity(JsonObject.class); + final var headers = json.getJsonObject("headers"); + Assertions.assertNotNull(headers, () -> String.format("Failed to find headers in %s", json)); + final var contentType = headers.getJsonArray("content-type"); + Assertions.assertNotNull(contentType, () -> String.format("Failed to find content-type in %s", headers)); + Assertions.assertTrue(contentType.toString().contains("boundary"), + () -> String.format("Failed to find boundary in %s", contentType)); + } + + @ApplicationPath("/") + @ApplicationScoped + public static class TestApplication extends Application { + @Override + public Set> getClasses() { + return Set.of(TestResource.class); + } + } + + @Path("/echo") + @RequestScoped + public static class TestResource { + + @Inject + private HttpHeaders headers; + + @POST + @Path("entity-parts") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + public Response upload(@FormParam("name") final String name, @FormParam("data") final InputStream data, + @FormParam("entity") final EntityPart entityPart) { + final JsonObjectBuilder builder = Json.createObjectBuilder(); + addHeaders(builder); + builder.add("name", name); + + // Read the data into a string + try (data) { + builder.add("data", new String(data.readAllBytes())); + } catch (IOException e) { + throw new ServerErrorException("Failed to read data " + data, Response.Status.BAD_REQUEST); + } + try { + builder.add(entityPart.getName(), entityPart.getContent(String.class)); + } catch (IOException e) { + throw new ServerErrorException("Failed to read entity " + entityPart, Response.Status.BAD_REQUEST); + } + return Response.ok(builder.build()).build(); + } + + @POST + @Path("/multipart-form-data") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + public Response echo(final MultipartFormDataInput input) { + final JsonObjectBuilder builder = Json.createObjectBuilder(); + addHeaders(builder); + builder.add("name", readInputPart(input, "name")); + builder.add("data", readInputPart(input, "data")); + builder.add("entity", readInputPart(input, "entity")); + return Response.ok(builder.build()).build(); + } + + private String readInputPart(final MultipartFormDataInput input, final String name) { + try { + return input.getFormDataPart(name, String.class, null); + } catch (IOException e) { + throw new ServerErrorException("Failed to read entity input part " + name, Response.Status.BAD_REQUEST); + } + } + + private void addHeaders(final JsonObjectBuilder builder) { + final JsonObjectBuilder headerBuilder = Json.createObjectBuilder(); + headers.getRequestHeaders() + .forEach((headerName, values) -> headerBuilder.add(headerName.toLowerCase(Locale.ROOT), + Json.createArrayBuilder(values))); + builder.add("headers", headerBuilder.build()); + } + } +} diff --git a/client/src/test/resources/META-INF/beans.xml b/client/src/test/resources/META-INF/beans.xml new file mode 100644 index 0000000..9ab5fb9 --- /dev/null +++ b/client/src/test/resources/META-INF/beans.xml @@ -0,0 +1,23 @@ + + + + \ No newline at end of file diff --git a/dco.txt b/dco.txt new file mode 100644 index 0000000..8201f99 --- /dev/null +++ b/dco.txt @@ -0,0 +1,37 @@ +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. +1 Letterman Drive +Suite D4700 +San Francisco, CA, 94129 + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..2014b4e --- /dev/null +++ b/pom.xml @@ -0,0 +1,290 @@ + + + dev.resteasy.tools + resteasy-parent + 3 + + + + 4.0.0 + + RESTEasy Jetty Integration + RESTEasy integration for Eclipse Jetty + + dev.resteasy.jetty + resteasy-jetty-parent + 1.0.0.Final-SNAPSHOT + pom + + https://resteasy.dev + + + + Apache License 2.0 + https://repository.jboss.org/licenses/apache-2.0.txt + repo + + + + + + jamezp + James R. Perkins + jperkins@redhat.com + Red Hat + + project-owner + + -8 + + + + + bom/bom + bom/project-bom + bom/test-bom + client + + + + scm:git:git://github.com/resteasy/resteasy-jetty.git + scm:git:git@github.com:resteasy/resteasy-jetty.git + https://github.com/resteasy/resteasy-jetty/tree/main/ + + + + GitHub Issues + https://github.com/resteasy/resteasy-jetty/issues + + + + UTF-8 + + + 17 + + + 6.2.10.Final + 33.0.0.Final + 1.0.19 + + + + true + + 3.6.3 + + false + ${maven.test.skip} + ${skipTests} + + + true + false + + ${parsedVersion.majorVersion}.${parsedVersion.minorVersion} + + + 7.1.2.Final + 5.0.0.Final + + + -Djava.io.tmpdir=${project.build.directory} + + + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${version.org.eclipse.jetty} + + + + org.wildfly.galleon-plugins + wildfly-galleon-maven-plugin + ${version.org.wildfly.galleon-plugins} + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.org.wildfly.plugins.wildfly-maven-plugin} + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + check-style + compile + + checkstyle + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + + + ban-bad-dependencies + + enforce + + + + + true + + + javax.activation:activation + javax.activation:javax.activation-api + javax.enterprise:cdi-api + javax.inject:javax.inject + javax.json:javax.json-api + javax.persistence:javax.persistence-api + javax.persistence:persistence-api + javax.security.enterprise:javax.security.enterprise-api + javax.servlet:servlet-api + javax.transaction:jta + javax.validation:validation-api + javax.xml:jaxrpc-api + javax.xml.bind:jaxb-api + javax.xml.soap:saaj-api + javax.xml.stream:stax-api + log4j:log4j + + + + + + + dep-convergence + + enforce + + + + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + parse-version + initialize + + parse-version + + + + + + + net.revelc.code.formatter + formatter-maven-plugin + + + net.revelc.code + impsort-maven-plugin + + + sort-resource-imports + process-resources + + sort + + + ${project.basedir}/src/main/resources + ${project.basedir}/src/test/resources + + + + + + + + + + format-check + + + + + net.revelc.code.formatter + formatter-maven-plugin + + + validate-format + validate + + validate + + + + validate-format-resources + validate + + validate + + + ${project.basedir}/src/main/resources + ${project.basedir}/src/test/resources + + + + + + net.revelc.code + impsort-maven-plugin + + + check-import-sort + validate + + check + + + + check-import-sort-resources + validate + + check + + + ${project.basedir}/src/main/resources + ${project.basedir}/src/test/resources + + + + + + + + + debug-logs + + + debug.logs + + + + false + + + +