Migrate Structure

This commit is contained in:
sgibb
2023-09-11 16:10:01 -04:00
parent 30f5990517
commit ef02038d1e
671 changed files with 394 additions and 74536 deletions

View File

@@ -1,12 +0,0 @@
root=true
[*.java]
indent_style = tab
indent_size = 4
continuation_indent_size = 8
[*.xml]
indent_style = tab
indent_size = 4
continuation_indent_size = 8

View File

@@ -1,44 +0,0 @@
# Contributing
Spring Cloud is released under the non-restrictive Apache 2.0 license,
and follows a very standard Github development process, using Github
tracker for issues and merging pull requests into master. If you want
to contribute even something trivial please do not hesitate, but
follow the guidelines below.
## Sign the Contributor License Agreement
Before we accept a non-trivial patch or pull request we will need you to sign the
[Contributor License Agreement](https://cla.pivotal.io/sign/spring).
Signing the contributor's agreement does not grant anyone commit rights to the main
repository, but it does mean that we can accept your contributions, and you will get an
author credit if we do. Active contributors might be asked to join the core team, and
given the ability to merge pull requests.
## Code of Conduct
This project adheres to the Contributor Covenant [Code of conduct](https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc). By participating, you are expected to uphold this code. Please report
unacceptable behavior to spring-code-of-conduct@pivotal.io.
## Code Conventions and Housekeeping
None of these is essential for a pull request, but they will all help. They can also be
added after the original pull request but before a merge.
* Use the Spring Framework code format conventions. If you use Eclipse
you can import formatter settings using the
`eclipse-code-formatter.xml` file from the
[Spring Cloud Build](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml) project. If using IntelliJ, you can use the
[Eclipse Code Formatter Plugin](https://plugins.jetbrains.com/plugin/6546) to import the same file.
* Make sure all new `.java` files to have a simple Javadoc class comment with at least an
`@author` tag identifying you, and preferably at least a paragraph on what the class is
for.
* Add the ASF license header comment to all new `.java` files (copy from existing files
in the project)
* Add yourself as an `@author` to the .java files that you modify substantially (more
than cosmetic changes).
* Add some Javadocs and, if you change the namespace, some XSD doc elements.
* A few unit tests would help a lot as well -- someone has to do it.
* If no-one else is using your branch, please rebase it against the current master (or
other target branch in the main project).
* When writing a commit message please follow [these conventions](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html),
if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit
message (where XXXX is the issue number).

View File

@@ -1,20 +0,0 @@
<!--
Thanks for raising a Spring Cloud issue. What sort of issue are you raising?
Question
Please ask questions about how to use something, or to understand why something isn't
working as you expect it to, on Stack Overflow using the spring-cloud tag.
Bug report
Please provide details of the problem, including the version of Spring Cloud that you
are using. If possible, please provide a test case or sample application that reproduces
the problem. This makes it much easier for us to diagnose the problem and to verify that
we have fixed it.
Enhancement
Please start by describing the problem that you are trying to solve. There may already
be a solution, or there may be a way to solve it that you hadn't considered.
-->

View File

@@ -1,17 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: waiting-for-triage
assignees: ''
---
**Describe the bug**
Please provide details of the problem, including the version of Spring Cloud that you
are using.
**Sample**
If possible, please provide a test case or sample application that reproduces
the problem. This makes it much easier for us to diagnose the problem and to verify that
we have fixed it.

View File

@@ -1,20 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: waiting-for-triage
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

53
.github/workflows/deploy-docs.yml vendored Normal file
View File

@@ -0,0 +1,53 @@
name: Deploy Docs
run-name: ${{ format('{0} ({1})', github.workflow, github.event.inputs.build-refname || 'all') }}
on:
workflow_dispatch:
inputs:
build-refname:
description: Enter git refname to build (e.g., 5.7.x).
required: false
push:
branches: docs-build
env:
GRADLE_ENTERPRISE_SECRET_ACCESS_KEY: ${{ secrets.GRADLE_ENTERPRISE_SECRET_ACCESS_KEY }}
permissions:
contents: write
jobs:
build:
if: github.repository_owner == 'spring-cloud'
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 5
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
- name: Set up refname build
if: github.event.inputs.build-refname
run: |
git fetch --depth 1 https://github.com/$GITHUB_REPOSITORY ${{ github.event.inputs.build-refname }}
export BUILD_REFNAME=${{ github.event.inputs.build-refname }}
echo "BUILD_REFNAME=$BUILD_REFNAME" >> $GITHUB_ENV
export BUILD_VERSION=$(git cat-file --textconv FETCH_HEAD:pom.xml | python3 -c "import xml.etree.ElementTree as xml; from sys import stdin; print(xml.parse(stdin).getroot().find('{http://maven.apache.org/POM/4.0.0}version').text)")
echo BUILD_VERSION=$BUILD_VERSION >> $GITHUB_ENV
- name: Run Antora
run: |
./mvnw --no-transfer-progress -B antora
- name: Publish Docs
uses: rwinch/spring-doc-actions/rsync-antora-reference@httpdocs-path
with:
docs-username: ${{ secrets.DOCS_USERNAME }}
docs-host: ${{ secrets.DOCS_HOST }}
docs-ssh-key: ${{ secrets.DOCS_SSH_KEY }}
docs-ssh-host-key: ${{ secrets.DOCS_SSH_HOST_KEY }}
site-path: target/antora/site
- name: Bust Cloudflare Cache
uses: spring-io/spring-doc-actions/bust-cloudflare-antora-cache@v0.0.11
with:
context-root: spring-cloud-gateway
cloudflare-zone-id: ${{ secrets.CLOUDFLARE_ZONE_ID }}
cloudflare-cache-token: ${{ secrets.CLOUDFLARE_CACHE_TOKEN }}

View File

@@ -1,37 +0,0 @@
# 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
on:
push:
branches: [ main, 3.1.x ]
pull_request:
branches: [ main, 3.1.x ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up JDK
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: '17'
- name: Cache local Maven repository
uses: actions/cache@v3
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Build with Maven
run: ./mvnw clean install -B -U -Pspring -Dmaven.test.redirectTestOutputToFile=true -Dmaven.wagon.http.pool=false -Dmaven.wagon.httpconnectionManager.ttlSeconds=120
- name: Publish Test Report
uses: mikepenz/action-junit-report@v2
if: always() # always run even if the previous step fails
with:
report_paths: '**/surefire-reports/TEST-*.xml'

37
.gitignore vendored
View File

@@ -1,23 +1,22 @@
.DS_Store
*~
#*
*#
.#*
.classpath
.project
.settings/
.springBeans
target/
bin/
_site/
.idea
.settings/
.project
.classpath
*.orig
.springBeans
.factorypath
.sts4-cache
.ant-targets-build.xml
src/ant/.ant-targets-upload-dist.xml
*.sonar4clipse*
.DS_Store
*.iml
*.ipr
*.iws
.factorypath
*.log
.shelf
*.swp
*.swo
.vscode/
.flattened-pom.xml
/.idea/
*.graphml
node
node_modules
build
package.json
package-lock.json

View File

@@ -1 +0,0 @@
-P spring

117
.mvn/wrapper/MavenWrapperDownloader.java vendored Normal file
View File

@@ -0,0 +1,117 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

Binary file not shown.

View File

@@ -1,18 +1,2 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://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.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.0/apache-maven-3.9.0-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

View File

@@ -1,3 +0,0 @@
# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=17.0.1-tem

View File

@@ -1,83 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2013-2017 the original author or authors.
~
~ 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
~
~ https://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.
~
-->
<settings>
<servers>
<server>
<id>repo.spring.io</id>
<username>${env.CI_DEPLOY_USERNAME}</username>
<password>${env.CI_DEPLOY_PASSWORD}</password>
</server>
</servers>
<profiles>
<profile>
<!--
N.B. this profile is only here to support users and IDEs that do not use Maven 3.3.
It isn't needed on the command line if you use the wrapper script (mvnw) or if you use
a native Maven with the right version. Eclipse users should points their Maven tooling to
this settings file, or copy the profile into their ~/.m2/settings.xml.
-->
<id>spring</id>
<activation><activeByDefault>true</activeByDefault></activation>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/libs-snapshot-local</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone-local</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/release</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/libs-snapshot-local</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone-local</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
</settings>

201
LICENSE
View File

@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
https://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
https://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.

View File

@@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
https://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
https://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.

View File

@@ -1,341 +1,23 @@
////
DO NOT EDIT THIS FILE. IT WAS GENERATED.
Manual changes to this file will be lost when it is generated again.
Edit the files in the src/main/asciidoc/ directory instead.
////
= Spring Cloud Gateway Docs Build
You're currently viewing the Antora playbook branch.
The playbook branch hosts the docs build that is used to build and publish the production docs site.
image::https://github.com/spring-cloud/spring-cloud-gateway/workflows/Build/badge.svg?style=svg["Actions Status", link="https://github.com/spring-cloud/spring-cloud-gateway/actions"]
image::https://codecov.io/gh/spring-cloud/spring-cloud-gateway/branch/main/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-gateway/branch/main"]
The Spring Cloud Gateway reference docs are built using https://antora.org[Antora].
This README covers how to build the docs in a software branch as well as how to build the production docs site locally.
== Building the Site
This project provides an API Gateway built on top of the Spring Ecosystem, including: Spring 6, Spring Boot 3 and Project Reactor. Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them such as: security, monitoring/metrics, and resiliency.
== Features
* Java 17
* Spring Framework 6
* Spring Boot 3
* Dynamic routing
* Route matching built into Spring Handler Mapping
* Route matching on HTTP Request (Path, Method, Header, Host, etc...)
* Filters scoped to Matching Route
* Filters can modify downstream HTTP Request and HTTP Response (Add/Remove Headers, Add/Remove Parameters, Rewrite Path, Set Path, Hystrix, etc...)
* API or configuration driven
* Supports Spring Cloud `DiscoveryClient` for configuring Routes
== Building
:jdkversion: 17
=== Basic Compile and Test
To build the source you will need to install JDK {jdkversion}.
Spring Cloud uses Maven for most build-related activities, and you
should be able to get off the ground quite quickly by cloning the
project you are interested in and typing
You can build the entire site by invoking the following on the docs-build branch and then viewing the site at `target/site/index.html`
[source,bash]
----
$ ./mvnw install
./mvnw antora
----
NOTE: You can also install Maven (>=3.3.3) yourself and run the `mvn` command
in place of `./mvnw` in the examples below. If you do that you also
might need to add `-P spring` if your local Maven settings do not
contain repository declarations for spring pre-release artifacts.
== Building a Specific Branch
NOTE: Be aware that you might need to increase the amount of memory
available to Maven by setting a `MAVEN_OPTS` environment variable with
a value like `-Xmx512m -XX:MaxPermSize=128m`. We try to cover this in
the `.mvn` configuration, so if you find you have to do it to make a
build succeed, please raise a ticket to get the settings added to
source control.
The projects that require middleware (i.e. Redis) for testing generally
require that a local instance of [Docker](https://www.docker.com/get-started) is installed and running.
=== Documentation
The spring-cloud-build module has a "docs" profile, and if you switch
that on it will try to build asciidoc sources from
`src/main/asciidoc`. As part of that process it will look for a
`README.adoc` and process it by loading all the includes, but not
parsing or rendering it, just copying it to `${main.basedir}`
(defaults to `${basedir}`, i.e. the root of the project). If there are
any changes in the README it will then show up after a Maven build as
a modified file in the correct place. Just commit it and push the change.
=== Working with the code
If you don't have an IDE preference we would recommend that you use
https://www.springsource.com/developer/sts[Spring Tools Suite] or
https://eclipse.org[Eclipse] when working with the code. We use the
https://eclipse.org/m2e/[m2eclipse] eclipse plugin for maven support. Other IDEs and tools
should also work without issue as long as they use Maven 3.3.3 or better.
==== Activate the Spring Maven profile
Spring Cloud projects require the 'spring' Maven profile to be activated to resolve
the spring milestone and snapshot repositories. Use your preferred IDE to set this
profile to be active, or you may experience build errors.
==== Importing into eclipse with m2eclipse
We recommend the https://eclipse.org/m2e/[m2eclipse] eclipse plugin when working with
eclipse. If you don't already have m2eclipse installed it is available from the "eclipse
marketplace".
NOTE: Older versions of m2e do not support Maven 3.3, so once the
projects are imported into Eclipse you will also need to tell
m2eclipse to use the right profile for the projects. If you
see many different errors related to the POMs in the projects, check
that you have an up to date installation. If you can't upgrade m2e,
add the "spring" profile to your `settings.xml`. Alternatively you can
copy the repository settings from the "spring" profile of the parent
pom into your `settings.xml`.
==== Importing into eclipse without m2eclipse
If you prefer not to use m2eclipse you can generate eclipse project metadata using the
following command:
[indent=0]
[source,bash]
----
$ ./mvnw eclipse:eclipse
./mvnw antora
----
The generated eclipse projects can be imported by selecting `import existing projects`
from the `file` menu.
== Contributing
:spring-cloud-build-branch: master
Spring Cloud is released under the non-restrictive Apache 2.0 license,
and follows a very standard Github development process, using Github
tracker for issues and merging pull requests into master. If you want
to contribute even something trivial please do not hesitate, but
follow the guidelines below.
=== Sign the Contributor License Agreement
Before we accept a non-trivial patch or pull request we will need you to sign the
https://cla.pivotal.io/sign/spring[Contributor License Agreement].
Signing the contributor's agreement does not grant anyone commit rights to the main
repository, but it does mean that we can accept your contributions, and you will get an
author credit if we do. Active contributors might be asked to join the core team, and
given the ability to merge pull requests.
=== Code of Conduct
This project adheres to the Contributor Covenant https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc[code of
conduct]. By participating, you are expected to uphold this code. Please report
unacceptable behavior to spring-code-of-conduct@pivotal.io.
=== Code Conventions and Housekeeping
None of these is essential for a pull request, but they will all help. They can also be
added after the original pull request but before a merge.
* Use the Spring Framework code format conventions. If you use Eclipse
you can import formatter settings using the
`eclipse-code-formatter.xml` file from the
https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml[Spring
Cloud Build] project. If using IntelliJ, you can use the
https://plugins.jetbrains.com/plugin/6546[Eclipse Code Formatter
Plugin] to import the same file.
* Make sure all new `.java` files to have a simple Javadoc class comment with at least an
`@author` tag identifying you, and preferably at least a paragraph on what the class is
for.
* Add the ASF license header comment to all new `.java` files (copy from existing files
in the project)
* Add yourself as an `@author` to the .java files that you modify substantially (more
than cosmetic changes).
* Add some Javadocs and, if you change the namespace, some XSD doc elements.
* A few unit tests would help a lot as well -- someone has to do it.
* If no-one else is using your branch, please rebase it against the current master (or
other target branch in the main project).
* When writing a commit message please follow https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions],
if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit
message (where XXXX is the issue number).
=== Checkstyle
Spring Cloud Build comes with a set of checkstyle rules. You can find them in the `spring-cloud-build-tools` module. The most notable files under the module are:
.spring-cloud-build-tools/
----
└── src
   ├── checkstyle
   │   └── checkstyle-suppressions.xml <3>
   └── main
   └── resources
   ├── checkstyle-header.txt <2>
   └── checkstyle.xml <1>
----
<1> Default Checkstyle rules
<2> File header setup
<3> Default suppression rules
==== Checkstyle configuration
Checkstyle rules are *disabled by default*. To add checkstyle to your project just define the following properties and plugins.
.pom.xml
----
<properties>
<maven-checkstyle-plugin.failsOnError>true</maven-checkstyle-plugin.failsOnError> <1>
<maven-checkstyle-plugin.failsOnViolation>true
</maven-checkstyle-plugin.failsOnViolation> <2>
<maven-checkstyle-plugin.includeTestSourceDirectory>true
</maven-checkstyle-plugin.includeTestSourceDirectory> <3>
</properties>
<build>
<plugins>
<plugin> <4>
<groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId>
</plugin>
<plugin> <5>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
<reporting>
<plugins>
<plugin> <5>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
</reporting>
</build>
----
<1> Fails the build upon Checkstyle errors
<2> Fails the build upon Checkstyle violations
<3> Checkstyle analyzes also the test sources
<4> Add the Spring Java Format plugin that will reformat your code to pass most of the Checkstyle formatting rules
<5> Add checkstyle plugin to your build and reporting phases
If you need to suppress some rules (e.g. line length needs to be longer), then it's enough for you to define a file under `${project.root}/src/checkstyle/checkstyle-suppressions.xml` with your suppressions. Example:
.projectRoot/src/checkstyle/checkstyle-suppresions.xml
----
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Puppy Crawl//DTD Suppressions 1.1//EN"
"https://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions>
<suppress files=".*ConfigServerApplication\.java" checks="HideUtilityClassConstructor"/>
<suppress files=".*ConfigClientWatch\.java" checks="LineLengthCheck"/>
</suppressions>
----
It's advisable to copy the `${spring-cloud-build.rootFolder}/.editorconfig` and `${spring-cloud-build.rootFolder}/.springformat` to your project. That way, some default formatting rules will be applied. You can do so by running this script:
```bash
$ curl https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/.editorconfig -o .editorconfig
$ touch .springformat
```
=== IDE setup
==== Intellij IDEA
In order to setup Intellij you should import our coding conventions, inspection profiles and set up the checkstyle plugin.
The following files can be found in the https://github.com/spring-cloud/spring-cloud-build/tree/master/spring-cloud-build-tools[Spring Cloud Build] project.
.spring-cloud-build-tools/
----
└── src
   ├── checkstyle
   │   └── checkstyle-suppressions.xml <3>
   └── main
   └── resources
   ├── checkstyle-header.txt <2>
   ├── checkstyle.xml <1>
   └── intellij
      ├── Intellij_Project_Defaults.xml <4>
      └── Intellij_Spring_Boot_Java_Conventions.xml <5>
----
<1> Default Checkstyle rules
<2> File header setup
<3> Default suppression rules
<4> Project defaults for Intellij that apply most of Checkstyle rules
<5> Project style conventions for Intellij that apply most of Checkstyle rules
.Code style
image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-code-style.png[Code style]
Go to `File` -> `Settings` -> `Editor` -> `Code style`. There click on the icon next to the `Scheme` section. There, click on the `Import Scheme` value and pick the `Intellij IDEA code style XML` option. Import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml` file.
.Inspection profiles
image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-inspections.png[Code style]
Go to `File` -> `Settings` -> `Editor` -> `Inspections`. There click on the icon next to the `Profile` section. There, click on the `Import Profile` and import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml` file.
.Checkstyle
To have Intellij work with Checkstyle, you have to install the `Checkstyle` plugin. It's advisable to also install the `Assertions2Assertj` to automatically convert the JUnit assertions
image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-checkstyle.png[Checkstyle]
Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on the `+` icon in the `Configuration file` section. There, you'll have to define where the checkstyle rules should be picked from. In the image above, we've picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build's GitHub repository (e.g. for the `checkstyle.xml` : `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml`). We need to provide the following variables:
- `checkstyle.header.file` - please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` URL.
- `checkstyle.suppressions.file` - default suppressions. Please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` URL.
- `checkstyle.additional.suppressions.file` - this variable corresponds to suppressions in your local project. E.g. you're working on `spring-cloud-contract`. Then point to the `project-root/src/checkstyle/checkstyle-suppressions.xml` folder. Example for `spring-cloud-contract` would be: `/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`.
IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources.
=== Duplicate Finder
Spring Cloud Build brings along the `basepom:duplicate-finder-maven-plugin`, that enables flagging duplicate and conflicting classes and resources on the java classpath.
==== Duplicate Finder configuration
Duplicate finder is *enabled by default* and will run in the `verify` phase of your Maven build, but it will only take effect in your project if you add the `duplicate-finder-maven-plugin` to the `build` section of the projecst's `pom.xml`.
.pom.xml
[source,xml]
----
<build>
<plugins>
<plugin>
<groupId>org.basepom.maven</groupId>
<artifactId>duplicate-finder-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
----
For other properties, we have set defaults as listed in the https://github.com/basepom/duplicate-finder-maven-plugin/wiki[plugin documentation].
You can easily override them but setting the value of the selected property prefixed with `duplicate-finder-maven-plugin`. For example, set `duplicate-finder-maven-plugin.skip` to `true` in order to skip duplicates check in your build.
If you need to add `ignoredClassPatterns` or `ignoredResourcePatterns` to your setup, make sure to add them in the plugin configuration section of your project:
[source,xml]
----
<build>
<plugins>
<plugin>
<groupId>org.basepom.maven</groupId>
<artifactId>duplicate-finder-maven-plugin</artifactId>
<configuration>
<ignoredClassPatterns>
<ignoredClassPattern>org.joda.time.base.BaseDateTime</ignoredClassPattern>
<ignoredClassPattern>.*module-info</ignoredClassPattern>
</ignoredClassPatterns>
<ignoredResourcePatterns>
<ignoredResourcePattern>changelog.txt</ignoredResourcePattern>
</ignoredResourcePatterns>
</configuration>
</plugin>
</plugins>
</build>
----

View File

@@ -1,5 +0,0 @@
# Security Policy
## Reporting a Vulnerability
To report security vulnerabilities, please go to https://pivotal.io/security.

44
antora-playbook.yml Normal file
View File

@@ -0,0 +1,44 @@
antora:
extensions:
- '@springio/antora-extensions/partial-build-extension'
- require: '@springio/antora-extensions/latest-version-extension'
- require: '@springio/antora-extensions/inject-collector-cache-config-extension'
- '@antora/collector-extension'
- '@antora/atlas-extension'
- require: '@springio/antora-extensions/root-component-extension'
root_component_name: 'cloud-gateway'
site:
title: Spring Cloud Gateway
url: https://docs.spring.io/spring-cloud-gateway/reference
robots: allow
git:
ensure_git_suffix: false
content:
sources:
- url: https://github.com/spring-cloud/spring-cloud-gateway
# Refname matching:
# https://docs.antora.org/antora/latest/playbook/content-refname-matching/
branches: [ main ]
tags: [ '({4..9}).+({1..9}).+({0..9})?(-{RC,M}+({0..9}))', '!4.1.0-M1' ]
start_path: docs
asciidoc:
attributes:
page-stackoverflow-url: https://stackoverflow.com/tags/spring-cloud
page-pagination: ''
hide-uri-scheme: '@'
tabs-sync-option: '@'
extensions:
- '@asciidoctor/tabs'
- '@springio/asciidoctor-extensions'
urls:
latest_version_segment_strategy: redirect:to
latest_version_segment: ''
redirect_facility: httpd
ui:
bundle:
url: https://github.com/spring-io/antora-ui-spring/releases/download/v0.3.5/ui-bundle.zip
snapshot: true
runtime:
log:
failure_level: warn
format: pretty

View File

@@ -1,100 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway</artifactId>
<version>4.1.0-SNAPSHOT</version>
</parent>
<artifactId>spring-cloud-gateway-docs</artifactId>
<packaging>jar</packaging>
<name>Spring Cloud Gateway Docs</name>
<description>Spring Cloud Docs</description>
<properties>
<docs.main>spring-cloud-gateway</docs.main>
<main.basedir>${basedir}/..</main.basedir>
<configprops.inclusionPattern>spring.cloud.gateway.*</configprops.inclusionPattern>
<upload-docs-zip.phase>deploy</upload-docs-zip.phase>
<!-- Don't upload docs jar to central / repo.spring.io -->
<maven-deploy-plugin-default.phase>none</maven-deploy-plugin-default.phase>
<!-- Observability -->
<micrometer-docs-generator.version>1.0.0</micrometer-docs-generator.version>
<micrometer-docs-generator.inputPath>${maven.multiModuleProjectDirectory}/spring-cloud-gateway-server/</micrometer-docs-generator.inputPath>
<micrometer-docs-generator.inclusionPattern>.*</micrometer-docs-generator.inclusionPattern>
<micrometer-docs-generator.outputPath>${maven.multiModuleProjectDirectory}/docs/target/observability/</micrometer-docs-generator.outputPath>
</properties>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/asciidoc</sourceDirectory>
</build>
<profiles>
<profile>
<id>docs</id>
<build>
<plugins>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>generate-docs</id>
<phase>prepare-package</phase>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>io.micrometer.docs.DocsGeneratorCommand</mainClass>
<includePluginDependencies>true</includePluginDependencies>
<arguments>
<argument>${micrometer-docs-generator.inputPath}</argument>
<argument>${micrometer-docs-generator.inclusionPattern}</argument>
<argument>${micrometer-docs-generator.outputPath}</argument>
</arguments>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-docs-generator</artifactId>
<version>${micrometer-docs-generator.version}</version>
<type>jar</type>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

File diff suppressed because it is too large Load Diff

View File

@@ -1,330 +0,0 @@
#!/bin/bash -x
set -e
# Set default props like MAVEN_PATH, ROOT_FOLDER etc.
function set_default_props() {
# The script should be executed from the root folder
ROOT_FOLDER=`pwd`
echo "Current folder is ${ROOT_FOLDER}"
if [[ ! -e "${ROOT_FOLDER}/.git" ]]; then
echo "You're not in the root folder of the project!"
exit 1
fi
# Prop that will let commit the changes
COMMIT_CHANGES="no"
MAVEN_PATH=${MAVEN_PATH:-}
echo "Path to Maven is [${MAVEN_PATH}]"
REPO_NAME=${PWD##*/}
echo "Repo name is [${REPO_NAME}]"
SPRING_CLOUD_STATIC_REPO=${SPRING_CLOUD_STATIC_REPO:-git@github.com:spring-cloud/spring-cloud-static.git}
echo "Spring Cloud Static repo is [${SPRING_CLOUD_STATIC_REPO}"
}
# Check if gh-pages exists and docs have been built
function check_if_anything_to_sync() {
git remote set-url --push origin `git config remote.origin.url | sed -e 's/^git:/https:/'`
if ! (git remote set-branches --add origin gh-pages && git fetch -q); then
echo "No gh-pages, so not syncing"
exit 0
fi
if ! [ -d docs/target/generated-docs ] && ! [ "${BUILD}" == "yes" ]; then
echo "No gh-pages sources in docs/target/generated-docs, so not syncing"
exit 0
fi
}
function retrieve_current_branch() {
# Code getting the name of the current branch. For master we want to publish as we did until now
# https://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch
# If there is a branch already passed will reuse it - otherwise will try to find it
CURRENT_BRANCH=${BRANCH}
if [[ -z "${CURRENT_BRANCH}" ]] ; then
CURRENT_BRANCH=$(git symbolic-ref -q HEAD)
CURRENT_BRANCH=${CURRENT_BRANCH##refs/heads/}
CURRENT_BRANCH=${CURRENT_BRANCH:-HEAD}
fi
echo "Current branch is [${CURRENT_BRANCH}]"
git checkout ${CURRENT_BRANCH} || echo "Failed to check the branch... continuing with the script"
}
# Switches to the provided value of the release version. We always prefix it with `v`
function switch_to_tag() {
git checkout v${VERSION}
}
# Build the docs if switch is on
function build_docs_if_applicable() {
if [[ "${BUILD}" == "yes" ]] ; then
./mvnw clean install -P docs -pl docs -DskipTests
fi
}
# Get the name of the `docs.main` property
# Get whitelisted branches - assumes that a `docs` module is available under `docs` profile
function retrieve_doc_properties() {
MAIN_ADOC_VALUE=$("${MAVEN_PATH}"mvn -q \
-Dexec.executable="echo" \
-Dexec.args='${docs.main}' \
--non-recursive \
org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
echo "Extracted 'main.adoc' from Maven build [${MAIN_ADOC_VALUE}]"
WHITELIST_PROPERTY=${WHITELIST_PROPERTY:-"docs.whitelisted.branches"}
WHITELISTED_BRANCHES_VALUE=$("${MAVEN_PATH}"mvn -q \
-Dexec.executable="echo" \
-Dexec.args="\${${WHITELIST_PROPERTY}}" \
org.codehaus.mojo:exec-maven-plugin:1.3.1:exec \
-P docs \
-pl docs)
echo "Extracted '${WHITELIST_PROPERTY}' from Maven build [${WHITELISTED_BRANCHES_VALUE}]"
}
# Stash any outstanding changes
function stash_changes() {
git diff-index --quiet HEAD && dirty=$? || (echo "Failed to check if the current repo is dirty. Assuming that it is." && dirty="1")
if [ "$dirty" != "0" ]; then git stash; fi
}
# Switch to gh-pages branch to sync it with current branch
function add_docs_from_target() {
local DESTINATION_REPO_FOLDER
if [[ -z "${DESTINATION}" && -z "${CLONE}" ]] ; then
DESTINATION_REPO_FOLDER=${ROOT_FOLDER}
elif [[ "${CLONE}" == "yes" ]]; then
mkdir -p ${ROOT_FOLDER}/target
local clonedStatic=${ROOT_FOLDER}/target/spring-cloud-static
if [[ ! -e "${clonedStatic}/.git" ]]; then
echo "Cloning Spring Cloud Static to target"
git clone ${SPRING_CLOUD_STATIC_REPO} ${clonedStatic} && git checkout gh-pages
else
echo "Spring Cloud Static already cloned - will pull changes"
cd ${clonedStatic} && git checkout gh-pages && git pull origin gh-pages
fi
DESTINATION_REPO_FOLDER=${clonedStatic}/${REPO_NAME}
mkdir -p ${DESTINATION_REPO_FOLDER}
else
if [[ ! -e "${DESTINATION}/.git" ]]; then
echo "[${DESTINATION}] is not a git repository"
exit 1
fi
DESTINATION_REPO_FOLDER=${DESTINATION}/${REPO_NAME}
mkdir -p ${DESTINATION_REPO_FOLDER}
echo "Destination was provided [${DESTINATION}]"
fi
cd ${DESTINATION_REPO_FOLDER}
git checkout gh-pages
git pull origin gh-pages
# Add git branches
###################################################################
if [[ -z "${VERSION}" ]] ; then
copy_docs_for_current_version
else
copy_docs_for_provided_version
fi
commit_changes_if_applicable
}
# Copies the docs by using the retrieved properties from Maven build
function copy_docs_for_current_version() {
if [[ "${CURRENT_BRANCH}" == "master" ]] ; then
echo -e "Current branch is master - will copy the current docs only to the root folder"
for f in docs/target/generated-docs/*; do
file=${f#docs/target/generated-docs/*}
if ! git ls-files -i -o --exclude-standard --directory | grep -q ^$file$; then
# Not ignored...
cp -rf $f ${ROOT_FOLDER}/
git add -A ${ROOT_FOLDER}/$file
fi
done
COMMIT_CHANGES="yes"
else
echo -e "Current branch is [${CURRENT_BRANCH}]"
# https://stackoverflow.com/questions/29300806/a-bash-script-to-check-if-a-string-is-present-in-a-comma-separated-list-of-strin
if [[ ",${WHITELISTED_BRANCHES_VALUE}," = *",${CURRENT_BRANCH},"* ]] ; then
mkdir -p ${ROOT_FOLDER}/${CURRENT_BRANCH}
echo -e "Branch [${CURRENT_BRANCH}] is whitelisted! Will copy the current docs to the [${CURRENT_BRANCH}] folder"
for f in docs/target/generated-docs/*; do
file=${f#docs/target/generated-docs/*}
if ! git ls-files -i -o --exclude-standard --directory | grep -q ^$file$; then
# Not ignored...
# We want users to access 1.0.0.RELEASE/ instead of 1.0.0.RELEASE/spring-cloud.sleuth.html
if [[ "${file}" == "${MAIN_ADOC_VALUE}.html" ]] ; then
# We don't want to copy the spring-cloud-sleuth.html
# we want it to be converted to index.html
cp -rf $f ${ROOT_FOLDER}/${CURRENT_BRANCH}/index.html
git add -A ${ROOT_FOLDER}/${CURRENT_BRANCH}/index.html
else
cp -rf $f ${ROOT_FOLDER}/${CURRENT_BRANCH}
git add -A ${ROOT_FOLDER}/${CURRENT_BRANCH}/$file
fi
fi
done
COMMIT_CHANGES="yes"
else
echo -e "Branch [${CURRENT_BRANCH}] is not on the white list! Check out the Maven [${WHITELIST_PROPERTY}] property in
[docs] module available under [docs] profile. Won't commit any changes to gh-pages for this branch."
fi
fi
}
# Copies the docs by using the explicitly provided version
function copy_docs_for_provided_version() {
local FOLDER=${DESTINATION_REPO_FOLDER}/${VERSION}
mkdir -p ${FOLDER}
echo -e "Current tag is [v${VERSION}] Will copy the current docs to the [${FOLDER}] folder"
for f in ${ROOT_FOLDER}/docs/target/generated-docs/*; do
file=${f#${ROOT_FOLDER}/docs/target/generated-docs/*}
copy_docs_for_branch ${file} ${FOLDER}
done
COMMIT_CHANGES="yes"
CURRENT_BRANCH="v${VERSION}"
}
# Copies the docs from target to the provided destination
# Params:
# $1 - file from target
# $2 - destination to which copy the files
function copy_docs_for_branch() {
local file=$1
local destination=$2
if ! git ls-files -i -o --exclude-standard --directory | grep -q ^${file}$; then
# Not ignored...
# We want users to access 1.0.0.RELEASE/ instead of 1.0.0.RELEASE/spring-cloud.sleuth.html
if [[ ("${file}" == "${MAIN_ADOC_VALUE}.html") || ("${file}" == "${REPO_NAME}.html") ]] ; then
# We don't want to copy the spring-cloud-sleuth.html
# we want it to be converted to index.html
cp -rf $f ${destination}/index.html
git add -A ${destination}/index.html
else
cp -rf $f ${destination}
git add -A ${destination}/$file
fi
fi
}
function commit_changes_if_applicable() {
if [[ "${COMMIT_CHANGES}" == "yes" ]] ; then
COMMIT_SUCCESSFUL="no"
git commit -a -m "Sync docs from ${CURRENT_BRANCH} to gh-pages" && COMMIT_SUCCESSFUL="yes" || echo "Failed to commit changes"
# Uncomment the following push if you want to auto push to
# the gh-pages branch whenever you commit to master locally.
# This is a little extreme. Use with care!
###################################################################
if [[ "${COMMIT_SUCCESSFUL}" == "yes" ]] ; then
git push origin gh-pages
fi
fi
}
# Switch back to the previous branch and exit block
function checkout_previous_branch() {
# If -version was provided we need to come back to root project
cd ${ROOT_FOLDER}
git checkout ${CURRENT_BRANCH} || echo "Failed to check the branch... continuing with the script"
if [ "$dirty" != "0" ]; then git stash pop; fi
exit 0
}
# Assert if properties have been properly passed
function assert_properties() {
echo "VERSION [${VERSION}], DESTINATION [${DESTINATION}], CLONE [${CLONE}]"
if [[ "${VERSION}" != "" && (-z "${DESTINATION}" && -z "${CLONE}") ]] ; then echo "Version was set but destination / clone was not!"; exit 1;fi
if [[ ("${DESTINATION}" != "" && "${CLONE}" != "") && -z "${VERSION}" ]] ; then echo "Destination / clone was set but version was not!"; exit 1;fi
if [[ "${DESTINATION}" != "" && "${CLONE}" == "yes" ]] ; then echo "Destination and clone was set. Pick one!"; exit 1;fi
}
# Prints the usage
function print_usage() {
cat <<EOF
The idea of this script is to update gh-pages branch with the generated docs. Without any options
the script will work in the following manner:
- if there's no gh-pages / target for docs module then the script ends
- for master branch the generated docs are copied to the root of gh-pages branch
- for any other branch (if that branch is whitelisted) a subfolder with branch name is created
and docs are copied there
- if the version switch is passed (-v) then a tag with (v) prefix will be retrieved and a folder
with that version number will be created in the gh-pages branch. WARNING! No whitelist verification will take place
- if the destination switch is passed (-d) then the script will check if the provided dir is a git repo and then will
switch to gh-pages of that repo and copy the generated docs to `docs/<project-name>/<version>`
- if the destination switch is passed (-d) then the script will check if the provided dir is a git repo and then will
switch to gh-pages of that repo and copy the generated docs to `docs/<project-name>/<version>`
USAGE:
You can use the following options:
-v|--version - the script will apply the whole procedure for a particular library version
-d|--destination - the root of destination folder where the docs should be copied. You have to use the full path.
E.g. point to spring-cloud-static folder. Can't be used with (-c)
-b|--build - will run the standard build process after checking out the branch
-c|--clone - will automatically clone the spring-cloud-static repo instead of providing the destination.
Obviously can't be used with (-d)
EOF
}
# ==========================================
# ____ ____ _____ _____ _____ _______
# / ____|/ ____| __ \|_ _| __ \__ __|
# | (___ | | | |__) | | | | |__) | | |
# \___ \| | | _ / | | | ___/ | |
# ____) | |____| | \ \ _| |_| | | |
# |_____/ \_____|_| \_\_____|_| |_|
#
# ==========================================
while [[ $# > 0 ]]
do
key="$1"
case ${key} in
-v|--version)
VERSION="$2"
shift # past argument
;;
-d|--destination)
DESTINATION="$2"
shift # past argument
;;
-b|--build)
BUILD="yes"
;;
-c|--clone)
CLONE="yes"
;;
-h|--help)
print_usage
exit 0
;;
*)
echo "Invalid option: [$1]"
print_usage
exit 1
;;
esac
shift # past argument or value
done
assert_properties
set_default_props
check_if_anything_to_sync
if [[ -z "${VERSION}" ]] ; then
retrieve_current_branch
else
switch_to_tag
fi
build_docs_if_applicable
retrieve_doc_properties
stash_changes
add_docs_from_target
checkout_previous_branch

Binary file not shown.

Before

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

57
mvnw vendored
View File

@@ -8,7 +8,7 @@
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
# 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
@@ -19,7 +19,7 @@
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
@@ -114,7 +114,6 @@ if $mingw ; then
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
@@ -212,7 +211,11 @@ else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
@@ -221,22 +224,38 @@ else
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
wget "$jarUrl" -O "$wrapperJarPath"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
curl -o "$wrapperJarPath" "$jarUrl"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
@@ -277,29 +296,13 @@ if $cygwin; then
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
echo "Running version check"
VERSION=$( sed '\!<parent!,\!</parent!d' `dirname $0`/pom.xml | grep '<version' | head -1 | sed -e 's/.*<version>//' -e 's!</version>.*$!!' )
echo "The found version is [${VERSION}]"
if echo $VERSION | egrep -q 'M|RC'; then
echo Activating \"milestone\" profile for version=\"$VERSION\"
echo $MAVEN_CONFIG | grep -q milestone || MAVEN_CONFIG="$MAVEN_CONFIG -Pmilestone"
else
echo Deactivating \"milestone\" profile for version=\"$VERSION\"
echo $MAVEN_CONFIG | grep -q milestone && MAVEN_CONFIG=$(echo $MAVEN_CONFIG | sed -e 's/-Pmilestone//')
fi
if echo $VERSION | egrep -q 'RELEASE'; then
echo Activating \"central\" profile for version=\"$VERSION\"
echo $MAVEN_CONFIG | grep -q milestone || MAVEN_CONFIG="$MAVEN_CONFIG -Pcentral"
else
echo Deactivating \"central\" profile for version=\"$VERSION\"
echo $MAVEN_CONFIG | grep -q central && MAVEN_CONFIG=$(echo $MAVEN_CONFIG | sed -e 's/-Pcentral//')
fi
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \

45
mvnw.cmd vendored
View File

@@ -7,7 +7,7 @@
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@@ -18,7 +18,7 @@
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@@ -26,7 +26,7 @@
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@@ -37,7 +37,7 @@
@echo off
@REM set title of command window
title %0
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
@@ -120,23 +120,44 @@ SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
echo Found %WRAPPER_JAR%
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
echo Finished downloading %WRAPPER_JAR%
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end

311
pom.xml
View File

@@ -1,287 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway</artifactId>
<version>4.1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<artifactId>spring-cloud-gateway-docs-build</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Spring Cloud Gateway</name>
<description>Spring Cloud Gateway</description>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-build</artifactId>
<version>4.1.0-SNAPSHOT</version>
<relativePath/>
</parent>
<name>Spring Cloud Gateway Docs Build</name>
<description>Builds Spring Cloud Gateway Docs.</description>
<url>https://spring.io/projects/spring-cloud-gateway</url>
<scm>
<url>https://github.com/spring-cloud/spring-cloud-gateway</url>
<connection>
scm:git:git://github.com/spring-cloud/spring-cloud-gateway.git
<connection>scm:git:https://github.com/spring-cloud/spring-cloud-gateway.git
</connection>
<developerConnection>
scm:git:ssh://git@github.com/spring-cloud/spring-cloud-gateway.git
scm:git:git@github.com:spring-cloud/spring-cloud-gateway.git
</developerConnection>
<tag>HEAD</tag>
<url>https://github.com/spring-cloud/spring-cloud-gateway</url>
</scm>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<url>https://www.apache.org/licenses/LICENSE-2.0</url>
</license>
</licenses>
<developers>
<developer>
<id>sgibb</id>
<name>Spencer Gibb</name>
<email>sgibb at pivotal.io</email>
<organization>Pivotal Software, Inc.</organization>
<organizationUrl>https://www.spring.io</organizationUrl>
<roles>
<role>Project lead</role>
</roles>
</developer>
</developers>
<issueManagement>
<url>https://github.com/spring-cloud/spring-cloud-gateway/issues</url>
</issueManagement>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<bucket4j.version>8.3.0</bucket4j.version>
<blockhound.version>1.0.6.RELEASE</blockhound.version>
<java.version>17</java.version>
<junit-pioneer.version>1.6.1</junit-pioneer.version>
<spring-cloud-circuitbreaker.version>3.1.0-SNAPSHOT</spring-cloud-circuitbreaker.version>
<spring-cloud-commons.version>4.1.0-SNAPSHOT</spring-cloud-commons.version>
<testcontainers.version>1.17.3</testcontainers.version>
<io.spring.maven.antora-version>0.0.3</io.spring.maven.antora-version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-dependencies</artifactId>
<version>${project.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons-dependencies</artifactId>
<version>${spring-cloud-commons.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-test-support</artifactId>
<version>${spring-cloud-commons.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-circuitbreaker-dependencies</artifactId>
<version>${spring-cloud-circuitbreaker.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4j</artifactId>
<version>${spring-cloud-circuitbreaker.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>com.bucket4j</groupId>
<artifactId>bucket4j-core</artifactId>
<version>${bucket4j.version}</version>
</dependency>
<dependency>
<groupId>com.bucket4j</groupId>
<artifactId>bucket4j-caffeine</artifactId>
<version>${bucket4j.version}</version>
</dependency>
<dependency>
<groupId>io.projectreactor.tools</groupId>
<artifactId>blockhound</artifactId>
<version>${blockhound.version}</version>
</dependency>
<dependency>
<groupId>io.projectreactor.tools</groupId>
<artifactId>blockhound-junit-platform</artifactId>
<version>${blockhound.version}</version>
</dependency>
<dependency>
<groupId>org.junit-pioneer</groupId>
<artifactId>junit-pioneer</artifactId>
<version>${junit-pioneer.version}</version>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-bom</artifactId>
<version>${testcontainers.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<modules>
<module>spring-cloud-gateway-dependencies</module>
<module>spring-cloud-gateway-mvc</module>
<module>spring-cloud-gateway-webflux</module>
<module>spring-cloud-gateway-server</module>
<module>spring-cloud-gateway-server-mvc</module>
<module>spring-cloud-starter-gateway</module>
<module>spring-cloud-starter-gateway-mvc</module>
<module>spring-cloud-gateway-sample</module>
<module>spring-cloud-gateway-integration-tests</module>
<module>docs</module>
</modules>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<groupId>io.spring.maven.antora</groupId>
<artifactId>antora-maven-plugin</artifactId>
<version>${io.spring.maven.antora-version}</version>
<extensions>true</extensions>
<configuration>
<options>
<option>--to-dir=target/antora/site</option>
<option>--stacktrace</option>
<option>--fetch</option>
</options>
<environment>
<ALGOLIA_API_KEY>9d489079e5ec46dbb238909fee5c9c29</ALGOLIA_API_KEY>
<ALGOLIA_APP_ID>WB1FQYI187</ALGOLIA_APP_ID>
<ALGOLIA_INDEX_NAME>springcloudgateway</ALGOLIA_INDEX_NAME>
</environment>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>spring</id>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/release</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/release</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
<profile>
<id>sonar</id>
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<executions>
<execution>
<id>pre-unit-test</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<propertyName>surefireArgLine</propertyName>
<destFile>${project.build.directory}/jacoco.exec
</destFile>
</configuration>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<!-- Sets the path to the file which contains the execution data. -->
<dataFile>${project.build.directory}/jacoco.exec
</dataFile>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<!-- Sets the VM argument line used when unit tests are run. -->
<argLine>${surefireArgLine}</argLine>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>withoutDockerTests</id>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludedGroups>DockerRequired</excludedGroups>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<repositories>
<repository>
<id>spring-snapshot</id>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
</project>

View File

@@ -1,114 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>spring-cloud-dependencies-parent</artifactId>
<groupId>org.springframework.cloud</groupId>
<version>4.1.0-SNAPSHOT</version>
<relativePath/>
</parent>
<artifactId>spring-cloud-gateway-dependencies</artifactId>
<version>4.1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>spring-cloud-gateway-dependencies</name>
<description>Spring Cloud Gateway Dependencies</description>
<properties>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-webflux</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-mvc</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-server</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-server-mvc</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway-mvc</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<profiles>
<profile>
<id>spring</id>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/release</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
</project>

View File

@@ -1,131 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>grpc</artifactId>
<packaging>jar</packaging>
<name>Spring Cloud Gateway gRPC Integration Test</name>
<description>Spring Cloud Gateway gRPC Integration Test</description>
<properties>
<grpc.version>1.47.0</grpc.version>
</properties>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-integration-tests</artifactId>
<version>4.1.0-SNAPSHOT</version>
<relativePath>..</relativePath> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-protobuf</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-tcnative-boringssl-static</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>annotations-api</artifactId>
<version>6.0.53</version>
<scope>provided</scope> <!-- not needed at runtime -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-test-support</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.6.2</version>
</extension>
</extensions>
<plugins>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.19.4:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.44.0:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -1,128 +0,0 @@
/*
* Copyright 2013-2021 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.tests.grpc;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import io.grpc.Grpc;
import io.grpc.Server;
import io.grpc.ServerCredentials;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.TlsServerCredentials;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
/**
* @author Alberto C. Ríos
*/
@SpringBootConfiguration
@EnableAutoConfiguration
public class GRPCApplication {
public static void main(String[] args) {
SpringApplication.run(GRPCApplication.class, args);
}
@Component
static class GRPCServer implements ApplicationRunner {
private static final Logger log = LoggerFactory.getLogger(GRPCServer.class);
private final Environment environment;
private Server server;
GRPCServer(Environment environment) {
this.environment = environment;
}
@Override
public void run(ApplicationArguments args) throws Exception {
final GRPCServer server = new GRPCServer(environment);
server.start();
}
private void start() throws IOException {
Integer serverPort = environment.getProperty("local.server.port", Integer.class);
int grpcPort = serverPort + 1;
ServerCredentials creds = createServerCredentials();
server = Grpc.newServerBuilderForPort(grpcPort, creds).addService(new HelloService()).build().start();
log.info("Starting gRPC server in port " + grpcPort);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
GRPCServer.this.stop();
}
catch (InterruptedException e) {
e.printStackTrace(System.err);
}
}));
}
private ServerCredentials createServerCredentials() throws IOException {
File certChain = new ClassPathResource("public.cert").getFile();
File privateKey = new ClassPathResource("private.key").getFile();
return TlsServerCredentials.create(certChain, privateKey);
}
private void stop() throws InterruptedException {
if (server != null) {
server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
}
}
static class HelloService extends HelloServiceGrpc.HelloServiceImplBase {
@Override
public void hello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
if ("failWithRuntimeException!".equals(request.getFirstName())) {
StatusRuntimeException exception = Status.FAILED_PRECONDITION.withDescription("Invalid firstName")
.asRuntimeException();
responseObserver.onError(exception);
responseObserver.onCompleted();
return;
}
String greeting = String.format("Hello, %s %s", request.getFirstName(), request.getLastName());
log.info("Sending response: " + greeting);
HelloResponse response = HelloResponse.newBuilder().setGreeting(greeting).build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
}
}

View File

@@ -1,17 +0,0 @@
syntax = "proto3";
option java_multiple_files = true;
option java_package = "org.springframework.cloud.gateway.tests.grpc";
package org.springframework.cloud.gateway.tests.grpc;
message HelloRequest {
optional string firstName = 1;
optional string lastName = 2;
}
message HelloResponse {
optional string greeting = 1;
}
service HelloService {
rpc hello(HelloRequest) returns (HelloResponse);
}

View File

@@ -1,32 +0,0 @@
Bag Attributes
friendlyName: bootapp
localKeyID: 54 69 6D 65 20 31 36 35 39 39 37 34 34 38 34 30 33 30
Key Attributes: <No Attributes>
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQClCZtSgRjM2uYM
O70+acD4rhwcc8ND23SwoKTNLPH6s1K2Pi5MZqF4Rnx+REJwerQrkgfMnsQ0QHcb
NjI9dhSwHw6aPigAGJQEzR8whDu2PkR57iBmySr3GLtpR+WkVGo/xAK92ozKt9aW
Saxm0miygYI8mgzrNpbaQAu6sZcS3RHkPYWw/izYVZLBB6IEpAJJrUqjzlu53TyN
X4VC4FWddItjOCiyrHe2+A+tFLNK3IZnFZBqoMcYR6/Rq+zsXx8ynCggkUwTFaPd
IVyzSYtooE2oq+aSjkJzKvoPA7BObLnrW+5Dklwj1iPtLhfuCflz2oa54/Hpl60R
Ke6y6/t5AgMBAAECggEAQvJ/sFswDUGq2kGNhfjuT7KJMr1+81Ldphy0XYqi6li9
77GPpGxpidnF/I6CCRCtb5NAWK/61VtlNYOpo6b3w24FxWn7XfaabMwsn8i0VDw0
GOYQ/MEUDcJZm96PeDbKFu3TUuKKBF3IzZQ7PEaUM/03MJApN20gio46c9RAfWTK
hN9jX9YkBpkSWPfx9RA9BOIXRrRMTXhidsVPnNxhhM7OAGZ1LhggDPaeiCIbVx6l
yMsyCkNvqdQbKu0hFcVyeQsGjovCC1Ye71F3em3ACguqDu+VAy3flpTbcDVf2D7T
zP2T5e5OEJ2hRTGdnEVSsXxWOWnq6Gt6ydNEe2AWVQKBgQC5HcQAUTnvIMaTez44
7SBfELNY1AzF24dha24JFIGY78QNRZi+4Agsvxjkx4fKSd4DfmPsCqentmEkEcDr
w6fH0CAFm/rrkzLHmesBCC8byl4WtfMW5i8h1yzOeQbYpx3MGIu5xhkE92gbNj+o
ioM7nkoBvloU0odiYTVnoNYnFwKBgQDkO5ldA8Vl3+BWhmhOtPu+1EKssWry5rdO
m6IiZ1uB6uG4bhAj5dSVVgDRX6pcuppMVZqIbPpdkS7/i0LVwohT7EmpMMJ5bezz
EhG1z6AvZDcGMDC/PPMp7SLjJviYZDaTWLekKwY6yV1T9gtOY70jjWkUcfN1IHpA
renHNNyL7wKBgQCEYvIqW+y3xFPfY1MzePoeop3wl+3ujjo6hI7z9XNdgZNO/ofn
cebGwX+3Fa9aDwu0qe4h/9i4y2ibWAsFUS6ran+MI2oGkYXOU5hKa6TtFgPF8CfC
J6prZCxKGSm5RYK81I0Qtchs0dblJx3NlgmWWHSK3Kwlmg5yYBzGWLLuzwKBgDzg
rNrDq76txcAun9oGqnPPWG2J8XYTFmgQWWIF4cG4rjasnP+GSXr/8r3mX6HWYFvm
JY8oSmv00u107wHnnseL6mYHzIfpS1/WvQSa+iZJ++dZqVcJYe8YAstGVN8JNAl/
i5RtqX66wXso0QE613OJP7MlZgQjApkICqiJMB7fAoGAVFdv/Nphcju7MCkXGuQe
amk7Z6Q2PjMWvLwiyB39PrIzvTOdaQyQk7oYdnAGFJbkmi7mmGiet5uvcE9OjNRb
+XeXo2LEZ2QWJEnHi9uCXSQF3eeBlJ2wGUsELPTHglWIUTpi5iDB2hHzczPzO8GY
qPb+ckCl8mTsHRKQQse4Bm0=
-----END PRIVATE KEY-----

View File

@@ -1,18 +0,0 @@
-----BEGIN CERTIFICATE-----
MIIC1zCCAb+gAwIBAgIIEsL9TgSEch8wDQYJKoZIhvcNAQELBQAwGjEYMBYGA1UE
AxMPbXktYm9vdC1hcHAub3JnMB4XDTIyMDgwODE2MDEyNFoXDTMyMDgwNTE2MDEy
NFowGjEYMBYGA1UEAxMPbXktYm9vdC1hcHAub3JnMIIBIjANBgkqhkiG9w0BAQEF
AAOCAQ8AMIIBCgKCAQEApQmbUoEYzNrmDDu9PmnA+K4cHHPDQ9t0sKCkzSzx+rNS
tj4uTGaheEZ8fkRCcHq0K5IHzJ7ENEB3GzYyPXYUsB8Omj4oABiUBM0fMIQ7tj5E
ee4gZskq9xi7aUflpFRqP8QCvdqMyrfWlkmsZtJosoGCPJoM6zaW2kALurGXEt0R
5D2FsP4s2FWSwQeiBKQCSa1Ko85bud08jV+FQuBVnXSLYzgosqx3tvgPrRSzStyG
ZxWQaqDHGEev0avs7F8fMpwoIJFMExWj3SFcs0mLaKBNqKvmko5Ccyr6DwOwTmy5
61vuQ5JcI9Yj7S4X7gn5c9qGuePx6ZetESnusuv7eQIDAQABoyEwHzAdBgNVHQ4E
FgQUf72EgsQASMCzSGwrFDaKnBoufm8wDQYJKoZIhvcNAQELBQADggEBAAHzJkp/
q+U0ki+JaFaUBYg85h+yJbi262hmFjLYDQEcz2tvAw93X9ytOzVtmo2H9AgsTJYA
z4UbJHfnTTa1KAHDHhzL/Adh/s2OZ7Y2kazLrHArFteKtGUo815JDL935JpiRBWc
Qn1WJJ6EFb+ZRMG7oROQ3LgvrradH8G51qxvSbH/fpmEFDTSHJNIG8tXcIA3fJkI
dsVJLygrXLzZQo5xI8rwMDX9aujRFU4Dgit58xquCkuzob/BonN7Es1Hp3beQjro
gddts4x5wWyiFun7uYrbPVhGMJNgwRKB5e3QQA6vYDyeQqvIy6n1lnDNIxvaOfPW
Je5gI59jCbxHs5g=
-----END CERTIFICATE-----

View File

@@ -1,103 +0,0 @@
/*
* Copyright 2013-2021 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.tests.grpc;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import io.grpc.ManagedChannel;
import io.grpc.StatusRuntimeException;
import io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.NettyChannelBuilder;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import static io.grpc.Status.FAILED_PRECONDITION;
import static io.grpc.netty.NegotiationType.TLS;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
/**
* @author Alberto C. Ríos
*/
@SpringBootTest(classes = org.springframework.cloud.gateway.tests.grpc.GRPCApplication.class,
webEnvironment = WebEnvironment.RANDOM_PORT)
public class GRPCApplicationTests {
@LocalServerPort
private int gatewayPort;
@BeforeEach
void setUp() {
int grpcServerPort = gatewayPort + 1;
final RouteConfigurer configurer = new RouteConfigurer(gatewayPort);
configurer.addRoute(grpcServerPort, "/**", null);
}
@Test
public void gRPCUnaryCallShouldReturnResponse() throws SSLException {
ManagedChannel channel = createSecuredChannel(gatewayPort);
final HelloResponse response = HelloServiceGrpc.newBlockingStub(channel)
.hello(HelloRequest.newBuilder().setFirstName("Sir").setLastName("FromClient").build());
Assertions.assertThat(response.getGreeting()).isEqualTo("Hello, Sir FromClient");
}
private ManagedChannel createSecuredChannel(int port) throws SSLException {
TrustManager[] trustAllCerts = createTrustAllTrustManager();
return NettyChannelBuilder.forAddress("localhost", port).useTransportSecurity()
.sslContext(GrpcSslContexts.forClient().trustManager(trustAllCerts[0]).build()).negotiationType(TLS)
.build();
}
@Test
public void gRPCUnaryCallShouldHandleRuntimeException() throws SSLException {
ManagedChannel channel = createSecuredChannel(gatewayPort);
try {
HelloServiceGrpc.newBlockingStub(channel)
.hello(HelloRequest.newBuilder().setFirstName("failWithRuntimeException!").build());
}
catch (StatusRuntimeException e) {
Assertions.assertThat(FAILED_PRECONDITION.getCode()).isEqualTo(e.getStatus().getCode());
Assertions.assertThat("Invalid firstName").isEqualTo(e.getStatus().getDescription());
}
}
private TrustManager[] createTrustAllTrustManager() {
return new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
}
}

View File

@@ -1,107 +0,0 @@
/*
* Copyright 2013-2021 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.tests.grpc;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.BasicHttpClientConnectionManager;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.config.Registry;
import org.apache.hc.core5.http.config.RegistryBuilder;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
/**
* @author Alberto C. Ríos
* @author Abel Salgado Romero
*/
@Disabled
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class JsonToGrpcApplicationTests {
@LocalServerPort
private int gatewayPort;
private RestTemplate restTemplate;
@BeforeEach
void setUp() {
restTemplate = createUnsecureClient();
}
@Test
public void shouldConvertFromJSONToGRPC() {
// Since GRPC server and GW run in same instance and don't know server port until
// test starts,
// we need to configure route dynamically using the actuator endpoint.
final RouteConfigurer configurer = new RouteConfigurer(gatewayPort);
int grpcServerPort = gatewayPort + 1;
configurer.addRoute(grpcServerPort, "/json/hello",
"JsonToGrpc=file:src/main/proto/hello.pb,file:src/main/proto/hello.proto,HelloService,hello");
String response = restTemplate.postForEntity("https://localhost:" + this.gatewayPort + "/json/hello",
"{\"firstName\":\"Duff\", \"lastName\":\"McKagan\"}", String.class).getBody();
Assertions.assertThat(response).isNotNull();
Assertions.assertThat(response).contains("{\"greeting\":\"Hello, Duff McKagan\"}");
}
private RestTemplate createUnsecureClient() {
TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
SSLContext sslContext;
try {
sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
}
catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
throw new RuntimeException(e);
}
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslSocketFactory).register("http", new PlainConnectionSocketFactory()).build();
HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
return new RestTemplate(requestFactory);
}
}

View File

@@ -1,114 +0,0 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.tests.grpc;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.net.ssl.SSLContext;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.BasicHttpClientConnectionManager;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.config.Registry;
import org.apache.hc.core5.http.config.RegistryBuilder;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
public class RouteConfigurer {
private final int actuatorPort;
private final RestTemplate restTemplate;
RouteConfigurer(int actuatorPort) {
this.actuatorPort = actuatorPort;
this.restTemplate = createUnsecureClient();
}
public void addRoute(int grpcServerPort, String path, String filter) {
final String routeId = "test-route-" + UUID.randomUUID();
Map<String, Object> route = new HashMap<>();
route.put("id", routeId);
route.put("uri", "https://localhost:" + grpcServerPort);
route.put("predicates", Collections.singletonList("Path=" + path));
if (filter != null) {
route.put("filters", Arrays.asList(filter));
}
ResponseEntity<String> exchange = restTemplate.exchange(url("/actuator/gateway/routes/" + routeId),
HttpMethod.POST, new HttpEntity<>(route), String.class);
assert exchange.getStatusCode() == HttpStatus.CREATED;
refreshRoutes();
}
private void refreshRoutes() {
ResponseEntity<String> exchange = restTemplate.exchange(url("/actuator/gateway/refresh"), HttpMethod.POST,
new HttpEntity<>(""), String.class);
assert exchange.getStatusCode() == HttpStatus.OK;
}
private String url(String context) {
return String.format("https://localhost:%s%s", this.actuatorPort, context);
}
private RestTemplate createUnsecureClient() {
TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
SSLContext sslContext;
try {
sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
}
catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
throw new RuntimeException(e);
}
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslSocketFactory).register("http", new PlainConnectionSocketFactory()).build();
HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
return new RestTemplate(requestFactory);
}
}

View File

@@ -1,37 +0,0 @@
server:
http2:
enabled: true
ssl:
key-store: classpath:keystore.p12
key-store-type: pkcs12
key-store-password: password
key-alias: bootapp
management:
endpoint:
health:
show-details: when_authorized
gateway:
enabled: true
endpoints:
web:
exposure:
include: "*"
spring:
cloud:
gateway:
httpserver:
wiretap: true
httpclient:
wiretap: true
ssl:
use-insecure-trust-manager: true
# Requires faking domain name (modifying /etc/hosts)
# trustedX509Certificates:
# - classpath:public.cert
logging:
level:
reactor.netty: DEBUG
org.springframework.cloud.gateway.filter: DEBUG

View File

@@ -1,71 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>http2</artifactId>
<packaging>jar</packaging>
<name>Spring Cloud Gateway HTTP2 Integration Test</name>
<description>Spring Cloud Gateway HTTP2 Integration Test</description>
<properties>
</properties>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-integration-tests</artifactId>
<version>4.1.0-SNAPSHOT</version>
<relativePath>..</relativePath> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-tcnative-boringssl-static</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-test-support</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -1,91 +0,0 @@
/*
* Copyright 2013-2021 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.tests.http2;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClients;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.ServiceInstanceListSuppliers;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Spencer Gibb
*/
// curl -i --insecure https://localhost:8443/hello
@SpringBootConfiguration
@EnableAutoConfiguration
@RestController
@LoadBalancerClients({ @LoadBalancerClient(name = "myservice", configuration = Http2Application.MyServiceConf.class),
@LoadBalancerClient(name = "nossl", configuration = Http2Application.NosslServiceConf.class) })
public class Http2Application {
private static Log log = LogFactory.getLog(Http2Application.class);
@GetMapping("hello")
public String hello() {
return "Hello";
}
@Bean
public RouteLocator myRouteLocator(RouteLocatorBuilder builder) {
return builder.routes().route(r -> r.path("/myprefix/**").filters(f -> f.stripPrefix(1)).uri("lb://myservice"))
.route(r -> r.path("/nossl/**").filters(f -> f.stripPrefix(1)).uri("lb://nossl"))
.route(r -> r.path("/neverssl/**").filters(f -> f.stripPrefix(1)).uri("http://neverssl.com"))
.route(r -> r.path("/httpbin/**").uri("https://nghttp2.org")).build();
}
public static void main(String[] args) {
SpringApplication.run(Http2Application.class, args);
}
static class MyServiceConf {
@Bean
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
Integer port = env.getProperty("local.server.port", Integer.class, 8443);
log.info("local.server.port = " + port);
return ServiceInstanceListSuppliers.from("myservice",
new DefaultServiceInstance("myservice-1", "myservice", "localhost", port, true));
}
}
static class NosslServiceConf {
@Bean
public ServiceInstanceListSupplier noSslStaticServiceInstanceListSupplier() {
int port = Integer.parseInt(System.getProperty("nossl.port", "8080"));
log.info("nossl.port = " + port);
return ServiceInstanceListSuppliers.from("nossl",
new DefaultServiceInstance("nossl-1", "nossl", "localhost", port, false));
}
}
}

View File

@@ -1,22 +0,0 @@
logging:
level:
org.springframework.cloud.gateway: TRACE
reactor.netty.http.client: DEBUG
server:
ssl:
key-store: classpath:sample.jks
key-store-password: secret
key-password: password
http2:
enabled: true
spring:
cloud:
gateway:
# httpserver:
# wiretap: true
httpclient:
wiretap: true
ssl:
use-insecure-trust-manager: true

View File

@@ -1,86 +0,0 @@
/*
* Copyright 2013-2021 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.tests.http2;
import java.time.Duration;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import reactor.core.publisher.Hooks;
import reactor.core.publisher.Mono;
import reactor.netty.http.Http2SslContextSpec;
import reactor.netty.http.HttpProtocol;
import reactor.netty.http.client.HttpClient;
import reactor.netty.resources.ConnectionProvider;
import reactor.test.StepVerifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.web.reactive.function.client.WebClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
/**
* @author Spencer Gibb
*/
@ExtendWith(OutputCaptureExtension.class)
@SpringBootTest(classes = Http2Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@DirtiesContext
public class Http2ApplicationTests {
@LocalServerPort
int port;
@Test
public void http2Works(CapturedOutput output) {
Hooks.onOperatorDebug();
String uri = "https://localhost:" + port + "/myprefix/hello";
String expected = "Hello";
assertResponse(uri, expected);
Assertions.assertThat(output).contains("Negotiated application-level protocol [h2]", "PRI * HTTP/2.0");
}
public static void assertResponse(String uri, String expected) {
WebClient client = WebClient.builder().clientConnector(new ReactorClientHttpConnector(getHttpClient())).build();
Mono<ResponseEntity<String>> responseEntityMono = client.get().uri(uri).retrieve().toEntity(String.class);
StepVerifier.create(responseEntityMono).assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).isEqualTo(expected);
}).expectComplete().verify();
}
static HttpClient getHttpClient() {
return HttpClient
.create(ConnectionProvider.builder("test").maxConnections(100)
.pendingAcquireTimeout(Duration.ofMillis(0)).pendingAcquireMaxCount(-1).build())
.protocol(HttpProtocol.HTTP11, HttpProtocol.H2).secure(sslContextSpec -> {
Http2SslContextSpec clientSslCtxt = Http2SslContextSpec.forClient()
.configure(builder -> builder.trustManager(InsecureTrustManagerFactory.INSTANCE));
sslContextSpec.sslContext(clientSslCtxt);
});
}
}

View File

@@ -1,34 +0,0 @@
/*
* Copyright 2013-2021 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.tests.http2.nossl;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Configuration
@EnableAutoConfiguration
public class NosslConfiguration {
@GetMapping("/")
public String home() {
return "nossl";
}
}

View File

@@ -1,75 +0,0 @@
/*
* Copyright 2013-2021 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.tests.http2.nossl;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import reactor.core.publisher.Hooks;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.cloud.gateway.tests.http2.Http2Application;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.util.TestSocketUtils;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import static org.springframework.cloud.gateway.tests.http2.Http2ApplicationTests.assertResponse;
/**
* @author Spencer Gibb
*/
@ExtendWith(OutputCaptureExtension.class)
@SpringBootTest(classes = Http2Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@DirtiesContext
public class NosslTests {
@LocalServerPort
int port;
@BeforeAll
static void beforeAll() {
int noSslPort = TestSocketUtils.findAvailableTcpPort();
System.setProperty("nossl.port", String.valueOf(noSslPort));
}
@AfterAll
static void afterAll() {
System.clearProperty("nossl.port");
}
@Test
public void http2TerminationWorks(CapturedOutput output) {
int nosslPort = Integer.parseInt(System.getProperty("nossl.port"));
System.err.println("nossl.port = " + nosslPort);
Hooks.onOperatorDebug();
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(NosslConfiguration.class)
.properties("server.port=" + nosslPort).profiles("nossl").run()) {
String uri = "https://localhost:" + port + "/nossl";
String expected = "nossl";
assertResponse(uri, expected);
Assertions.assertThat(output).doesNotContain("PRI * HTTP/2.0");
}
}
}

View File

@@ -1,13 +0,0 @@
server:
ssl:
enabled: false
key-store: ~
key-store-password: ~
key-password: ~
http2:
enabled: false
spring:
cloud:
gateway:
enabled: false

View File

@@ -1,63 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>mvc-failure-analyzer</artifactId>
<packaging>jar</packaging>
<name>Spring Cloud Gateway MVC Failure Analyzer Integration Test</name>
<description>Spring Cloud Gateway MVC Failure Analyzer Integration Test</description>
<properties>
</properties>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-integration-tests</artifactId>
<version>4.1.0-SNAPSHOT</version>
<relativePath>..</relativePath> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -1,67 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.sample;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.ServiceInstanceListSuppliers;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Spencer Gibb
*/
@SpringBootConfiguration
@EnableAutoConfiguration
@RestController
@LoadBalancerClient(name = "myservice", configuration = MyServiceConf.class)
public class MvcFailureAnalyzerApplication {
@GetMapping("hello")
public String hello() {
return "Hello";
}
@Bean
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public RouteLocator myRouteLocator(RouteLocatorBuilder builder) {
return builder.routes().route(r -> r.path("/myprefix/**").filters(f -> f.stripPrefix(1)).uri("lb://myservice"))
.build();
}
}
class MyServiceConf {
@Value("${local.server.port}")
private int port = 0;
@Bean
public ServiceInstanceListSupplier staticServiceInstanceListSupplier() {
return ServiceInstanceListSuppliers.from("myservice",
new DefaultServiceInstance("myservice-1", "myservice", "localhost", port, false));
}
}

View File

@@ -1,3 +0,0 @@
logging:
level:
org.springframework.cloud.gateway: TRACE

View File

@@ -1,72 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.sample;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.cloud.gateway.support.MvcFoundOnClasspathException;
import org.springframework.cloud.gateway.support.MvcFoundOnClasspathFailureAnalyzer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.web.reactive.server.WebTestClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* @author Spencer Gibb
*/
@ExtendWith(OutputCaptureExtension.class)
public class MvcFailureAnalyzerApplicationTests {
@Test
public void exceptionThrown(CapturedOutput output) {
assertThatThrownBy(() -> new SpringApplication(MvcFailureAnalyzerApplication.class).run("--server.port=0"))
.hasRootCauseInstanceOf(MvcFoundOnClasspathException.class);
assertThat(output).contains(MvcFoundOnClasspathFailureAnalyzer.MESSAGE,
MvcFoundOnClasspathFailureAnalyzer.ACTION);
}
@Test
public void exceptionNotThrownWhenDisabled(CapturedOutput output) {
assertThatCode(() -> new SpringApplication(MvcFailureAnalyzerApplication.class)
.run("--spring.cloud.gateway.enabled=false", "--server.port=0")).doesNotThrowAnyException();
assertThat(output).doesNotContain(MvcFoundOnClasspathFailureAnalyzer.MESSAGE,
MvcFoundOnClasspathFailureAnalyzer.ACTION);
}
@Test
public void exceptionNotThrownWhenReactiveTypeSet(CapturedOutput output) {
assertThatCode(() -> {
ConfigurableApplicationContext context = new SpringApplication(MvcFailureAnalyzerApplication.class)
.run("--spring.main.web-application-type=reactive", "--server.port=0", "--debug=true");
Integer port = context.getEnvironment().getProperty("local.server.port", Integer.class);
WebTestClient client = WebTestClient.bindToServer().baseUrl("http://localhost:" + port).build();
client.get().uri("/myprefix/hello").exchange().expectStatus().isOk().expectBody(String.class)
.isEqualTo("Hello");
context.close();
}).doesNotThrowAnyException();
assertThat(output).doesNotContain(MvcFoundOnClasspathFailureAnalyzer.MESSAGE,
MvcFoundOnClasspathFailureAnalyzer.ACTION);
}
}

View File

@@ -1,40 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-gateway-integration-tests</artifactId>
<packaging>pom</packaging>
<name>Spring Cloud Gateway Integration Tests</name>
<description>Spring Cloud Gateway Integration Tests</description>
<properties>
</properties>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway</artifactId>
<version>4.1.0-SNAPSHOT</version>
<relativePath>..</relativePath> <!-- lookup parent from repository -->
</parent>
<modules>
<module>grpc</module>
<module>http2</module>
<module>mvc-failure-analyzer</module>
</modules>
<build>
<plugins>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -1,55 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-gateway-mvc</artifactId>
<name>spring-cloud-gateway-mvc</name>
<description>Spring Cloud Gateway MVC</description>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway</artifactId>
<version>4.1.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>

View File

@@ -1,612 +0,0 @@
/*
* Copyright 2016-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.mvc;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import java.util.function.Function;
import java.util.stream.Collectors;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.WriteListener;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;
import org.springframework.core.Conventions;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.RequestEntity;
import org.springframework.http.RequestEntity.BodyBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;
/**
* A <code>@RequestMapping</code> argument type that can proxy the request to a backend.
* Spring will inject one of these into your MVC handler method, and you get return a
* <code>ResponseEntity</code> that you get from one of the HTTP methods {@link #get()},
* {@link #post()}, {@link #put()}, {@link #patch()}, {@link #delete()} etc. Example:
*
* <pre>
* &#64;GetMapping("/proxy/{id}")
* public ResponseEntity&lt;?&gt; proxy(@PathVariable Integer id, ProxyExchange&lt;?&gt; proxy)
* throws Exception {
* return proxy.uri("http://localhost:9000/foos/" + id).get();
* }
* </pre>
*
* <p>
* By default the incoming request body and headers are sent intact to the downstream
* service (with the exception of "sensitive" headers). To manipulate the downstream
* request there are "builder" style methods in {@link ProxyExchange}, but only the
* {@link #uri(String)} is mandatory. You can change the sensitive headers by calling the
* {@link #sensitive(String...)} method (Authorization and Cookie are sensitive by
* default).
* </p>
* <p>
* The type parameter <code>T</code> in <code>ProxyExchange&lt;T&gt;</code> is the type of
* the response body, so it comes out in the {@link ResponseEntity} that you return from
* your <code>@RequestMapping</code>. If you don't care about the type of the request and
* response body (e.g. if it's just a passthru) then use a wildcard, or
* <code>byte[]</code> or <code>Object</code>. Use a concrete type if you want to
* transform or manipulate the response, or if you want to assert that it is convertible
* to the type you declare.
* </p>
* <p>
* To manipulate the response use the overloaded HTTP methods with a <code>Function</code>
* argument and pass in code to transform the response. E.g.
*
* <pre>
* &#64;PostMapping("/proxy")
* public ResponseEntity&lt;Foo&gt; proxy(ProxyExchange&lt;Foo&gt; proxy) throws Exception {
* return proxy.uri("http://localhost:9000/foos/") //
* .post(response -> ResponseEntity.status(response.getStatusCode()) //
* .headers(response.getHeaders()) //
* .header("X-Custom", "MyCustomHeader") //
* .body(response.getBody()) //
* );
* }
*
* </pre>
*
* </p>
* <p>
* The full machinery of Spring {@link HttpMessageConverter message converters} is applied
* to the incoming request and response and also to the backend request. If you need
* additional converters then they need to be added upstream in the MVC configuration and
* also to the {@link RestTemplate} that is used in the backend calls (see the
* {@link ProxyExchange#ProxyExchange(RestTemplate, NativeWebRequest, ModelAndViewContainer, WebDataBinderFactory, Type)
* constructor} for details).
* </p>
* <p>
* As well as the HTTP methods for a backend call you can also use
* {@link #forward(String)} for a local in-container dispatch.
* <p>
* </p>
*
* @author Dave Syer
*
*/
public class ProxyExchange<T> {
/**
* Contains headers that are considered case-sensitive by default.
*/
public static Set<String> DEFAULT_SENSITIVE = Collections
.unmodifiableSet(new HashSet<>(Arrays.asList("cookie", "authorization")));
private URI uri;
private RestTemplate rest;
private Object body;
private RequestResponseBodyMethodProcessor delegate;
private NativeWebRequest webRequest;
private ModelAndViewContainer mavContainer;
private WebDataBinderFactory binderFactory;
private Set<String> sensitive;
private HttpHeaders headers = new HttpHeaders();
private Type responseType;
public ProxyExchange(RestTemplate rest, NativeWebRequest webRequest, ModelAndViewContainer mavContainer,
WebDataBinderFactory binderFactory, Type type) {
this.responseType = type;
this.rest = rest;
this.webRequest = webRequest;
this.mavContainer = mavContainer;
this.binderFactory = binderFactory;
this.delegate = new RequestResponseBodyMethodProcessor(rest.getMessageConverters());
}
/**
* Sets the body for the downstream request (if using {@link #post()}, {@link #put()}
* or {@link #patch()}). The body can be omitted if you just want to pass the incoming
* request downstream without changing it. If you want to transform the incoming
* request you can declare it as a <code>@RequestBody</code> in your
* <code>@RequestMapping</code> in the usual Spring MVC way.
* @param body the request body to send downstream
* @return this for convenience
*/
public ProxyExchange<T> body(Object body) {
this.body = body;
return this;
}
/**
* Sets a header for the downstream call.
* @param name Header name
* @param value Header values
* @return this for convenience
*/
public ProxyExchange<T> header(String name, String... value) {
this.headers.put(name, Arrays.asList(value));
return this;
}
/**
* Additional headers, or overrides of the incoming ones, to be used in the downstream
* call.
* @param headers the http headers to use in the downstream call
* @return this for convenience
*/
public ProxyExchange<T> headers(HttpHeaders headers) {
this.headers.putAll(headers);
return this;
}
/**
* Sets the names of sensitive headers that are not passed downstream to the backend
* service.
* @param names the names of sensitive headers
* @return this for convenience
*/
public ProxyExchange<T> sensitive(String... names) {
if (this.sensitive == null) {
this.sensitive = new HashSet<>();
}
this.sensitive.clear();
for (String name : names) {
this.sensitive.add(name.toLowerCase());
}
return this;
}
/**
* Sets the uri for the backend call when triggered by the HTTP methods.
* @param uri the backend uri to send the request to
* @return this for convenience
*/
public ProxyExchange<T> uri(URI uri) {
this.uri = uri;
return this;
}
/**
* Sets the uri for the backend call when triggered by the HTTP methods.
* @param uri the backend uri to send the request to
* @return this for convenience
*/
public ProxyExchange<T> uri(String uri) {
try {
return this.uri(new URI(uri));
}
catch (URISyntaxException e) {
throw new IllegalStateException("Cannot create URI", e);
}
}
public String path() {
return (String) this.webRequest.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE,
WebRequest.SCOPE_REQUEST);
}
public String path(String prefix) {
String path = path();
if (!path.startsWith(prefix)) {
throw new IllegalArgumentException("Path does not start with prefix (" + prefix + "): " + path);
}
return path.substring(prefix.length());
}
public void forward(String path) {
HttpServletRequest request = this.webRequest.getNativeRequest(HttpServletRequest.class);
HttpServletResponse response = this.webRequest.getNativeResponse(HttpServletResponse.class);
try {
request.getRequestDispatcher(path).forward(new BodyForwardingHttpServletRequest(request, response),
response);
}
catch (Exception e) {
throw new IllegalStateException("Cannot forward request", e);
}
}
public ResponseEntity<T> get() {
RequestEntity<?> requestEntity = headers((BodyBuilder) RequestEntity.get(uri)).body(body());
return exchange(requestEntity);
}
public <S> ResponseEntity<S> get(Function<ResponseEntity<T>, ResponseEntity<S>> converter) {
return converter.apply(get());
}
public ResponseEntity<T> head() {
RequestEntity<?> requestEntity = headers((BodyBuilder) RequestEntity.head(uri)).build();
return exchange(requestEntity);
}
public <S> ResponseEntity<S> head(Function<ResponseEntity<T>, ResponseEntity<S>> converter) {
return converter.apply(head());
}
public ResponseEntity<T> options() {
RequestEntity<?> requestEntity = headers((BodyBuilder) RequestEntity.options(uri)).build();
return exchange(requestEntity);
}
public <S> ResponseEntity<S> options(Function<ResponseEntity<T>, ResponseEntity<S>> converter) {
return converter.apply(options());
}
public ResponseEntity<T> post() {
RequestEntity<Object> requestEntity = headers(RequestEntity.post(uri)).body(body());
return exchange(requestEntity);
}
public <S> ResponseEntity<S> post(Function<ResponseEntity<T>, ResponseEntity<S>> converter) {
return converter.apply(post());
}
public ResponseEntity<T> delete() {
RequestEntity<Object> requestEntity = headers((BodyBuilder) RequestEntity.delete(uri)).body(body());
return exchange(requestEntity);
}
public <S> ResponseEntity<S> delete(Function<ResponseEntity<T>, ResponseEntity<S>> converter) {
return converter.apply(delete());
}
public ResponseEntity<T> put() {
RequestEntity<Object> requestEntity = headers(RequestEntity.put(uri)).body(body());
return exchange(requestEntity);
}
public <S> ResponseEntity<S> put(Function<ResponseEntity<T>, ResponseEntity<S>> converter) {
return converter.apply(put());
}
public ResponseEntity<T> patch() {
RequestEntity<Object> requestEntity = headers(RequestEntity.patch(uri)).body(body());
return exchange(requestEntity);
}
public <S> ResponseEntity<S> patch(Function<ResponseEntity<T>, ResponseEntity<S>> converter) {
return converter.apply(patch());
}
private ResponseEntity<T> exchange(RequestEntity<?> requestEntity) {
Type type = this.responseType;
if (type instanceof TypeVariable || type instanceof WildcardType) {
type = Object.class;
}
return rest.exchange(requestEntity, ParameterizedTypeReference.forType(type));
}
private void addHeaders(HttpHeaders headers) {
ArrayList<String> headerNames = new ArrayList<>();
webRequest.getHeaderNames().forEachRemaining(headerNames::add);
Set<String> filteredKeys = filterHeaderKeys(headerNames);
filteredKeys.stream().filter(key -> !headers.containsKey(key))
.forEach(header -> headers.addAll(header, Arrays.asList(webRequest.getHeaderValues(header))));
}
private BodyBuilder headers(BodyBuilder builder) {
proxy();
for (String name : filterHeaderKeys(headers)) {
builder.header(name, headers.get(name).toArray(new String[0]));
}
builder.headers(this::addHeaders);
return builder;
}
private Set<String> filterHeaderKeys(HttpHeaders headers) {
return filterHeaderKeys(headers.keySet());
}
private Set<String> filterHeaderKeys(Collection<String> headerNames) {
final Set<String> sensitiveHeaders = this.sensitive != null ? this.sensitive : DEFAULT_SENSITIVE;
return headerNames.stream().filter(header -> !sensitiveHeaders.contains(header.toLowerCase()))
.collect(Collectors.toSet());
}
private void proxy() {
try {
URI uri = new URI(webRequest.getNativeRequest(HttpServletRequest.class).getRequestURL().toString());
appendForwarded(uri);
appendXForwarded(uri);
}
catch (URISyntaxException e) {
throw new IllegalStateException("Cannot create URI for request: "
+ webRequest.getNativeRequest(HttpServletRequest.class).getRequestURL());
}
}
private void appendXForwarded(URI uri) {
// Append the legacy headers if they were already added upstream
String host = headers.getFirst("x-forwarded-host");
if (host == null) {
return;
}
host = host + "," + uri.getHost();
headers.set("x-forwarded-host", host);
String proto = headers.getFirst("x-forwarded-proto");
if (proto == null) {
return;
}
proto = proto + "," + uri.getScheme();
headers.set("x-forwarded-proto", proto);
}
private void appendForwarded(URI uri) {
String forwarded = headers.getFirst("forwarded");
if (forwarded != null) {
forwarded = forwarded + ",";
}
else {
forwarded = "";
}
forwarded = forwarded + forwarded(uri, webRequest.getHeader("host"));
headers.set("forwarded", forwarded);
}
private String forwarded(URI uri, String hostHeader) {
if (StringUtils.hasText(hostHeader)) {
return "host=" + hostHeader;
}
if ("http".equals(uri.getScheme())) {
return "host=" + uri.getHost();
}
return String.format("host=%s;proto=%s", uri.getHost(), uri.getScheme());
}
private Object body() {
if (body != null) {
return body;
}
body = getRequestBody();
return body;
}
/**
* Search for the request body if it was already deserialized using
* <code>@RequestBody</code>. If it is not found then deserialize it in the same way
* that it would have been for a <code>@RequestBody</code>.
* @return the request body
*/
private Object getRequestBody() {
for (String key : mavContainer.getModel().keySet()) {
if (key.startsWith(BindingResult.MODEL_KEY_PREFIX)) {
BindingResult result = (BindingResult) mavContainer.getModel().get(key);
return result.getTarget();
}
}
MethodParameter input = new MethodParameter(ClassUtils.getMethod(BodyGrabber.class, "body", Object.class), 0);
try {
delegate.resolveArgument(input, mavContainer, webRequest, binderFactory);
}
catch (Exception e) {
throw new IllegalStateException("Cannot resolve body", e);
}
String name = Conventions.getVariableNameForParameter(input);
BindingResult result = (BindingResult) mavContainer.getModel().get(BindingResult.MODEL_KEY_PREFIX + name);
return result.getTarget();
}
protected static class BodyGrabber {
public Object body(@RequestBody(required = false) Object body) {
return body;
}
}
protected static class BodySender {
@ResponseBody
public Object body() {
return null;
}
}
/**
* A servlet request wrapper that can be safely passed downstream to an internal
* forward dispatch, caching its body, and making it available in converted form using
* Spring message converters.
*
*/
class BodyForwardingHttpServletRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
private HttpServletResponse response;
BodyForwardingHttpServletRequest(HttpServletRequest request, HttpServletResponse response) {
super(request);
this.request = request;
this.response = response;
}
private List<String> header(String name) {
List<String> list = headers.get(name);
return list;
}
@Override
public ServletInputStream getInputStream() throws IOException {
Object body = body();
MethodParameter output = new MethodParameter(ClassUtils.getMethod(BodySender.class, "body"), -1);
ServletOutputToInputConverter response = new ServletOutputToInputConverter(this.response);
ServletWebRequest webRequest = new ServletWebRequest(this.request, response);
try {
delegate.handleReturnValue(body, output, mavContainer, webRequest);
}
catch (HttpMessageNotWritableException | HttpMediaTypeNotAcceptableException e) {
throw new IllegalStateException("Cannot convert body", e);
}
return response.getInputStream();
}
@Override
public Enumeration<String> getHeaderNames() {
Set<String> names = headers.keySet();
if (names.isEmpty()) {
return super.getHeaderNames();
}
Set<String> result = new LinkedHashSet<>(names);
result.addAll(Collections.list(super.getHeaderNames()));
return new Vector<String>(result).elements();
}
@Override
public Enumeration<String> getHeaders(String name) {
List<String> list = header(name);
if (list != null) {
return new Vector<String>(list).elements();
}
return super.getHeaders(name);
}
@Override
public String getHeader(String name) {
List<String> list = header(name);
if (list != null && !list.isEmpty()) {
return list.iterator().next();
}
return super.getHeader(name);
}
}
}
/**
* Convenience class that converts an incoming request input stream into a form that can
* be easily deserialized to a Java object using Spring message converters. It is only
* used in a local forward dispatch, in which case there is a danger that the request body
* will need to be read and analysed more than once. Apart from using the message
* converters the other main feature of this class is that the request body is cached and
* can be read repeatedly as necessary.
*
* @author Dave Syer
*
*/
class ServletOutputToInputConverter extends HttpServletResponseWrapper {
private StringBuilder builder = new StringBuilder();
ServletOutputToInputConverter(HttpServletResponse response) {
super(response);
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
builder.append(Character.valueOf((char) b));
}
@Override
public void setWriteListener(WriteListener listener) {
}
@Override
public boolean isReady() {
return true;
}
};
}
public ServletInputStream getInputStream() {
ByteArrayInputStream body = new ByteArrayInputStream(builder.toString().getBytes());
return new ServletInputStream() {
@Override
public int read() throws IOException {
return body.read();
}
@Override
public void setReadListener(ReadListener listener) {
}
@Override
public boolean isReady() {
return true;
}
@Override
public boolean isFinished() {
return body.available() <= 0;
}
};
}
}

View File

@@ -1,124 +0,0 @@
/*
* Copyright 2016-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.mvc.config;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Set;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.cloud.gateway.mvc.ProxyExchange;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import static java.util.stream.Collectors.toSet;
/**
* @author Dave Syer
* @author Tim Ysewyn
*/
public class ProxyExchangeArgumentResolver implements HandlerMethodArgumentResolver {
private final RestTemplate rest;
private HttpHeaders headers;
private Set<String> autoForwardedHeaders;
private Set<String> sensitive;
public ProxyExchangeArgumentResolver(RestTemplate builder) {
this.rest = builder;
}
public void setHeaders(HttpHeaders headers) {
this.headers = headers;
}
public void setAutoForwardedHeaders(Set<String> autoForwardedHeaders) {
this.autoForwardedHeaders = autoForwardedHeaders == null ? null
: autoForwardedHeaders.stream().map(String::toLowerCase).collect(toSet());
}
public void setSensitive(Set<String> sensitive) {
this.sensitive = sensitive;
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return ProxyExchange.class.isAssignableFrom(parameter.getParameterType());
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
ProxyExchange<?> proxy = new ProxyExchange<>(rest, webRequest, mavContainer, binderFactory, type(parameter));
configureHeaders(proxy);
configureAutoForwardedHeaders(proxy, webRequest);
configureSensitive(proxy);
return proxy;
}
private Type type(MethodParameter parameter) {
Type type = parameter.getGenericParameterType();
if (type instanceof ParameterizedType) {
ParameterizedType param = (ParameterizedType) type;
type = param.getActualTypeArguments()[0];
}
return type;
}
private HttpHeaders extractAutoForwardedHeaders(NativeWebRequest webRequest) {
HttpServletRequest nativeRequest = webRequest.getNativeRequest(HttpServletRequest.class);
Enumeration<String> headerNames = nativeRequest.getHeaderNames();
HttpHeaders headers = new HttpHeaders();
while (headerNames.hasMoreElements()) {
String header = headerNames.nextElement();
if (this.autoForwardedHeaders.contains(header.toLowerCase())) {
headers.addAll(header, Collections.list(nativeRequest.getHeaders(header)));
}
}
return headers;
}
private void configureHeaders(final ProxyExchange<?> proxy) {
if (headers != null) {
proxy.headers(headers);
}
}
private void configureAutoForwardedHeaders(final ProxyExchange<?> proxy, final NativeWebRequest webRequest) {
if ((autoForwardedHeaders != null) && (autoForwardedHeaders.size() > 0)) {
proxy.headers(extractAutoForwardedHeaders(webRequest));
}
}
private void configureSensitive(final ProxyExchange<?> proxy) {
if (sensitive != null) {
proxy.sensitive(sensitive.toArray(new String[0]));
}
}
}

View File

@@ -1,86 +0,0 @@
/*
* Copyright 2016-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.mvc.config;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.mvc.ProxyExchange;
import org.springframework.http.HttpHeaders;
/**
* Configuration properties for the {@link ProxyExchange} argument handler in
* <code>@RequestMapping</code> methods.
*
* @author Dave Syer
* @author Tim Ysewyn
*
*/
@ConfigurationProperties("spring.cloud.gateway.proxy")
public class ProxyProperties {
/**
* Fixed header values that will be added to all downstream requests.
*/
private Map<String, String> headers = new LinkedHashMap<>();
/**
* A set of header names that should be send downstream by default.
*/
private Set<String> autoForward = new HashSet<>();
/**
* A set of sensitive header names that will not be sent downstream by default.
*/
private Set<String> sensitive = null;
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public Set<String> getAutoForward() {
return autoForward;
}
public void setAutoForward(Set<String> autoForward) {
this.autoForward = autoForward;
}
public Set<String> getSensitive() {
return sensitive;
}
public void setSensitive(Set<String> sensitive) {
this.sensitive = sensitive;
}
public HttpHeaders convertHeaders() {
HttpHeaders headers = new HttpHeaders();
for (String key : this.headers.keySet()) {
headers.set(key, this.headers.get(key));
}
return headers;
}
}

View File

@@ -1,90 +0,0 @@
/*
* Copyright 2016-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.mvc.config;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.gateway.mvc.ProxyExchange;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Autoconfiguration for the {@link ProxyExchange} argument handler in Spring MVC
* <code>@RequestMapping</code> methods.
*
* @author Dave Syer
* @author Tim Ysewyn
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication
@ConditionalOnClass({ HandlerMethodReturnValueHandler.class })
@EnableConfigurationProperties(ProxyProperties.class)
public class ProxyResponseAutoConfiguration implements WebMvcConfigurer {
@Autowired
private ApplicationContext context;
@Bean
@ConditionalOnMissingBean
public ProxyExchangeArgumentResolver proxyExchangeArgumentResolver(Optional<RestTemplateBuilder> optional,
ProxyProperties proxy) {
RestTemplateBuilder builder = optional.orElse(new RestTemplateBuilder());
RestTemplate template = builder.build();
template.setErrorHandler(new NoOpResponseErrorHandler());
template.getMessageConverters().add(new ByteArrayHttpMessageConverter() {
@Override
public boolean supports(Class<?> clazz) {
return true;
}
});
ProxyExchangeArgumentResolver resolver = new ProxyExchangeArgumentResolver(template);
resolver.setHeaders(proxy.convertHeaders());
resolver.setAutoForwardedHeaders(proxy.getAutoForward());
resolver.setSensitive(proxy.getSensitive()); // can be null
return resolver;
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(context.getBean(ProxyExchangeArgumentResolver.class));
}
private static class NoOpResponseErrorHandler extends DefaultResponseErrorHandler {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
}
}

View File

@@ -1,2 +0,0 @@
org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc=\
org.springframework.cloud.gateway.mvc.config.ProxyResponseAutoConfiguration

View File

@@ -1 +0,0 @@
org.springframework.cloud.gateway.mvc.config.ProxyResponseAutoConfiguration

View File

@@ -1,203 +0,0 @@
/*
* Copyright 2016-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.mvc;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.gateway.mvc.GetWithBodyRequestTests.TestApplication.Foo;
import org.springframework.cloud.gateway.mvc.config.ProxyExchangeArgumentResolver;
import org.springframework.cloud.gateway.mvc.config.ProxyProperties;
import org.springframework.cloud.gateway.mvc.http.GetWithBodyRequestClientHttpRequestFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = GetWithBodyRequestTests.TestApplication.class)
public class GetWithBodyRequestTests {
@Autowired
private TestRestTemplate rest;
@Autowired
private TestApplication testApplication;
@LocalServerPort
private int port;
@BeforeEach
public void init() throws Exception {
testApplication.setHome(new URI("http://localhost:" + port));
rest.getRestTemplate().setRequestFactory(new GetWithBodyRequestClientHttpRequestFactory());
}
@Test
public void get() {
assertThat(rest.getForObject("/proxy/0", Foo.class).getName()).isEqualTo("bye");
}
@Test
public void getWithBodyRequest() {
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
final Foo bodyRequest = new Foo("hello");
final HttpEntity<Foo> entity = new HttpEntity<>(bodyRequest, headers);
final ResponseEntity<Foo> response = rest.exchange("/proxy/get-with-body-request", HttpMethod.GET, entity,
Foo.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).isInstanceOfSatisfying(Foo.class,
foo -> assertThat(foo.getName()).isEqualTo("hello world"));
}
@SpringBootApplication
static class TestApplication {
@Autowired
private ProxyController proxyController;
public void setHome(URI home) {
proxyController.setHome(home);
}
@Bean
public ProxyExchangeArgumentResolver proxyExchangeArgumentResolver(final ProxyProperties proxy) {
ProxyExchangeArgumentResolver resolver = new ProxyExchangeArgumentResolver(
generateConfiguredRestTemplate());
resolver.setHeaders(proxy.convertHeaders());
resolver.setAutoForwardedHeaders(proxy.getAutoForward());
resolver.setSensitive(proxy.getSensitive());
return resolver;
}
private RestTemplate generateConfiguredRestTemplate() {
final RestTemplateBuilder builder = new RestTemplateBuilder();
final RestTemplate template = builder.build();
template.setRequestFactory(new GetWithBodyRequestClientHttpRequestFactory());
template.setErrorHandler(new NoOpResponseErrorHandler());
template.getMessageConverters().add(new ByteArrayHttpMessageConverter() {
@Override
public boolean supports(Class<?> clazz) {
return true;
}
});
return template;
}
@RestController
static class ProxyController {
private URI home;
public void setHome(URI home) {
this.home = home;
}
@GetMapping("/proxy/{id}")
public ResponseEntity<?> proxyFoos(@PathVariable Integer id, ProxyExchange<?> proxy) throws Exception {
return proxy.uri(home.toString() + "/foos/" + id).get();
}
@GetMapping("/proxy/get-with-body-request")
public ResponseEntity<?> proxyFooWithBody(@RequestBody Foo foo, ProxyExchange<?> proxy) throws Exception {
return proxy.uri(home.toString() + "/foo/get-with-body-request").get();
}
}
@RestController
static class TestController {
@GetMapping("/foos/{id}")
public Foo foo(@PathVariable Integer id, @RequestHeader HttpHeaders headers) {
String custom = headers.getFirst("X-Custom");
return new Foo(id == 1 ? "foo" : custom != null ? custom : "bye");
}
@GetMapping("/foo/get-with-body-request")
public Foo getWithBody(@RequestBody Foo foo) {
return new Foo(foo.getName() + " world");
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
static class Foo {
private String name;
Foo() {
}
Foo(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
private static class NoOpResponseErrorHandler extends DefaultResponseErrorHandler {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
}
}
}

View File

@@ -1,540 +0,0 @@
/*
* Copyright 2016-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.mvc;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.cloud.gateway.mvc.ProductionConfigurationTests.TestApplication;
import org.springframework.cloud.gateway.mvc.ProductionConfigurationTests.TestApplication.Bar;
import org.springframework.cloud.gateway.mvc.ProductionConfigurationTests.TestApplication.Foo;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(properties = { "spring.cloud.gateway.proxy.auto-forward=Baz" },
webEnvironment = WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = TestApplication.class)
public class ProductionConfigurationTests {
@Autowired
private TestRestTemplate rest;
@Autowired
private TestApplication application;
@LocalServerPort
private int port;
@BeforeEach
public void init() {
application.setHome(URI.create("http://localhost:" + port));
rest.getRestTemplate().setRequestFactory(new SimpleClientHttpRequestFactory());
}
@Test
public void get() {
assertThat(rest.getForObject("/proxy/0", Foo.class).getName()).isEqualTo("bye");
}
@Test
public void path() {
assertThat(rest.getForObject("/proxy/path/1", Foo.class).getName()).isEqualTo("foo");
}
@Test
public void resource() {
assertThat(rest.getForObject("/proxy/html/test.html", String.class)).contains("<body>Test");
}
@Test
public void resourceWithNoType() {
assertThat(rest.getForObject("/proxy/typeless/test.html", String.class)).contains("<body>Test");
}
@Test
public void missing() {
assertThat(rest.getForEntity("/proxy/missing/0", Foo.class).getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
}
@Test
public void uri() {
assertThat(rest.getForObject("/proxy/0", Foo.class).getName()).isEqualTo("bye");
}
@Test
public void post() {
assertThat(rest.postForObject("/proxy/0", Collections.singletonMap("name", "foo"), Bar.class).getName())
.isEqualTo("host=localhost:" + port + ";foo");
}
@Test
public void forward() {
assertThat(rest.getForObject("/forward/foos/0", Foo.class).getName()).isEqualTo("bye");
}
@Test
public void forwardHeader() {
ResponseEntity<Foo> result = rest.getForEntity("/forward/special/foos/0", Foo.class);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(result.getBody().getName()).isEqualTo("FOO");
}
@Test
public void postForwardHeader() {
ResponseEntity<List<Bar>> result = rest.exchange(
RequestEntity.post(rest.getRestTemplate().getUriTemplateHandler().expand("/forward/special/bars"))
.body(Collections.singletonList(Collections.singletonMap("name", "foo"))),
new ParameterizedTypeReference<List<Bar>>() {
});
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(result.getBody().iterator().next().getName()).isEqualTo("FOOfoo");
}
@Test
public void postForwardBody() {
ResponseEntity<String> result = rest
.exchange(
RequestEntity.post(rest.getRestTemplate().getUriTemplateHandler().expand("/forward/body/bars"))
.body(Collections.singletonList(Collections.singletonMap("name", "foo"))),
String.class);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(result.getBody()).contains("foo");
}
@Test
public void postForwardForgetBody() {
ResponseEntity<String> result = rest.exchange(
RequestEntity.post(rest.getRestTemplate().getUriTemplateHandler().expand("/forward/forget/bars"))
.body(Collections.singletonList(Collections.singletonMap("name", "foo"))),
String.class);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(result.getBody()).contains("foo");
}
@Test
public void postForwardBodyFoo() {
ResponseEntity<List<Bar>> result = rest.exchange(
RequestEntity.post(rest.getRestTemplate().getUriTemplateHandler().expand("/forward/body/bars"))
.body(Collections.singletonList(Collections.singletonMap("name", "foo"))),
new ParameterizedTypeReference<List<Bar>>() {
});
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(result.getBody().iterator().next().getName()).isEqualTo("foo");
}
@Test
public void list() {
assertThat(rest.exchange(
RequestEntity.post(rest.getRestTemplate().getUriTemplateHandler().expand("/proxy"))
.body(Collections.singletonList(Collections.singletonMap("name", "foo"))),
new ParameterizedTypeReference<List<Bar>>() {
}).getBody().iterator().next().getName()).isEqualTo("host=localhost:" + port + ";foo");
}
@Test
public void bodyless() {
assertThat(rest.postForObject("/proxy/0", Collections.singletonMap("name", "foo"), Bar.class).getName())
.isEqualTo("host=localhost:" + port + ";foo");
}
@Test
public void entity() {
assertThat(
rest.exchange(RequestEntity.post(rest.getRestTemplate().getUriTemplateHandler().expand("/proxy/entity"))
.body(Collections.singletonMap("name", "foo")), new ParameterizedTypeReference<List<Bar>>() {
}).getBody().iterator().next().getName()).isEqualTo("host=localhost:" + port + ";foo");
}
@Test
public void entityWithType() {
assertThat(
rest.exchange(RequestEntity.post(rest.getRestTemplate().getUriTemplateHandler().expand("/proxy/type"))
.body(Collections.singletonMap("name", "foo")), new ParameterizedTypeReference<List<Bar>>() {
}).getBody().iterator().next().getName()).isEqualTo("host=localhost:" + port + ";foo");
}
@Test
public void single() {
assertThat(rest.postForObject("/proxy/single", Collections.singletonMap("name", "foobar"), Bar.class).getName())
.isEqualTo("host=localhost:" + port + ";foobar");
}
@Test
public void converter() {
assertThat(
rest.postForObject("/proxy/converter", Collections.singletonMap("name", "foobar"), Bar.class).getName())
.isEqualTo("host=localhost:" + port + ";foobar");
}
@Test
public void noBody() {
Foo foo = rest.postForObject("/proxy/no-body", null, Foo.class);
assertThat(foo.getName()).isEqualTo("hello");
}
@Test
public void deleteWithoutBody() {
ResponseEntity<Void> deleteResponse = rest.exchange("/proxy/{id}/no-body", HttpMethod.DELETE, null, Void.TYPE,
Collections.singletonMap("id", "123"));
assertThat(deleteResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
public void deleteWithBody() {
Foo foo = new Foo("to-be-deleted");
ParameterizedTypeReference<Map<String, Foo>> returnType = new ParameterizedTypeReference<Map<String, Foo>>() {
};
ResponseEntity<Map<String, Foo>> deleteResponse = rest.exchange("/proxy/{id}", HttpMethod.DELETE,
new HttpEntity<Foo>(foo), returnType, Collections.singletonMap("id", "123"));
assertThat(deleteResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(deleteResponse.getBody().get("deleted")).usingRecursiveComparison().isEqualTo(foo);
}
@Test
@SuppressWarnings({ "Duplicates", "unchecked" })
public void testSensitiveHeadersOverride() {
RequestEntity<Void> request = RequestEntity
.get(rest.getRestTemplate().getUriTemplateHandler().expand("/proxy/headers")).header("foo", "bar")
.header("abc", "xyz").header("cookie", "monster").build();
Map<String, List<String>> headers = rest.exchange(request, Map.class).getBody();
assertThat(headers).doesNotContainKey("foo").doesNotContainKey("hello").containsKeys("bar", "abc");
assertThat(headers.get("cookie")).containsOnly("monster");
}
@Test
@SuppressWarnings({ "Duplicates", "unchecked" })
public void testSensitiveHeadersDefault() {
Map<String, List<String>> headers = rest.exchange(RequestEntity
.get(rest.getRestTemplate().getUriTemplateHandler().expand("/proxy/sensitive-headers-default"))
.header("cookie", "monster").build(), Map.class).getBody();
assertThat(headers).doesNotContainKey("cookie");
}
@Test
@SuppressWarnings({ "Duplicates", "unchecked" })
public void headers() {
Map<String, List<String>> headers = rest
.exchange(RequestEntity.get(rest.getRestTemplate().getUriTemplateHandler().expand("/proxy/headers"))
.header("foo", "bar").header("abc", "xyz").header("baz", "fob").build(), Map.class)
.getBody();
assertThat(headers).doesNotContainKey("foo").doesNotContainKey("hello").containsKeys("bar", "abc");
assertThat(headers.get("bar")).containsOnly("hello");
assertThat(headers.get("abc")).containsOnly("123");
assertThat(headers.get("baz")).containsOnly("fob");
}
@Test
public void forwardedHeaderUsesHost() {
Map<String, List<String>> headers = rest
.exchange(RequestEntity.get(rest.getRestTemplate().getUriTemplateHandler().expand("/proxy/headers"))
.header("host", "foo:1234").build(), Map.class)
.getBody();
assertThat(headers).containsKey("forwarded");
assertThat(headers.get("forwarded").size()).isEqualTo(1);
assertThat(headers.get("forwarded").get(0)).isEqualTo("host=localhost:" + port);
}
@SpringBootApplication
static class TestApplication {
@Autowired
private ProxyController controller;
public void setHome(URI home) {
controller.setHome(home);
}
@RestController
static class ProxyController {
private URI home;
public void setHome(URI home) {
this.home = home;
}
@GetMapping("/proxy/{id}")
public ResponseEntity<?> proxyFoos(@PathVariable Integer id, ProxyExchange<?> proxy) {
return proxy.uri(home.toString() + "/foos/" + id).get();
}
@GetMapping("/proxy/path/**")
public ResponseEntity<?> proxyPath(ProxyExchange<?> proxy, UriComponentsBuilder uri) {
String path = proxy.path("/proxy/path/");
return proxy.uri(home.toString() + "/foos/" + path).get();
}
@GetMapping("/proxy/html/**")
public ResponseEntity<String> proxyHtml(ProxyExchange<String> proxy, UriComponentsBuilder uri) {
String path = proxy.path("/proxy/html");
return proxy.uri(home.toString() + path).get();
}
@GetMapping("/proxy/typeless/**")
public ResponseEntity<?> proxyTypeless(ProxyExchange<byte[]> proxy, UriComponentsBuilder uri) {
String path = proxy.path("/proxy/typeless");
return proxy.uri(home.toString() + path).get();
}
@GetMapping("/proxy/missing/{id}")
public ResponseEntity<?> proxyMissing(@PathVariable Integer id, ProxyExchange<?> proxy) {
return proxy.uri(home.toString() + "/missing/" + id).get();
}
@GetMapping("/proxy")
public ResponseEntity<?> proxyUri(ProxyExchange<?> proxy) {
return proxy.uri(home.toString() + "/foos").get();
}
@PostMapping("/proxy/{id}")
public ResponseEntity<?> proxyBars(@PathVariable Integer id, @RequestBody Map<String, Object> body,
ProxyExchange<List<Object>> proxy) {
body.put("id", id);
return proxy.uri(home.toString() + "/bars").body(Arrays.asList(body)).post(this::first);
}
@PostMapping("/proxy")
public ResponseEntity<?> barsWithNoBody(ProxyExchange<?> proxy) {
return proxy.uri(home.toString() + "/bars").post();
}
@PostMapping("/proxy/entity")
public ResponseEntity<?> explicitEntity(@RequestBody Foo foo, ProxyExchange<?> proxy) {
return proxy.uri(home.toString() + "/bars").body(Arrays.asList(foo)).post();
}
@PostMapping("/proxy/type")
public ResponseEntity<List<Bar>> explicitEntityWithType(@RequestBody Foo foo,
ProxyExchange<List<Bar>> proxy) {
return proxy.uri(home.toString() + "/bars").body(Arrays.asList(foo)).post();
}
@PostMapping("/proxy/single")
public ResponseEntity<?> implicitEntity(@RequestBody Foo foo, ProxyExchange<List<Object>> proxy) {
return proxy.uri(home.toString() + "/bars").body(Arrays.asList(foo)).post(this::first);
}
@PostMapping("/proxy/converter")
public ResponseEntity<Bar> implicitEntityWithConverter(@RequestBody Foo foo,
ProxyExchange<List<Bar>> proxy) {
return proxy.uri(home.toString() + "/bars").body(Arrays.asList(foo))
.post(response -> ResponseEntity.status(response.getStatusCode()).headers(response.getHeaders())
.body(response.getBody().iterator().next()));
}
@PostMapping("/proxy/no-body")
public ResponseEntity<Foo> noBody(ProxyExchange<Foo> proxy) {
return proxy.uri(home.toString() + "/foos").post();
}
@DeleteMapping("/proxy/{id}/no-body")
public ResponseEntity<?> deleteWithoutBody(@PathVariable Integer id, ProxyExchange<?> proxy) {
return proxy.uri(home.toString() + "/foos/" + id + "/no-body").delete();
}
@DeleteMapping("/proxy/{id}")
public ResponseEntity<?> deleteWithBody(@PathVariable Integer id, @RequestBody Foo foo,
ProxyExchange<?> proxy) {
return proxy.uri(home.toString() + "/foos/" + id).body(foo).delete(response -> ResponseEntity
.status(response.getStatusCode()).headers(response.getHeaders()).body(response.getBody()));
}
@GetMapping("/forward/**")
public void forward(ProxyExchange<?> proxy) {
String path = proxy.path("/forward");
if (path.startsWith("/special")) {
proxy.header("X-Custom", "FOO");
path = proxy.path("/forward/special");
}
proxy.forward(path);
}
@PostMapping("/forward/**")
public void postForward(ProxyExchange<?> proxy) {
String path = proxy.path("/forward");
if (path.startsWith("/special")) {
proxy.header("X-Custom", "FOO");
path = proxy.path("/forward/special");
}
proxy.forward(path);
}
@PostMapping("/forward/body/**")
public void postForwardBody(@RequestBody byte[] body, ProxyExchange<?> proxy) {
String path = proxy.path("/forward/body");
proxy.body(body).forward(path);
}
@SuppressWarnings("unused")
@PostMapping("/forward/forget/**")
public void postForwardForgetBody(@RequestBody byte[] body, ProxyExchange<?> proxy) {
String path = proxy.path("/forward/forget");
proxy.forward(path);
}
@GetMapping("/proxy/headers")
@SuppressWarnings("Duplicates")
public ResponseEntity<Map<String, List<String>>> headers(ProxyExchange<Map<String, List<String>>> proxy) {
proxy.sensitive("foo", "hello");
proxy.header("bar", "hello");
proxy.header("abc", "123");
proxy.header("hello", "world");
return proxy.uri(home.toString() + "/headers").get();
}
@GetMapping("/proxy/sensitive-headers-default")
public ResponseEntity<Map<String, List<String>>> defaultSensitiveHeaders(
ProxyExchange<Map<String, List<String>>> proxy) {
proxy.header("bar", "hello");
proxy.header("abc", "123");
proxy.header("hello", "world");
return proxy.uri(home.toString() + "/headers").get();
}
private <T> ResponseEntity<T> first(ResponseEntity<List<T>> response) {
return ResponseEntity.status(response.getStatusCode()).headers(response.getHeaders())
.body(response.getBody().iterator().next());
}
}
@RestController
static class TestController {
@GetMapping("/foos")
public List<Foo> foos() {
return Arrays.asList(new Foo("hello"));
}
@PostMapping("/foos")
public Foo postFoos() {
return new Foo("hello");
}
@GetMapping("/foos/{id}")
public Foo foo(@PathVariable Integer id, @RequestHeader HttpHeaders headers) {
String custom = headers.getFirst("X-Custom");
return new Foo(id == 1 ? "foo" : custom != null ? custom : "bye");
}
@DeleteMapping("/foos/{id}/no-body")
public ResponseEntity<?> deleteFoo(@PathVariable Integer id) {
return ResponseEntity.ok().build();
}
@DeleteMapping("/foos/{id}")
public ResponseEntity<?> deleteFoo(@PathVariable Integer id, @RequestBody Foo foo) {
return ResponseEntity.ok().body(Collections.singletonMap("deleted", foo));
}
@PostMapping("/bars")
public List<Bar> bars(@RequestBody List<Foo> foos, @RequestHeader HttpHeaders headers) {
String custom = headers.getFirst("X-Custom");
custom = custom == null ? "" : custom;
custom = headers.getFirst("forwarded") == null ? custom : headers.getFirst("forwarded") + ";" + custom;
return Arrays.asList(new Bar(custom + foos.iterator().next().getName()));
}
@GetMapping("/headers")
public Map<String, List<String>> headers(@RequestHeader HttpHeaders headers) {
return new LinkedMultiValueMap<>(headers);
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
static class Foo {
private String name;
Foo() {
}
Foo(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
static class Bar {
private String name;
Bar() {
}
Bar(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
}

View File

@@ -1,118 +0,0 @@
/*
* Copyright 2016-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.mvc.config;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.gateway.mvc.ProxyExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.DefaultResponseErrorHandler;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = ProxyExchangeArgumentResolverTest.ProxyExchangeArgumentResolverTestApplication.class)
public class ProxyExchangeArgumentResolverTest {
@Autowired
private TestRestTemplate rest;
@Autowired
private ProxyExchangeArgumentResolverTestApplication application;
@LocalServerPort
private int port;
@BeforeEach
public void setUp() throws Exception {
application.setHome(new URI("http://localhost:" + port));
rest.getRestTemplate().setRequestFactory(new SimpleClientHttpRequestFactory());
}
@Test
public void shouldProxyRequestWhenProxyExchangeArgumentResolverIsNotConfigured() {
final ResponseEntity<String> response = rest.getForEntity("/proxy", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).contains("Hello World");
}
@SpringBootApplication
static class ProxyExchangeArgumentResolverTestApplication {
@Autowired
private ProxyController controller;
@Bean
public ProxyExchangeArgumentResolver proxyExchangeArgumentResolver() {
RestTemplateBuilder builder = new RestTemplateBuilder();
builder.errorHandler(new DefaultResponseErrorHandler());
builder.messageConverters(new ByteArrayHttpMessageConverter());
return new ProxyExchangeArgumentResolver(builder.build());
}
public void setHome(final URI home) {
controller.setHome(home);
}
@RestController
static class ProxyController {
private URI home;
public void setHome(URI home) {
this.home = home;
}
@GetMapping("/proxy")
public ResponseEntity<?> proxyFoo(ProxyExchange<?> proxy) {
return proxy.uri(home.toString() + "/foo").get();
}
}
@RestController
static class TestController {
@GetMapping("/foo")
public List<String> foo() {
return Collections.singletonList("Hello World");
}
}
}
}

View File

@@ -1,48 +0,0 @@
/*
* Copyright 2016-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.mvc.http;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.AbstractClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
abstract class AbstractBufferingClientHttpRequest extends AbstractClientHttpRequest {
private ByteArrayOutputStream bufferedOutput = new ByteArrayOutputStream(1024);
protected OutputStream getBodyInternal(HttpHeaders headers) {
return bufferedOutput;
}
protected abstract ClientHttpResponse executeInternal(HttpHeaders headers, byte[] body) throws IOException;
protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
final byte[] bytes = bufferedOutput.toByteArray();
if (headers.getContentLength() < 0L) {
headers.setContentLength(bytes.length);
}
final ClientHttpResponse response = executeInternal(headers, bytes);
bufferedOutput = new ByteArrayOutputStream(0);
return response;
}
}

View File

@@ -1,131 +0,0 @@
/*
* Copyright 2016-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.mvc.http;
import java.io.Closeable;
import java.io.IOException;
import java.net.URI;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.Configurable;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpTrace;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
public class GetWithBodyRequestClientHttpRequestFactory implements ClientHttpRequestFactory, DisposableBean {
private final HttpClient httpClient;
public GetWithBodyRequestClientHttpRequestFactory() {
this.httpClient = HttpClients.createSystem();
}
@Override
public ClientHttpRequest createRequest(final URI uri, final HttpMethod httpMethod) throws IOException {
final HttpUriRequest httpRequest = createHttpUriRequest(httpMethod, uri);
final HttpContext context = HttpClientContext.create();
if (context.getAttribute("http.request-config") == null) {
RequestConfig config = null;
if (httpRequest instanceof Configurable) {
config = ((Configurable) httpRequest).getConfig();
}
if (config == null) {
config = createRequestConfig(httpClient);
}
if (config != null) {
context.setAttribute("http.request-config", config);
}
}
return new HttpComponentsClientHttpRequest(httpClient, httpRequest, context);
}
private HttpUriRequest createHttpUriRequest(final HttpMethod httpMethod, final URI uri) {
if (httpMethod.equals(HttpMethod.GET)) {
return new GetWithEntity(uri);
}
else if (httpMethod.equals(HttpMethod.HEAD)) {
return new HttpHead(uri);
}
else if (httpMethod.equals(HttpMethod.OPTIONS)) {
return new HttpOptions(uri);
}
else if (httpMethod.equals(HttpMethod.POST)) {
return new HttpPost(uri);
}
else if (httpMethod.equals(HttpMethod.DELETE)) {
return new HttpDelete(uri);
}
else if (httpMethod.equals(HttpMethod.PUT)) {
return new HttpPut(uri);
}
else if (httpMethod.equals(HttpMethod.PATCH)) {
return new HttpPatch(uri);
}
else if (httpMethod.equals(HttpMethod.TRACE)) {
return new HttpTrace(uri);
}
throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
}
private RequestConfig createRequestConfig(final HttpClient client) {
if (client instanceof Configurable) {
return ((Configurable) client).getConfig();
}
return null;
}
@Override
public void destroy() throws Exception {
if (httpClient instanceof Closeable) {
((Closeable) httpClient).close();
}
}
public static class GetWithEntity extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "GET";
public GetWithEntity(final URI uri) {
setURI(uri);
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}
}

View File

@@ -1,99 +0,0 @@
/*
* Copyright 2016-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.mvc.http;
import java.io.IOException;
import java.net.URI;
import java.util.Iterator;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StringUtils;
final class HttpComponentsClientHttpRequest extends AbstractBufferingClientHttpRequest {
private static final String COOKIE_HEADER_NAME = "Cookie";
private static final String CONTENT_LENGTH_HEADER_NAME = "Content-Length";
private static final String TRANSFER_ENCODING_HEADER_NAME = "Transfer-Encoding";
private final HttpClient httpClient;
private final HttpUriRequest httpRequest;
private final HttpContext httpContext;
HttpComponentsClientHttpRequest(final HttpClient httpClient, final HttpUriRequest httpRequest,
final HttpContext httpContext) {
this.httpClient = httpClient;
this.httpRequest = httpRequest;
this.httpContext = httpContext;
}
@Override
public HttpMethod getMethod() {
return HttpMethod.valueOf(httpRequest.getMethod());
}
@Override
public URI getURI() {
return httpRequest.getURI();
}
@Override
protected ClientHttpResponse executeInternal(final HttpHeaders headers, final byte[] bufferedOutput)
throws IOException {
addHeaders(headers);
attachBodyRequest(bufferedOutput);
final HttpResponse response = httpClient.execute(httpRequest, httpContext);
return new HttpComponentsClientHttpResponse(response);
}
private void addHeaders(final HttpHeaders headers) {
headers.forEach((headerName, headerValues) -> {
if (COOKIE_HEADER_NAME.equalsIgnoreCase(headerName)) {
String headerValue = StringUtils.collectionToDelimitedString(headerValues, ": ");
httpRequest.addHeader(headerName, headerValue);
}
else if (!CONTENT_LENGTH_HEADER_NAME.equalsIgnoreCase(headerName)
&& !TRANSFER_ENCODING_HEADER_NAME.equalsIgnoreCase(headerName)) {
final Iterator<String> it = headerValues.iterator();
while (it.hasNext()) {
String value = it.next();
httpRequest.addHeader(headerName, value);
}
}
});
}
private void attachBodyRequest(final byte[] bufferedOutput) {
if (httpRequest instanceof HttpEntityEnclosingRequest) {
((HttpEntityEnclosingRequest) httpRequest).setEntity(new ByteArrayEntity(bufferedOutput));
}
}
}

View File

@@ -1,88 +0,0 @@
/*
* Copyright 2016-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.mvc.http;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.AbstractClientHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.util.StreamUtils;
final class HttpComponentsClientHttpResponse extends AbstractClientHttpResponse {
private final HttpResponse response;
@Nullable
private HttpHeaders headers;
HttpComponentsClientHttpResponse(final HttpResponse response) {
this.response = response;
}
@Override
public int getRawStatusCode() throws IOException {
return response.getStatusLine().getStatusCode();
}
@Override
public String getStatusText() throws IOException {
return response.getStatusLine().getReasonPhrase();
}
@Override
public HttpHeaders getHeaders() {
if (headers == null) {
headers = new HttpHeaders();
final Header[] responseHeaders = response.getAllHeaders();
for (Header header : responseHeaders) {
headers.add(header.getName(), header.getValue());
}
}
return headers;
}
@Override
public InputStream getBody() throws IOException {
final HttpEntity entity = response.getEntity();
return entity != null ? entity.getContent() : StreamUtils.emptyInput();
}
@Override
public void close() {
try {
try {
EntityUtils.consume(response.getEntity());
}
finally {
if (response instanceof Closeable) {
((Closeable) response).close();
}
}
}
catch (IOException ignored) {
}
}
}

View File

@@ -1,4 +0,0 @@
<html>
<body>Test
</body>
</html>

View File

@@ -1,177 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-gateway-sample</artifactId>
<packaging>jar</packaging>
<name>Spring Cloud Gateway Sample</name>
<description>Spring Cloud Gateway Sample</description>
<properties>
</properties>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway</artifactId>
<version>4.1.0-SNAPSHOT</version>
<relativePath>..</relativePath> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.isomorphism</groupId>
<artifactId>token-bucket</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-server</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-test-support</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-loadbalancer</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
<jvmTarget>17</jvmTarget>
</configuration>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<source>src/main/java</source>
<source>src/main/kotlin</source>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<source>src/test/java</source>
<source>src/test/kotlin</source>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
<executions>
<!-- Replacing default-compile as it is treated specially by maven -->
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<!-- Replacing default-testCompile as it is treated specially by maven -->
<execution>
<id>default-testCompile</id>
<phase>none</phase>
</execution>
<execution>
<id>java-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>java-test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -1,194 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.sample;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import reactor.core.publisher.Mono;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
/**
* @author Spencer Gibb
*/
@SpringBootConfiguration
@EnableAutoConfiguration
@Import(AdditionalRoutes.class)
public class GatewaySampleApplication {
public static final String HELLO_FROM_FAKE_ACTUATOR_METRICS_GATEWAY_REQUESTS = "hello from fake /actuator/metrics/spring.cloud.gateway.requests";
@Value("${test.uri:http://httpbin.org:80}")
String uri;
public static void main(String[] args) {
SpringApplication.run(GatewaySampleApplication.class, args);
}
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
//@formatter:off
// String uri = "http://httpbin.org:80";
// String uri = "http://localhost:9080";
return builder.routes()
.route(r -> r.host("**.abc.org").and().path("/anything/png")
.filters(f ->
f.prefixPath("/httpbin")
.addResponseHeader("X-TestHeader", "foobar"))
.uri(uri)
)
.route("read_body_pred", r -> r.host("*.readbody.org")
.and().readBody(String.class,
s -> s.trim().equalsIgnoreCase("hi"))
.filters(f -> f.prefixPath("/httpbin")
.addResponseHeader("X-TestHeader", "read_body_pred")
).uri(uri)
)
.route("rewrite_request_obj", r -> r.host("*.rewriterequestobj.org")
.filters(f -> f.prefixPath("/httpbin")
.addResponseHeader("X-TestHeader", "rewrite_request")
.modifyRequestBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE,
(exchange, s) -> {
return Mono.just(new Hello(s.toUpperCase()));
})
).uri(uri)
)
.route("rewrite_request_upper", r -> r.host("*.rewriterequestupper.org")
.filters(f -> f.prefixPath("/httpbin")
.addResponseHeader("X-TestHeader", "rewrite_request_upper")
.modifyRequestBody(String.class, String.class,
(exchange, s) -> {
return Mono.just(s.toUpperCase() + s.toUpperCase());
})
).uri(uri)
)
.route("rewrite_response_upper", r -> r.host("*.rewriteresponseupper.org")
.filters(f -> f.prefixPath("/httpbin")
.addResponseHeader("X-TestHeader", "rewrite_response_upper")
.modifyResponseBody(String.class, String.class,
(exchange, s) -> {
return Mono.just(s.toUpperCase());
})
).uri(uri)
)
.route("rewrite_empty_response", r -> r.host("*.rewriteemptyresponse.org")
.filters(f -> f.prefixPath("/httpbin")
.addResponseHeader("X-TestHeader", "rewrite_empty_response")
.modifyResponseBody(String.class, String.class,
(exchange, s) -> {
if (s == null) {
return Mono.just("emptybody");
}
return Mono.just(s.toUpperCase());
})
).uri(uri)
)
.route("rewrite_response_fail_supplier", r -> r.host("*.rewriteresponsewithfailsupplier.org")
.filters(f -> f.prefixPath("/httpbin")
.addResponseHeader("X-TestHeader", "rewrite_response_fail_supplier")
.modifyResponseBody(String.class, String.class,
(exchange, s) -> {
if (s == null) {
return Mono.error(new IllegalArgumentException("this should not happen"));
}
return Mono.just(s.toUpperCase());
})
).uri(uri)
)
.route("rewrite_response_obj", r -> r.host("*.rewriteresponseobj.org")
.filters(f -> f.prefixPath("/httpbin")
.addResponseHeader("X-TestHeader", "rewrite_response_obj")
.modifyResponseBody(Map.class, String.class, MediaType.TEXT_PLAIN_VALUE,
(exchange, map) -> {
Object data = map.get("data");
return Mono.just(data.toString());
})
.setResponseHeader("Content-Type", MediaType.TEXT_PLAIN_VALUE)
).uri(uri)
)
.route(r -> r.path("/image/webp")
.filters(f ->
f.prefixPath("/httpbin")
.addResponseHeader("X-AnotherHeader", "baz"))
.uri(uri)
)
.route(r -> r.order(-1)
.host("**.throttle.org").and().path("/get")
.filters(f -> f.prefixPath("/httpbin")
.filter(new ThrottleGatewayFilter()
.setCapacity(1)
.setRefillTokens(1)
.setRefillPeriod(10)
.setRefillUnit(TimeUnit.SECONDS)))
.uri(uri)
)
.build();
//@formatter:on
}
@Bean
public RouterFunction<ServerResponse> testFunRouterFunction() {
RouterFunction<ServerResponse> route = RouterFunctions.route(RequestPredicates.path("/testfun"),
request -> ServerResponse.ok().body(BodyInserters.fromValue("hello")));
return route;
}
@Bean
public RouterFunction<ServerResponse> testWhenMetricPathIsNotMeet() {
RouterFunction<ServerResponse> route = RouterFunctions.route(
RequestPredicates.path("/actuator/metrics/spring.cloud.gateway.requests"), request -> ServerResponse
.ok().body(BodyInserters.fromValue(HELLO_FROM_FAKE_ACTUATOR_METRICS_GATEWAY_REQUESTS)));
return route;
}
static class Hello {
String message;
Hello() {
}
Hello(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
}

View File

@@ -1,99 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.sample;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.isomorphism.util.TokenBucket;
import org.isomorphism.util.TokenBuckets;
import reactor.core.publisher.Mono;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
/**
* Sample throttling filter. See https://github.com/bbeck/token-bucket
*/
public class ThrottleGatewayFilter implements GatewayFilter {
private static final Log log = LogFactory.getLog(ThrottleGatewayFilter.class);
int capacity;
int refillTokens;
int refillPeriod;
TimeUnit refillUnit;
public int getCapacity() {
return capacity;
}
public ThrottleGatewayFilter setCapacity(int capacity) {
this.capacity = capacity;
return this;
}
public int getRefillTokens() {
return refillTokens;
}
public ThrottleGatewayFilter setRefillTokens(int refillTokens) {
this.refillTokens = refillTokens;
return this;
}
public int getRefillPeriod() {
return refillPeriod;
}
public ThrottleGatewayFilter setRefillPeriod(int refillPeriod) {
this.refillPeriod = refillPeriod;
return this;
}
public TimeUnit getRefillUnit() {
return refillUnit;
}
public ThrottleGatewayFilter setRefillUnit(TimeUnit refillUnit) {
this.refillUnit = refillUnit;
return this;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
TokenBucket tokenBucket = TokenBuckets.builder().withCapacity(capacity)
.withFixedIntervalRefillStrategy(refillTokens, refillPeriod, refillUnit).build();
// TODO: get a token bucket for a key
log.debug("TokenBucket capacity: " + tokenBucket.getCapacity());
boolean consumed = tokenBucket.tryConsume();
if (consumed) {
return chain.filter(exchange);
}
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
return exchange.getResponse().setComplete();
}
}

View File

@@ -1,44 +0,0 @@
/*
* Copyright 2017-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.sample
import org.springframework.beans.factory.annotation.Value
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder
import org.springframework.cloud.gateway.route.builder.filters
import org.springframework.cloud.gateway.route.builder.routes
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration(proxyBeanMethods = false)
open class AdditionalRoutes {
@Value("\${test.uri:http://httpbin.org:80}")
var uri: String? = null
@Bean
open fun additionalRouteLocator(builder: RouteLocatorBuilder) = builder.routes {
route(id = "test-kotlin") {
host("kotlin.abc.org") and path("/anything/kotlinroute")
filters {
prefixPath("/httpbin")
addResponseHeader("X-TestHeader", "foobar")
}
uri(uri)
}
}
}

View File

@@ -1,43 +0,0 @@
test:
# hostport: httpbin.org:80
# hostport: localhost:5000
# uri: http://${test.hostport}
uri: lb://httpbin
spring:
jmx:
enabled: false
cloud:
gateway:
default-filters:
- PrefixPath=/httpbin
- AddResponseHeader=X-Response-Default-Foo, Default-Bar
routes:
# =====================================
# to run server
# $ wscat --listen 9000
# to run client
# $ wscat --connect ws://localhost:8080/echo
- id: websocket_test
uri: ws://localhost:9000
order: 9000
predicates:
- Path=/echo
# =====================================
- id: default_path_to_httpbin
uri: ${test.uri}
order: 10000
predicates:
- Path=/**
logging:
level:
org.springframework.cloud.gateway: TRACE
org.springframework.http.server.reactive: DEBUG
org.springframework.web.reactive: DEBUG
reactor.ipc.netty: DEBUG
reactor.netty: DEBUG
management.endpoints.web.exposure.include: '*'

View File

@@ -1,217 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.sample;
import java.io.IOException;
import java.time.Duration;
import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.gateway.config.GatewayMetricsProperties;
import org.springframework.cloud.gateway.test.HttpBinCompatibleController;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.ServiceInstanceListSuppliers;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.test.util.TestSocketUtils;
import org.springframework.test.web.reactive.server.WebTestClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author Spencer Gibb
*/
@SpringBootTest(classes = { GatewaySampleApplicationTests.TestConfig.class }, webEnvironment = RANDOM_PORT,
properties = { "management.endpoint.gateway.enabled=true", "management.server.port=${test.port}" })
public class GatewaySampleApplicationTests {
protected static int managementPort;
@Autowired
GatewayMetricsProperties metricsProperties;
@LocalServerPort
protected int port = 0;
protected WebTestClient webClient;
protected String baseUri;
@BeforeAll
public static void beforeClass() {
managementPort = TestSocketUtils.findAvailableTcpPort();
System.setProperty("test.port", String.valueOf(managementPort));
}
@AfterAll
public static void afterClass() {
System.clearProperty("test.port");
}
@BeforeEach
public void setup() {
baseUri = "http://localhost:" + port;
this.webClient = WebTestClient.bindToServer().responseTimeout(Duration.ofSeconds(10)).baseUrl(baseUri).build();
}
@Test
public void contextLoads() {
webClient.get().uri("/get").exchange().expectStatus().isOk();
}
@Test
@SuppressWarnings("unchecked")
public void readBodyPredicateStringWorks() {
webClient.post().uri("/post").header("Host", "www.readbody.org").bodyValue("hi").exchange().expectStatus()
.isOk().expectHeader().valueEquals("X-TestHeader", "read_body_pred").expectBody(Map.class)
.consumeWith(result -> assertThat(result.getResponseBody()).containsEntry("data", "hi"));
}
@Test
@SuppressWarnings("unchecked")
public void rewriteRequestBodyStringWorks() {
webClient.post().uri("/post").header("Host", "www.rewriterequestupper.org").bodyValue("hello").exchange()
.expectStatus().isOk().expectHeader().valueEquals("X-TestHeader", "rewrite_request_upper")
.expectBody(Map.class)
.consumeWith(result -> assertThat(result.getResponseBody()).containsEntry("data", "HELLOHELLO"));
}
@Test
@SuppressWarnings("unchecked")
public void rewriteRequestBodyObjectWorks() {
webClient.post().uri("/post").header("Host", "www.rewriterequestobj.org").bodyValue("hello").exchange()
.expectStatus().isOk().expectHeader().valueEquals("X-TestHeader", "rewrite_request")
.expectBody(Map.class).consumeWith(result -> assertThat(result.getResponseBody()).containsEntry("data",
"{\"message\":\"HELLO\"}"));
}
@Test
@SuppressWarnings("unchecked")
public void rewriteResponseBodyStringWorks() {
webClient.post().uri("/post").header("Host", "www.rewriteresponseupper.org").bodyValue("hello").exchange()
.expectStatus().isOk().expectHeader().valueEquals("X-TestHeader", "rewrite_response_upper")
.expectBody(Map.class)
.consumeWith(result -> assertThat(result.getResponseBody()).containsEntry("DATA", "HELLO"));
}
@Test
@SuppressWarnings("unchecked")
public void rewriteResponseEmptyBodyToStringWorks() {
webClient.post().uri("/post/empty").header("Host", "www.rewriteemptyresponse.org").exchange().expectStatus()
.isOk().expectHeader().valueEquals("X-TestHeader", "rewrite_empty_response").expectBody(String.class)
.consumeWith(result -> assertThat(result.getResponseBody()).isEqualTo("emptybody"));
}
@Test
@SuppressWarnings("unchecked")
public void emptyBodySupplierNotCalledWhenBodyPresent() {
webClient.post().uri("/post").header("Host", "www.rewriteresponsewithfailsupplier.org").bodyValue("hello")
.exchange().expectStatus().isOk().expectHeader()
.valueEquals("X-TestHeader", "rewrite_response_fail_supplier").expectBody(Map.class)
.consumeWith(result -> assertThat(result.getResponseBody()).containsEntry("DATA", "HELLO"));
}
@Test
@SuppressWarnings("unchecked")
public void rewriteResponeBodyObjectWorks() {
webClient.post().uri("/post").header("Host", "www.rewriteresponseobj.org").bodyValue("hello").exchange()
.expectStatus().isOk().expectHeader().valueEquals("X-TestHeader", "rewrite_response_obj")
.expectBody(String.class)
.consumeWith(result -> assertThat(result.getResponseBody()).isEqualTo("hello"));
}
@Test
public void complexPredicate() {
webClient.get().uri("/anything/png").header("Host", "www.abc.org").exchange().expectHeader()
.valueEquals("X-TestHeader", "foobar").expectStatus().isOk();
}
@Test
public void routeFromKotlin() {
webClient.get().uri("/anything/kotlinroute").header("Host", "kotlin.abc.org").exchange().expectHeader()
.valueEquals("X-TestHeader", "foobar").expectStatus().isOk();
}
@Test
public void actuatorManagementPort() {
webClient.get().uri("http://localhost:" + managementPort + "/actuator/gateway/routes").exchange().expectStatus()
.isOk();
}
@Test
public void actuatorMetrics() {
contextLoads();
String metricName = metricsProperties.getPrefix() + ".requests";
webClient.get().uri("http://localhost:" + managementPort + "/actuator/metrics/" + metricName).exchange()
.expectStatus().isOk().expectBody().consumeWith(i -> {
String body = new String(i.getResponseBodyContent());
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode actualObj = mapper.readTree(body);
JsonNode findValue = actualObj.findValue("name");
assertThat(findValue.asText()).as("Expected to find metric with name gateway.requests")
.isEqualTo(metricName);
}
catch (IOException e) {
throw new IllegalStateException(e);
}
});
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@LoadBalancerClient(name = "httpbin", configuration = LoadBalancerConfig.class)
@Import(GatewaySampleApplication.class)
protected static class TestConfig {
@Bean
public HttpBinCompatibleController httpBinCompatibleController() {
return new HttpBinCompatibleController();
}
}
protected static class LoadBalancerConfig {
@LocalServerPort
int port;
@Bean
public ServiceInstanceListSupplier fixedServiceInstanceListSupplier(Environment env) {
return ServiceInstanceListSuppliers.from("httpbin",
new DefaultServiceInstance("httpbin-1", "httpbin", "localhost", port, false));
}
}
}

View File

@@ -1,80 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.sample;
import java.time.Duration;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.gateway.sample.GatewaySampleApplicationTests.TestConfig;
import org.springframework.cloud.test.ClassPathExclusions;
import org.springframework.cloud.test.ModifiedClassPathRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.util.TestSocketUtils;
import org.springframework.test.web.reactive.server.WebTestClient;
@RunWith(ModifiedClassPathRunner.class)
@ClassPathExclusions({ "micrometer-core.jar", "spring-boot-actuator-*.jar",
"spring-boot-actuator-autoconfigure-*.jar" })
@DirtiesContext
public class GatewaySampleApplicationWithoutMetricsTests {
static protected int port;
protected WebTestClient webClient;
protected String baseUri;
@BeforeClass
public static void beforeClass() {
port = TestSocketUtils.findAvailableTcpPort();
System.setProperty("server.port", Integer.toString(port));
}
@AfterClass
public static void afterClass() {
System.clearProperty("server.port");
}
@Before
public void setup() {
baseUri = "http://localhost:" + port;
this.webClient = WebTestClient.bindToServer().responseTimeout(Duration.ofSeconds(10)).baseUrl(baseUri).build();
}
protected ConfigurableApplicationContext init(Class<?> config) {
return new SpringApplicationBuilder().web(WebApplicationType.REACTIVE)
.sources(GatewaySampleApplication.class, config).run();
}
@Test
public void actuatorMetrics() {
init(TestConfig.class);
webClient.get().uri("/get").exchange().expectStatus().isOk();
webClient.get().uri("http://localhost:" + port + "/actuator/metrics/spring.cloud.gateway.requests").exchange()
.expectStatus().isOk().expectBody(String.class)
.isEqualTo(GatewaySampleApplication.HELLO_FROM_FAKE_ACTUATOR_METRICS_GATEWAY_REQUESTS);
}
}

View File

@@ -1,104 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2013-2023 the original author or authors.
~
~ 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
~
~ https://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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway</artifactId>
<version>4.1.0-SNAPSHOT</version>
<relativePath>..</relativePath> <!-- lookup parent from repository -->
</parent>
<artifactId>spring-cloud-gateway-server-mvc</artifactId>
<packaging>jar</packaging>
<name>Spring Cloud Gateway Server MVC</name>
<description>Spring Cloud Gateway Server MVC</description>
<properties>
<main.basedir>${basedir}/..</main.basedir>
</properties>
<dependencies>
<!-- Spring dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-loadbalancer</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<optional>true</optional>
</dependency>
<!-- Third party dependencies -->
<dependency>
<groupId>com.bucket4j</groupId>
<artifactId>bucket4j-core</artifactId>
<optional>true</optional>
</dependency>
<!-- Spring test dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Third party test dependencies -->
<dependency>
<groupId>com.bucket4j</groupId>
<artifactId>bucket4j-caffeine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -1,164 +0,0 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.server.mvc;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration;
import org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration;
import org.springframework.boot.ssl.SslBundle;
import org.springframework.boot.ssl.SslBundles;
import org.springframework.boot.web.client.ClientHttpRequestFactories;
import org.springframework.boot.web.client.ClientHttpRequestFactorySettings;
import org.springframework.boot.web.client.RestClientCustomizer;
import org.springframework.cloud.gateway.server.mvc.common.ArgumentSupplierBeanPostProcessor;
import org.springframework.cloud.gateway.server.mvc.config.GatewayMvcProperties;
import org.springframework.cloud.gateway.server.mvc.config.GatewayMvcPropertiesBeanDefinitionRegistrar;
import org.springframework.cloud.gateway.server.mvc.filter.ForwardedRequestHeadersFilter;
import org.springframework.cloud.gateway.server.mvc.filter.HttpHeadersFilter.RequestHttpHeadersFilter;
import org.springframework.cloud.gateway.server.mvc.filter.HttpHeadersFilter.ResponseHttpHeadersFilter;
import org.springframework.cloud.gateway.server.mvc.filter.RemoveContentLengthRequestHeadersFilter;
import org.springframework.cloud.gateway.server.mvc.filter.RemoveHopByHopRequestHeadersFilter;
import org.springframework.cloud.gateway.server.mvc.filter.RemoveHopByHopResponseHeadersFilter;
import org.springframework.cloud.gateway.server.mvc.filter.TransferEncodingNormalizationRequestHeadersFilter;
import org.springframework.cloud.gateway.server.mvc.filter.WeightCalculatorFilter;
import org.springframework.cloud.gateway.server.mvc.filter.XForwardedRequestHeadersFilter;
import org.springframework.cloud.gateway.server.mvc.handler.ProxyExchange;
import org.springframework.cloud.gateway.server.mvc.handler.ProxyExchangeHandlerFunction;
import org.springframework.cloud.gateway.server.mvc.handler.RestClientProxyExchange;
import org.springframework.cloud.gateway.server.mvc.predicate.PredicateDiscoverer;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClient;
@AutoConfiguration(after = { RestTemplateAutoConfiguration.class, RestClientAutoConfiguration.class })
@Import(GatewayMvcPropertiesBeanDefinitionRegistrar.class)
public class GatewayServerMvcAutoConfiguration {
@Bean
public ArgumentSupplierBeanPostProcessor argumentSupplierBeanPostProcessor(ApplicationEventPublisher publisher) {
return new ArgumentSupplierBeanPostProcessor(publisher);
}
@Bean
public RestClientCustomizer gatewayRestClientCustomizer(ClientHttpRequestFactory requestFactory) {
return restClientBuilder -> restClientBuilder.requestFactory(requestFactory);
}
@Bean
@ConditionalOnMissingBean(ProxyExchange.class)
public RestClientProxyExchange restClientProxyExchange(RestClient.Builder restClientBuilder) {
return new RestClientProxyExchange(restClientBuilder.build());
}
@Bean
@ConditionalOnMissingBean
public ForwardedRequestHeadersFilter forwardedRequestHeadersFilter() {
return new ForwardedRequestHeadersFilter();
}
@Bean
@ConditionalOnMissingBean
public ClientHttpRequestFactory gatewayClientHttpRequestFactory(GatewayMvcProperties gatewayMvcProperties,
SslBundles sslBundles) {
GatewayMvcProperties.HttpClient properties = gatewayMvcProperties.getHttpClient();
SslBundle sslBundle = null;
if (StringUtils.hasText(properties.getSslBundle())) {
sslBundle = sslBundles.getBundle(properties.getSslBundle());
}
ClientHttpRequestFactorySettings settings = new ClientHttpRequestFactorySettings(properties.getConnectTimeout(),
properties.getReadTimeout(), sslBundle);
if (properties.getType() == GatewayMvcProperties.HttpClientType.JDK) {
// TODO: customize restricted headers
String restrictedHeaders = System.getProperty("jdk.httpclient.allowRestrictedHeaders");
if (!StringUtils.hasText(restrictedHeaders)) {
System.setProperty("jdk.httpclient.allowRestrictedHeaders", "host");
}
else if (StringUtils.hasText(restrictedHeaders) && !restrictedHeaders.contains("host")) {
System.setProperty("jdk.httpclient.allowRestrictedHeaders", restrictedHeaders + ",host");
}
return ClientHttpRequestFactories.get(JdkClientHttpRequestFactory.class, settings);
}
// Autodetect
return ClientHttpRequestFactories.get(settings);
}
@Bean
@ConditionalOnMissingBean
public GatewayMvcProperties gatewayMvcProperties() {
return new GatewayMvcProperties();
}
@Bean
public PredicateDiscoverer predicateDiscoverer() {
return new PredicateDiscoverer();
}
@Bean
@ConditionalOnMissingBean
public ProxyExchangeHandlerFunction proxyExchangeHandlerFunction(ProxyExchange proxyExchange,
ObjectProvider<RequestHttpHeadersFilter> requestHttpHeadersFilters,
ObjectProvider<ResponseHttpHeadersFilter> responseHttpHeadersFilters) {
return new ProxyExchangeHandlerFunction(proxyExchange, requestHttpHeadersFilters, responseHttpHeadersFilters);
}
@Bean
@ConditionalOnMissingBean
public RemoveContentLengthRequestHeadersFilter removeContentLengthRequestHeadersFilter() {
return new RemoveContentLengthRequestHeadersFilter();
}
@Bean
@ConditionalOnMissingBean
public RemoveHopByHopRequestHeadersFilter removeHopByHopRequestHeadersFilter() {
return new RemoveHopByHopRequestHeadersFilter();
}
@Bean
@ConditionalOnMissingBean
public RemoveHopByHopResponseHeadersFilter removeHopByHopResponseHeadersFilter() {
return new RemoveHopByHopResponseHeadersFilter();
}
@Bean
@ConditionalOnMissingBean
public TransferEncodingNormalizationRequestHeadersFilter transferEncodingNormalizationRequestHeadersFilter() {
return new TransferEncodingNormalizationRequestHeadersFilter();
}
@Bean
@ConditionalOnMissingBean
public WeightCalculatorFilter weightCalculatorFilter() {
return new WeightCalculatorFilter();
}
@Bean
@ConditionalOnMissingBean
public XForwardedRequestHeadersFilter xForwardedRequestHeadersFilter() {
return new XForwardedRequestHeadersFilter();
}
}

View File

@@ -1,80 +0,0 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.server.mvc.common;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Supplier;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.server.mvc.invoke.reflect.DefaultOperationMethod;
import org.springframework.cloud.gateway.server.mvc.invoke.reflect.OperationMethod;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.core.log.LogMessage;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
public abstract class AbstractGatewayDiscoverer {
protected final Log log = LogFactory.getLog(getClass());
protected volatile MultiValueMap<String, OperationMethod> operations = new LinkedMultiValueMap<>();
public <T extends Supplier<Collection<Method>>, R> void doDiscover(Class<T> supplierClass, Class<R> returnType) {
List<T> suppliers = loadSuppliers(supplierClass);
List<Method> methods = new ArrayList<>();
for (Supplier<Collection<Method>> supplier : suppliers) {
methods.addAll(supplier.get());
}
for (Method method : methods) {
// TODO: replace with a BiPredicate of some kind
if (returnType.isAssignableFrom(method.getReturnType())) {
addOperationMethod(method);
}
}
}
protected void addOperationMethod(Method method) {
OperationMethod operationMethod = new DefaultOperationMethod(method);
String key = method.getName();
operations.add(key, operationMethod);
log.trace(LogMessage.format("Discovered %s", operationMethod));
}
public abstract void discover();
protected <T> List<T> loadSuppliers(Class<T> supplierClass) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
List<T> suppliers = SpringFactoriesLoader.loadFactories(supplierClass, classLoader);
return suppliers;
}
public MultiValueMap<String, OperationMethod> getOperations() {
if (operations == null || operations.isEmpty()) {
discover();
}
return operations;
}
}

View File

@@ -1,33 +0,0 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.server.mvc.common;
public interface ArgumentSupplier<T> {
ArgumentSuppliedEvent<T> getArgumentSuppliedEvent();
interface ArgumentSuppliedEvent<T> {
Class<T> getType();
T getArgument();
Object getSource();
}
}

View File

@@ -1,188 +0,0 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.server.mvc.common;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cloud.gateway.server.mvc.common.ArgumentSupplier.ArgumentSuppliedEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.function.HandlerFunction;
import org.springframework.web.servlet.function.RequestPredicate;
import org.springframework.web.servlet.function.RequestPredicates;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.RouterFunctions;
import org.springframework.web.servlet.function.ServerRequest;
// The RequestPredicate needs to add `visitor.unknown(this)` in accept();
public class ArgumentSupplierBeanPostProcessor implements BeanPostProcessor {
private final ApplicationEventPublisher publisher;
public ArgumentSupplierBeanPostProcessor(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof RouterFunction<?> routerFunction) {
PredicateVisitor predicateVisitor = new PredicateVisitor();
RouterFunctionVisitor routerFunctionVisitor = new RouterFunctionVisitor(predicateVisitor);
routerFunction.accept(routerFunctionVisitor);
if (predicateVisitor.argumentSupplier != null) {
ArgumentSuppliedEvent<?> argumentSuppliedEvent = predicateVisitor.argumentSupplier
.getArgumentSuppliedEvent();
if (predicateVisitor.attributes != null) {
argumentSuppliedEvent = new AttributedArugmentSuppliedEvent<>(argumentSuppliedEvent,
predicateVisitor.attributes);
}
publisher.publishEvent(argumentSuppliedEvent);
}
}
return bean;
}
class RouterFunctionVisitor implements RouterFunctions.Visitor {
private final PredicateVisitor predicateVisitor;
RouterFunctionVisitor(PredicateVisitor predicateVisitor) {
this.predicateVisitor = predicateVisitor;
}
@Override
public void route(RequestPredicate predicate, HandlerFunction<?> handlerFunction) {
predicate.accept(predicateVisitor);
}
@Override
public void attributes(Map<String, Object> attributes) {
this.predicateVisitor.attributesRef.set(attributes);
}
@Override
public void startNested(RequestPredicate predicate) {
}
@Override
public void endNested(RequestPredicate predicate) {
}
@Override
public void resources(Function<ServerRequest, Optional<Resource>> lookupFunction) {
}
@Override
public void unknown(RouterFunction<?> routerFunction) {
}
}
class PredicateVisitor implements RequestPredicates.Visitor {
private final AtomicReference<Map<String, Object>> attributesRef = new AtomicReference<>();
private ArgumentSupplier argumentSupplier;
private Map<String, Object> attributes;
@Override
public void unknown(RequestPredicate predicate) {
if (predicate instanceof ArgumentSupplier argumentSupplier) {
this.argumentSupplier = argumentSupplier;
this.attributes = attributesRef.get();
}
}
@Override
public void method(Set<HttpMethod> methods) {
}
@Override
public void path(String pattern) {
}
@Override
public void pathExtension(String extension) {
}
@Override
public void header(String name, String value) {
}
@Override
public void param(String name, String value) {
}
@Override
public void startAnd() {
}
@Override
public void and() {
}
@Override
public void endAnd() {
}
@Override
public void startOr() {
}
@Override
public void or() {
}
@Override
public void endOr() {
}
@Override
public void startNegate() {
}
@Override
public void endNegate() {
}
}
}

View File

@@ -1,50 +0,0 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.server.mvc.common;
import java.util.Map;
import org.springframework.cloud.gateway.server.mvc.common.ArgumentSupplier.ArgumentSuppliedEvent;
import org.springframework.context.ApplicationEvent;
public class AttributedArugmentSuppliedEvent<T> extends ApplicationEvent implements ArgumentSuppliedEvent<T> {
private final ArgumentSuppliedEvent<T> event;
private final Map<String, Object> attributes;
public AttributedArugmentSuppliedEvent(ArgumentSuppliedEvent<T> event, Map<String, Object> attributes) {
super(event.getSource());
this.event = event;
this.attributes = attributes;
}
@Override
public Class<T> getType() {
return event.getType();
}
@Override
public T getArgument() {
return event.getArgument();
}
public Map<String, Object> getAttributes() {
return attributes;
}
}

View File

@@ -1,44 +0,0 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.server.mvc.common;
import org.springframework.context.ApplicationEvent;
public class DefaultArgumentSuppliedEvent<T> extends ApplicationEvent
implements ArgumentSupplier.ArgumentSuppliedEvent<T> {
private final Class<T> type;
private final T argument;
public DefaultArgumentSuppliedEvent(Object source, Class<T> type, T argument) {
super(source);
this.type = type;
this.argument = argument;
}
@Override
public Class<T> getType() {
return type;
}
@Override
public T getArgument() {
return argument;
}
}

View File

@@ -1,144 +0,0 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.server.mvc.common;
import org.springframework.core.style.ToStringCreator;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.util.Assert;
public class HttpStatusHolder {
private final HttpStatusCode httpStatus;
private final Integer status;
public HttpStatusHolder(HttpStatusCode httpStatus, Integer status) {
Assert.isTrue(httpStatus != null || status != null, "httpStatus and status may not both be null");
this.httpStatus = httpStatus;
this.status = status;
}
public static HttpStatusHolder valueOf(String status) {
HttpStatusCode httpStatus;
try {
httpStatus = HttpStatus.valueOf(status.toUpperCase());
}
catch (IllegalArgumentException e) {
httpStatus = null;
}
final Integer intStatus;
if (httpStatus == null) {
intStatus = Integer.parseInt(status);
}
else {
intStatus = null;
}
return new HttpStatusHolder(httpStatus, intStatus);
}
/**
* Resolves an {@link HttpStatusCode}.
* @return either the httpStatus field if not null, or resolves an HttpStatusCode
* based on the int status.
*/
public HttpStatusCode resolve() {
if (httpStatus != null) {
return httpStatus;
}
return HttpStatusCode.valueOf(status);
}
public HttpStatusCode getHttpStatus() {
return httpStatus;
}
public Integer getStatus() {
return status;
}
/**
* Whether this status code is in the HTTP series
* {@link HttpStatus.Series#INFORMATIONAL}.
* @return <code>true</code> if status code is in the INFORMATIONAL http series
*/
public boolean is1xxInformational() {
return HttpStatus.Series.INFORMATIONAL.equals(getSeries());
}
/**
* Whether this status code is in the HTTP series
* {@link HttpStatus.Series#SUCCESSFUL}.
* @return <code>true</code> if status code is in the SUCCESSFUL http series
*/
public boolean is2xxSuccessful() {
return HttpStatus.Series.SUCCESSFUL.equals(getSeries());
}
/**
* Whether this status code is in the HTTP series
* {@link HttpStatus.Series#REDIRECTION}.
* @return <code>true</code> if status code is in the REDIRECTION http series
*/
public boolean is3xxRedirection() {
return HttpStatus.Series.REDIRECTION.equals(getSeries());
}
/**
* Whether this status code is in the HTTP series
* {@link HttpStatus.Series#CLIENT_ERROR}.
* @return <code>true</code> if status code is in the CLIENT_ERROR http series
*/
public boolean is4xxClientError() {
return HttpStatus.Series.CLIENT_ERROR.equals(getSeries());
}
/**
* Whether this status code is in the HTTP series
* {@link HttpStatus.Series#SERVER_ERROR}.
* @return <code>true</code> if status code is in the SERVER_ERROR http series
*/
public boolean is5xxServerError() {
return HttpStatus.Series.SERVER_ERROR.equals(getSeries());
}
public HttpStatus.Series getSeries() {
if (httpStatus != null) {
return HttpStatus.Series.valueOf(httpStatus.value());
}
if (status != null) {
return HttpStatus.Series.valueOf(status);
}
return null;
}
/**
* Whether this status code is in the HTTP series
* {@link HttpStatus.Series#CLIENT_ERROR} or {@link HttpStatus.Series#SERVER_ERROR}.
* @return <code>true</code> if is either CLIENT_ERROR or SERVER_ERROR
*/
public boolean isError() {
return is4xxClientError() || is5xxServerError();
}
@Override
public String toString() {
return new ToStringCreator(this).append("httpStatus", httpStatus).append("status", status).toString();
}
}

View File

@@ -1,79 +0,0 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.server.mvc.common;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.core.style.ToStringCreator;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
public class KeyValues {
private List<KeyValue> keyValues = new ArrayList<>();
public List<KeyValue> getKeyValues() {
return keyValues;
}
public void setKeyValues(List<KeyValue> keyValues) {
this.keyValues = keyValues;
}
public static KeyValues valueOf(String s) {
String[] tokens = StringUtils.tokenizeToStringArray(s, ",", true, true);
List<KeyValue> parsedKeyValues = Arrays.stream(tokens).map(KeyValue::valueOf).toList();
KeyValues keyValues = new KeyValues();
keyValues.setKeyValues(parsedKeyValues);
return keyValues;
}
public static class KeyValue {
private final String key;
private final String value;
public KeyValue(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return new ToStringCreator(this).append("name", key).append("value", value).toString();
}
public static KeyValue valueOf(String s) {
String[] tokens = StringUtils.tokenizeToStringArray(s, ":", true, true);
Assert.isTrue(tokens.length == 2, () -> "String must be two tokens delimited by colon, but was " + s);
return new KeyValue(tokens[0], tokens[1]);
}
}
}

View File

@@ -1,218 +0,0 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.server.mvc.common;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.function.ServerRequest;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.util.UriComponentsBuilder;
import static org.springframework.web.servlet.function.RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
// TODO: maybe rename to ServerRequestUtils?
public abstract class MvcUtils {
/**
* Cached raw request body key.
*/
public static final String CACHED_REQUEST_BODY_ATTR = qualify("cachedRequestBody");
/**
* CircuitBreaker execution exception attribute name.
*/
public static final String CIRCUITBREAKER_EXECUTION_EXCEPTION_ATTR = qualify("circuitBreakerExecutionException");
/**
* Gateway route ID attribute name.
*/
public static final String GATEWAY_ATTRIBUTES_ATTR = qualify("gatewayAttributes");
/**
* Gateway request URL attribute name.
*/
public static final String GATEWAY_REQUEST_URL_ATTR = qualify("gatewayRequestUrl");
/**
* Gateway route ID attribute name.
*/
public static final String GATEWAY_ROUTE_ID_ATTR = qualify("gatewayRouteId");
/**
* Preserve-Host header attribute name.
*/
public static final String PRESERVE_HOST_HEADER_ATTRIBUTE = qualify("preserveHostHeader");
/**
* Weight attribute name.
*/
public static final String WEIGHT_ATTR = qualify("routeWeight");
private MvcUtils() {
}
private static String qualify(String attr) {
return "GatewayServerMvc." + attr;
}
public static <T> Optional<T> cacheAndReadBody(ServerRequest request, Class<T> toClass) {
ByteArrayInputStream rawBody = cacheBody(request);
return readBody(request, rawBody, toClass);
}
public static ByteArrayInputStream cacheBody(ServerRequest request) {
try {
byte[] bytes = StreamUtils.copyToByteArray(request.servletRequest().getInputStream());
ByteArrayInputStream body = new ByteArrayInputStream(bytes);
putAttribute(request, MvcUtils.CACHED_REQUEST_BODY_ATTR, body);
return body;
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static String expand(ServerRequest request, String template) {
Assert.notNull(request, "request may not be null");
Assert.notNull(template, "template may not be null");
if (template.indexOf('{') == -1) { // short circuit
return template;
}
Map<String, Object> variables = getUriTemplateVariables(request);
return UriComponentsBuilder.fromPath(template).build().expand(variables).getPath();
}
public static List<String> expandMultiple(ServerRequest request, Collection<String> templates) {
return templates.stream().map(value -> MvcUtils.expand(request, value)).toList();
}
public static String[] expandMultiple(ServerRequest request, String... templates) {
List<String> expanded = Arrays.stream(templates).map(value -> MvcUtils.expand(request, value)).toList();
return expanded.toArray(new String[0]);
}
public static ApplicationContext getApplicationContext(ServerRequest request) {
WebApplicationContext webApplicationContext = RequestContextUtils
.findWebApplicationContext(request.servletRequest());
if (webApplicationContext == null) {
throw new IllegalStateException("No Application Context in request attributes");
}
return webApplicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getAttribute(ServerRequest request, String key) {
if (request.attributes().containsKey(key)) {
return (T) request.attributes().get(key);
}
return (T) getGatewayAttributes(request).get(key);
}
@SuppressWarnings("unchecked")
public static Map<String, Object> getGatewayAttributes(ServerRequest request) {
// This map is made in GatewayDelegatingRouterFunction.route() and persists across
// attribute resetting in RequestPredicates
Map<String, Object> attributes = (Map<String, Object>) request.attributes().get(GATEWAY_ATTRIBUTES_ATTR);
return attributes;
}
@SuppressWarnings("unchecked")
public static Map<String, Object> getUriTemplateVariables(ServerRequest request) {
return (Map<String, Object>) request.attributes().getOrDefault(URI_TEMPLATE_VARIABLES_ATTRIBUTE,
new HashMap<>());
}
public static void putAttribute(ServerRequest request, String key, Object value) {
request.attributes().put(key, value);
getGatewayAttributes(request).put(key, value);
}
@SuppressWarnings("unchecked")
public static void putUriTemplateVariables(ServerRequest request, Map<String, String> uriVariables) {
if (request.attributes().containsKey(URI_TEMPLATE_VARIABLES_ATTRIBUTE)) {
Map<String, Object> existingVariables = (Map<String, Object>) request.attributes()
.get(URI_TEMPLATE_VARIABLES_ATTRIBUTE);
HashMap<String, Object> newVariables = new HashMap<>(existingVariables);
newVariables.putAll(uriVariables);
request.attributes().put(URI_TEMPLATE_VARIABLES_ATTRIBUTE, newVariables);
}
else {
request.attributes().put(URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriVariables);
}
}
@SuppressWarnings("unchecked")
public static <T> Optional<T> readBody(ServerRequest request, ByteArrayInputStream body, Class<T> toClass) {
try {
HttpInputMessage inputMessage = new ByteArrayInputMessage(request, body);
List<HttpMessageConverter<?>> httpMessageConverters = request.messageConverters();
for (HttpMessageConverter<?> messageConverter : httpMessageConverters) {
if (messageConverter.canRead(toClass, request.headers().contentType().orElse(null))) {
T convertedValue = (T) messageConverter.read((Class) toClass, inputMessage);
return Optional.of(convertedValue);
}
}
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
return Optional.empty();
}
public static void setRouteId(ServerRequest request, String routeId) {
request.attributes().put(GATEWAY_ROUTE_ID_ATTR, routeId);
request.servletRequest().setAttribute(GATEWAY_ROUTE_ID_ATTR, routeId);
}
public static void setRequestUrl(ServerRequest request, URI url) {
request.attributes().put(GATEWAY_REQUEST_URL_ATTR, url);
request.servletRequest().setAttribute(GATEWAY_REQUEST_URL_ATTR, url);
}
private record ByteArrayInputMessage(ServerRequest request, ByteArrayInputStream body) implements HttpInputMessage {
@Override
public InputStream getBody() {
return body;
}
@Override
public HttpHeaders getHeaders() {
return request.headers().asHttpHeaders();
}
}
}

View File

@@ -1,34 +0,0 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.server.mvc.common;
public abstract class NameUtils {
/**
* Generated name prefix.
*/
public static final String GENERATED_NAME_PREFIX = "_genkey_";
private NameUtils() {
throw new AssertionError("Must not instantiate utility class.");
}
public static String generateName(int i) {
return GENERATED_NAME_PREFIX + i;
}
}

View File

@@ -1,77 +0,0 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.server.mvc.common;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Indexed;
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Shortcut {
/**
* The names and order of arguments for a shortcut. Synonym for {@link #fieldOrder()}.
* Defaults to the names and order of the method on which this is declared.
*/
@AliasFor("fieldOrder")
String[] value() default {};
/**
* The names and order of arguments for a shortcut. Synonym for {@link #value()}.
* Defaults to the names and order of the method on which this is declared.
*/
@AliasFor("value")
String[] fieldOrder() default {};
/**
* Strategy for parsing the shortcut String.
*/
Type type() default Type.DEFAULT;
/**
* Optional property prefix to be appended to fields.
*/
String fieldPrefix() default "";
enum Type {
/**
* Default shortcut type.
*/
DEFAULT,
/**
* List shortcut type.
*/
LIST,
/**
* List is all elements except last which is a boolean flag.
*/
LIST_TAIL_FLAG;
}
}

View File

@@ -1,87 +0,0 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.server.mvc.common;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotEmpty;
import org.springframework.core.style.ToStringCreator;
import org.springframework.validation.annotation.Validated;
@Validated
public class WeightConfig {
/**
* Configuration prefix for {@link WeightConfig}.
*/
public static final String CONFIG_PREFIX = "weight";
@NotEmpty
private String group;
private String routeId;
@Min(0)
private int weight;
private WeightConfig() {
}
public WeightConfig(String routeId, String group, int weight) {
this.routeId = routeId;
this.group = group;
this.weight = weight;
}
public WeightConfig(String routeId) {
this.routeId = routeId;
}
public String getGroup() {
return group;
}
public WeightConfig setGroup(String group) {
this.group = group;
return this;
}
public String getRouteId() {
return routeId;
}
public WeightConfig setRouteId(String routeId) {
this.routeId = routeId;
return this;
}
public int getWeight() {
return weight;
}
public WeightConfig setWeight(int weight) {
this.weight = weight;
return this;
}
@Override
public String toString() {
return new ToStringCreator(this).append("routeId", routeId).append("group", group).append("weight", weight)
.toString();
}
}

View File

@@ -1,105 +0,0 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.gateway.server.mvc.config;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import jakarta.validation.constraints.NotNull;
import org.springframework.cloud.gateway.server.mvc.common.NameUtils;
import org.springframework.validation.annotation.Validated;
import static org.springframework.util.StringUtils.tokenizeToStringArray;
/**
* @author Spencer Gibb
*/
@Validated
public class FilterProperties {
@NotNull
private String name;
private Map<String, String> args = new LinkedHashMap<>();
public FilterProperties() {
}
public FilterProperties(String text) {
int eqIdx = text.indexOf('=');
if (eqIdx <= 0) {
setName(text);
return;
}
setName(text.substring(0, eqIdx));
String[] args = tokenizeToStringArray(text.substring(eqIdx + 1), ",");
for (int i = 0; i < args.length; i++) {
this.args.put(NameUtils.generateName(i), args[i]);
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getArgs() {
return args;
}
public void setArgs(Map<String, String> args) {
this.args = args;
}
public void addArg(String key, String value) {
this.args.put(key, value);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FilterProperties that = (FilterProperties) o;
return Objects.equals(name, that.name) && Objects.equals(args, that.args);
}
@Override
public int hashCode() {
return Objects.hash(name, args);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("FilterDefinition{");
sb.append("name='").append(name).append('\'');
sb.append(", args=").append(args);
sb.append('}');
return sb.toString();
}
}

Some files were not shown because too many files have changed in this diff Show More