1
0
mirror of synced 2026-07-08 20:30:04 +00:00

Compare commits

..

78 Commits

Author SHA1 Message Date
Josh Cummings bdc3feaa6d Release 5.5.2 2021-08-16 11:43:06 -06:00
Josh Cummings 134f8b0c5d Update org.springframework.data to 2021.0.4
Closes gh-10195
2021-08-16 10:02:27 -06:00
Josh Cummings 835ee559d7 Update org.springframework to 5.3.9
Closes gh-10194
2021-08-16 10:02:25 -06:00
Josh Cummings cfe48556d4 Update org.slf4j to 1.7.32
Closes gh-10193
2021-08-16 10:02:22 -06:00
Josh Cummings c7b73d7b3b Update org.jetbrains.kotlinx to 1.5.1
Closes gh-10192
2021-08-16 10:02:20 -06:00
Josh Cummings 618edc2e12 Update org.jetbrains.kotlin to 1.5.21
Closes gh-10191
2021-08-16 10:02:18 -06:00
Josh Cummings f7fef100c0 Update org.eclipse.jetty to 9.4.43.v20210629
Closes gh-10190
2021-08-16 10:02:15 -06:00
Josh Cummings 9be97e76dc Update org.aspectj to 1.9.7
Closes gh-10189
2021-08-16 10:02:13 -06:00
Josh Cummings 603e0a4140 Update io.projectreactor to 2020.0.10
Closes gh-10187
2021-08-16 10:02:08 -06:00
Josh Cummings b081627f52 Update com.nimbusds to 9.9.1
Closes gh-10186
2021-08-16 10:02:05 -06:00
Josh Cummings 10a0bda63f Update jackson-bom to 2.12.4
Closes gh-10183
2021-08-16 10:01:58 -06:00
Josh Cummings 7db5149163 Update logback-classic to 1.2.5
Closes gh-10182
2021-08-16 10:01:56 -06:00
Josh Cummings b206670245 Exclude Kotlin RC and M releases 2021-08-16 09:59:59 -06:00
Fabio Guenci b067aa4653 Preserve Null Claim Values
Prior to this commit ClaimTypeConverter returned the claims with the
original value for all the claims with a null converted value.
The changes allows ClaimTypeConverter to overwrite and return claims
with converted value of null.

Closes gh-10135
2021-08-16 08:22:31 -06:00
Abdul Al-Faraj ba16d91971 Improve OpenSAML Version Check
Closes gh-10077
2021-07-26 10:51:31 -06:00
Steve Riesenberg dfebd6d9d4 Revert "URL encode client credentials"
This reverts commit e6c268add0.

Issue gh-9610 gh-9858
Closes gh-10018
Closes gh-10121
2021-07-20 12:59:44 -05:00
Eleftheria Stein bd703ff4ac Fix release instructions for generating changelog 2021-07-19 13:42:35 +02:00
dmitrilc 7abaefda10 Update oauth2-resourceserver.adoc
fix the name of the parameter, from failure to badCredentials

Replaces AuthenticationFailureEvent

Remove AuthenticationFailureEvent Reference

Closes gh-10062
2021-07-16 11:58:34 -06:00
Marcus Da Coregio 4440020217 Update SAML docs to point to correct api url
Closes gh-9953
2021-07-12 15:47:28 -03:00
Marcus Da Coregio c2b9c0856d Use springFrameworkVersion property in docs links
Closes gh-9987
2021-07-12 15:47:09 -03:00
Marcus Da Coregio a06f47fac3 Add springFrameworkVersion property in gradle
Closes gh-9954
2021-07-12 15:45:01 -03:00
Marcus Da Coregio 8c0103498a Ensure line endings for .bat are not modified
Closes gh-10039
2021-07-12 15:37:29 -03:00
Luke Quinane e269e5cb91 Fix typos
Closes gh-10050
2021-07-08 09:20:50 -03:00
Eleftheria Stein ed8b08fa24 Fix README local Maven install command
Switching from the maven to maven-publish plugin means users should use publishToMavenLocal to install jars into their local Maven cache.

Closes gh-10047
2021-07-07 13:26:28 +02:00
Marcus Da Coregio 208e327629 Update docs links to point to minor version branches
Closes gh-9986
2021-07-01 09:08:53 -03:00
Marcus Da Coregio 51dfae1b91 Add samplesBranch property
Closes gh-10019
2021-07-01 09:08:30 -03:00
Daniel Garnier-Moiroux 2fd94752c9 Fix Saml2WebSsoAuthenticationRequestFilter javadoc
Closes gh-10025
2021-06-30 13:51:29 +02:00
/usr/local/ΕΨΗΕΛΩΝ 61284ce22d Improve AuthenticationManagerBeanDefinitionParser XML parsing
Closes gh-7282
2021-06-28 11:55:05 +02:00
Eleftheria Stein fdd017d935 Apply DefaultLoginPageConfigurer before logout
If they are not applied in this order, then the LogoutConfigurer cannot
set the logoutSuccessUrl, because the DefaultLoginPageGeneratingFilter
does not exist yet.
This impacts users that inject the default HttpSecurity bean.

Closes gh-9973
2021-06-24 10:28:19 +02:00
Josh Cummings bfeb6bd756 Next Development Version 2021-06-21 12:59:19 -06:00
Josh Cummings e41360b4a3 Release 5.5.1 2021-06-21 11:00:32 -06:00
Josh Cummings e2e06539fc Remove commons-codec constraint
Closes gh-9977
2021-06-21 10:41:22 -06:00
Josh Cummings 93f59a228b Update to OpenSAML 4.1.1
Closes gh-9976
2021-06-21 10:41:11 -06:00
Josh Cummings b2bb014492 Update to nimbus-jose-jwt 9.10
Closes gh-9975
2021-06-21 10:41:06 -06:00
Josh Cummings 062910c2c4 Update to oauth2-oidc-sdk 9.9
Closes gh-9974
2021-06-21 10:40:59 -06:00
Josh Cummings 40fdb5a60d Update org.springframework to 5.3.8
Closes gh-9984
2021-06-21 10:40:06 -06:00
Josh Cummings 2fa0da5cde Update org.slf4j to 1.7.31
Closes gh-9983
2021-06-21 10:40:06 -06:00
Josh Cummings c5f4ae5c0a Update org.jetbrains.kotlin to 1.5.10
Closes gh-9982
2021-06-21 10:39:54 -06:00
Josh Cummings c68c1c55ff Update hibernate-entitymanager to 5.4.32.Final
Closes gh-9981
2021-06-21 10:37:30 -06:00
Josh Cummings be2595bc66 Update org.eclipse.jetty to 9.4.42.v20210604
Closes gh-9980
2021-06-21 10:37:28 -06:00
Josh Cummings dddd71439f Update io.rsocket to 1.1.1
Closes gh-9979
2021-06-21 10:37:25 -06:00
Marcus Hert da Coregio 95a1ccb52c Fix Broken Links in Docs
Closes gh-9869
2021-06-21 10:58:44 -03:00
Marcus Hert da Coregio 4060f83261 Add a link checker to docs build
Closes gh-9818
2021-06-21 10:58:44 -03:00
Marcus Da Coregio f9a7ae0a6f Update links to point to migrated samples
Closes gh-9816
2021-06-21 10:58:43 -03:00
Marcus Hert da Coregio 425d008f1d Add messaging to documentation about sample migration
Closes gh-9815
2021-06-21 10:58:43 -03:00
Eleftheria Stein b73104c9d1 Add missing WebFlux CORS Reference
Closes gh-9951
2021-06-18 16:33:01 +02:00
Eleftheria Stein 895ef6cf76 Remove non-existent class from RSocket reference docs
Closes gh-9949
2021-06-18 14:18:31 +02:00
Eleftheria Stein cb4bb463da Disable default logout page when logout disabled
Closes gh-9475
2021-06-17 17:09:34 +02:00
Arnaud Mergey 5fd81eeaf1 fix typo preventing full exception to be displayed in log
closes gh-9901
2021-06-17 08:38:24 -06:00
Steve Riesenberg a332e2a728 Support additional client authentication methods
Closes gh-9780
2021-06-16 16:03:13 -05:00
Steve Riesenberg 9daf058a6e Handle missing authorization endpoint uri
Closes gh-9795
2021-06-16 16:00:53 -05:00
Steve Riesenberg 839cc5e851 Remove validation for unsupported grant types
Closes gh-9828
2021-06-16 15:55:45 -05:00
Christian Frommeyer 0087128be8 Replace StringUtils from oauth2-oidc-sdk
SecurityMockServerConfigurers.java previously used the StringUtils from
the optional oauth2-oidc-sdk dependency. Replacing this with the
StringUtils from the spring framework this should not force adding the
dependency in cases where it is not actually used.

Closes gh-9923
2021-06-16 13:22:49 -06:00
Josh Cummings bfc9c5e18f Use stack-workflow-status Action
Closes gh-9792
2021-06-16 13:21:20 -06:00
Joe Grandja 6fbd038111 Jwt client authentication converter detects new key
Closes gh-9814
2021-06-16 12:58:01 -04:00
Steve Riesenberg 700bda68b7 Store one request by default in WebSessionOAuth2ServerAuthorizationRequestRepository
Related to gh-9649
Closes gh-9857
2021-06-15 11:32:35 -05:00
Marcus Hert da Coregio 53870ab3de Fix Adding Filter Relative to Custom Filter
Closes gh-9787
2021-06-14 15:51:27 -03:00
Josh Cummings fe13b488a1 Anonymous Authentication Argument Resolution Docs
Closes gh-3338
2021-06-08 16:12:38 -06:00
Josh Cummings c38495bfaf Change Getting Started Link
Point to 5.5.x reference guide

Issue gh-6502
2021-06-08 13:56:58 -06:00
Josh Cummings c4b210b580 Fix Getting Started Link
Closes gh-6502
2021-06-08 13:44:06 -06:00
Josh Cummings 1a28b4f849 Format PayloadInterceptorRSocket
Issue gh-9345
2021-06-04 12:47:25 -06:00
Josh Cummings 63cd52d1a6 PayloadInterceptorRSocket retains all payloads
Flux#skip discards its corresponding elements, meaning that they
aren't intended for reuse. When using RSocket's ByteBufPayloads,
this means that the bytes are releaseed back into RSocket's pool.

Since the downstream request may still need the skipped payload,
we should construct the publisher in a different way so as to
avoid the preemptive release.

Deferring Spring JavaFormat to clarify what changed.

Closes gh-9345
2021-06-04 12:47:22 -06:00
Eleftheria Stein 895ae0ac55 Remove hard dependency on Kotlin
Closes gh-9811
2021-06-03 18:34:52 +03:00
Steve Riesenberg e6c268add0 URL encode client credentials
Closes gh-9610
2021-06-03 09:12:18 -05:00
Eleftheria Stein 82d471a592 Fix Resource Server clock skew default value in docs
Closes gh-6611
2021-06-02 12:22:42 +03:00
Josh Cummings f48a006034 Polish postLogoutRedirectUri encoding
Issue gh-9511
2021-05-26 13:51:26 -06:00
Hans Hosea Schaefer b7a0959ede Encode postLogoutRedirectUri query params
Now encodes already encoded queryparameters in postLogoutRedirectUrl
correctly

Closes gh-9511
2021-05-26 13:51:15 -06:00
Marcus Hert da Coregio 29f4193529 Adjust createNewSessionIfAllowed to prevent NPE
Ensure that isTransientAuthentication reuses the same authentication object from saveContext

Closes gh-8947
2021-05-26 13:46:08 -03:00
Steve Riesenberg ab59adbfd2 Handle encoded spaces in the root dn
Fixes an issue where provider URLs passed to the constructor of the
DefaultSpringSecurityContextSource can be URL encoded, resulting in
an invalid base dn. Additionally adds support for list constructor
to support spaces in base dn.

Closes gh-9742
2021-05-26 10:29:49 -05:00
Steve Riesenberg de4b3a4310 Handle custom status codes in error handler
Fixes an issue where custom status codes in the error response cause an
IllegalArgumentException to be thrown when resolving an HttpStatus.

Closes gh-9741
2021-05-25 13:41:04 -05:00
Marcus Hert da Coregio e691906dbc Combine multiple OS builds into one
Closes gh-9790
2021-05-25 14:19:46 -03:00
Marcus Hert da Coregio 5a06fbd984 Update Env Variables in Build Windows Job
Closes gh-9761
2021-05-25 11:07:37 -06:00
Eleftheria Stein 34b55242fe Ensure Kotlin 1.3 compatibility
Closes gh-9765
2021-05-19 10:15:24 +02:00
Rob Winch 26e34368c0 Use GPG_PRIVATE_KEY directly
Closes gh-9776
2021-05-18 17:19:24 -05:00
Rob Winch 0fb7c24cbb core depends on crypto
Issue gh-9767
2021-05-18 17:19:24 -05:00
Josh Cummings 0351883dfa Include all configured branches in CI
Closes gh-9775
2021-05-18 15:59:40 -06:00
Rob Winch 95132d9fe3 Remove spring-security-crypto from spring-core pom
Instead of having api extend included configuration, we should use the
*Classpath configurations.

Closes gh-9767
2021-05-18 15:32:17 -05:00
Rob Winch bf9f1de6e1 Artifactory defaults to publish mavenJava Publication
Closes gh-9772
2021-05-18 15:32:17 -05:00
1912 changed files with 21891 additions and 58896 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
# EditorConfig for Spring Security
# see https://github.com/spring-projects/spring-security/blob/master/CONTRIBUTING.adoc#mind-the-whitespace
# see https://github.com/spring-projects/spring-security/blob/master/CONTRIBUTING.md#mind-the-whitespace
root = true
-1
View File
@@ -14,4 +14,3 @@
*.odg binary
*.otg binary
*.png binary
*.hsx binary
+1 -1
View File
@@ -1,5 +1,5 @@
<!--
For Security Vulnerabilities, please use https://spring.io/security-policy
For Security Vulnerabilities, please use https://pivotal.io/security#reporting
-->
### Summary
-20
View File
@@ -1,20 +0,0 @@
{
"index_name": "security-docs",
"start_urls": [
"https://docs.spring.io/spring-security/reference/"
],
"selectors": {
"lvl0": {
"selector": "//nav[@class='crumbs']//li[@class='crumb'][last()-1]",
"type": "xpath",
"global": true,
"default_value": "Home"
},
"lvl1": ".doc h1",
"lvl2": ".doc h2",
"lvl3": ".doc h3",
"lvl4": ".doc h4",
"text": ".doc p, .doc td.content, .doc th.tableblock"
}
}
-20
View File
@@ -1,20 +0,0 @@
#!/bin/bash
HOST="$1"
HOST_PATH="$2"
SSH_PRIVATE_KEY="$3"
SSH_KNOWN_HOST="$4"
if [ "$#" -ne 4 ]; then
echo -e "not enough arguments USAGE:\n\n$0 \$HOST \$HOST_PATH \$SSH_PRIVATE_KEY \$SSH_KNOWN_HOSTS \n\n" >&2
exit 1
fi
# Use a non-default path to avoid overriding when testing locally
SSH_PRIVATE_KEY_PATH=~/.ssh/github-actions-docs
install -m 600 -D /dev/null "$SSH_PRIVATE_KEY_PATH"
echo "$SSH_PRIVATE_KEY" > "$SSH_PRIVATE_KEY_PATH"
echo "$SSH_KNOWN_HOST" > ~/.ssh/known_hosts
rsync --delete -avze "ssh -i $SSH_PRIVATE_KEY_PATH" docs/build/site/ "$HOST:$HOST_PATH"
rm -f "$SSH_PRIVATE_KEY_PATH"
@@ -1,21 +0,0 @@
#!/bin/bash
###
# Docs
# config.json https://docsearch.algolia.com/docs/config-file
# Run the crawler https://docsearch.algolia.com/docs/run-your-own/#run-the-crawl-from-the-docker-image
### USAGE
if [ "$#" -ne 3 ]; then
echo -e "not enough arguments USAGE:\n\n$0 \$ALGOLIA_APPLICATION_ID \$ALGOLIA_API_KEY \$CONFIG_FILE\n\n" >&2
exit 1
fi
# Script Parameters
APPLICATION_ID=$1
API_KEY=$2
CONFIG_FILE=$3
#### Script
script_dir=$(dirname $0)
docker run -e "APPLICATION_ID=$APPLICATION_ID" -e "API_KEY=$API_KEY" -e "CONFIG=$(cat $CONFIG_FILE | jq -r tostring)" algolia/docsearch-scraper
-5
View File
@@ -1,5 +0,0 @@
REPOSITORY_REF="$1"
TOKEN="$2"
curl -H "Accept: application/vnd.github.everest-preview+json" -H "Authorization: token ${TOKEN}" --request POST --data '{"event_type": "request-build-reference"}' https://api.github.com/repos/${REPOSITORY_REF}/dispatches
echo "Requested Build for $REPOSITORY_REF"
-16
View File
@@ -1,16 +0,0 @@
name: Update Algolia Index
on:
schedule:
- cron: '0 10 * * *' # Once per day at 10am UTC
workflow_dispatch: # Manual trigger
jobs:
update:
name: Update Algolia Index
runs-on: ubuntu-latest
steps:
- name: Checkout Source
uses: actions/checkout@v2
- name: Update Index
run: ${GITHUB_WORKSPACE}/.github/actions/algolia-docsearch-scraper.sh "${{ secrets.ALGOLIA_APPLICATION_ID }}" "${{ secrets.ALGOLIA_WRITE_API_KEY }}" "${GITHUB_WORKSPACE}/.github/actions/algolia-config.json"
-32
View File
@@ -1,32 +0,0 @@
name: Generate Antora Files and Request Build
on:
workflow_dispatch:
push:
branches-ignore:
- 'gh-pages'
tags: '**'
env:
GH_ACTIONS_REPO_TOKEN: ${{ secrets.GH_ACTIONS_REPO_TOKEN }}
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Source
uses: actions/checkout@v2
- name: Generate antora.yml
run: ./gradlew :spring-security-docs:generateAntora
- name: Extract Branch Name
id: extract_branch_name
run: echo "##[set-output name=generated_branch_name;]$(echo ${GITHUB_REPOSITORY}/${GITHUB_REF##*/})"
- name: Push generated antora files to the spring-generated-docs
uses: JamesIves/github-pages-deploy-action@4.1.4
with:
branch: ${{ steps.extract_branch_name.outputs.generated_branch_name }} # The branch the action should deploy to.
folder: "docs/build/generateAntora" # The folder the action should deploy.
repository-name: "spring-io/spring-generated-docs"
token: ${{ secrets.GH_ACTIONS_REPO_TOKEN }}
- name: Dispatch Build Request
run: ${GITHUB_WORKSPACE}/.github/actions/dispatch.sh 'spring-projects/spring-security' "$GH_ACTIONS_REPO_TOKEN"
@@ -13,7 +13,6 @@ env:
GRADLE_ENTERPRISE_SECRET_ACCESS_KEY: ${{ secrets.GRADLE_ENTERPRISE_SECRET_ACCESS_KEY }}
COMMIT_OWNER: ${{ github.event.pusher.name }}
COMMIT_SHA: ${{ github.sha }}
STRUCTURE101_LICENSEID: ${{ secrets.STRUCTURE101_LICENSEID }}
ARTIFACTORY_USERNAME: ${{ secrets.ARTIFACTORY_USERNAME }}
ARTIFACTORY_PASSWORD: ${{ secrets.ARTIFACTORY_PASSWORD }}
RUN_JOBS: ${{ github.repository == 'spring-projects/spring-security' }}
@@ -46,7 +45,7 @@ jobs:
- name: Setup gradle user name
run: |
mkdir -p ~/.gradle
echo 'systemProp.user.name=spring-builds+github' >> ~/.gradle/gradle.properties
echo 'systemProp.user.name=spring-builds' >> ~/.gradle/gradle.properties
- name: Cache Gradle packages
uses: actions/cache@v2
with:
@@ -72,18 +71,21 @@ jobs:
- name: Setup gradle user name
run: |
mkdir -p ~/.gradle
echo 'systemProp.user.name=spring-builds+github' >> ~/.gradle/gradle.properties
echo 'systemProp.user.name=spring-builds' >> ~/.gradle/gradle.properties
- name: Snapshot Tests
run: |
export GRADLE_ENTERPRISE_CACHE_USERNAME="$GRADLE_ENTERPRISE_CACHE_USER"
export GRADLE_ENTERPRISE_CACHE_PASSWORD="$GRADLE_ENTERPRISE_CACHE_PASSWORD"
export GRADLE_ENTERPRISE_ACCESS_KEY="$GRADLE_ENTERPRISE_SECRET_ACCESS_KEY"
./gradlew test --refresh-dependencies -PartifactoryUsername="$ARTIFACTORY_USERNAME" -PartifactoryPassword="$ARTIFACTORY_PASSWORD" -PforceMavenRepositories=snapshot -PspringVersion='5.+' -PreactorVersion='20+' -PspringDataVersion='Neumann-BUILD-SNAPSHOT' -PrsocketVersion=1.1.0-SNAPSHOT -PspringBootVersion=2.4.0-SNAPSHOT -PlocksDisabled --stacktrace
check_samples:
name: Check Samples project
sonar_analysis:
name: Static Code Analysis
needs: [prerequisites]
runs-on: ubuntu-latest
if: needs.prerequisites.outputs.runjobs
env:
SONAR_URL: ${{ secrets.SONAR_URL }}
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
steps:
- uses: actions/checkout@v2
- name: Set up JDK
@@ -93,37 +95,25 @@ jobs:
- name: Setup gradle user name
run: |
mkdir -p ~/.gradle
echo 'systemProp.user.name=spring-builds+github' >> ~/.gradle/gradle.properties
- name: Check samples project
echo 'systemProp.user.name=spring-builds' >> ~/.gradle/gradle.properties
- name: Run Sonar on given (non-main) branch
if: ${{ github.ref != 'refs/heads/main' }}
run: |
export BRANCH=${GITHUB_REF#refs/heads/}
export GRADLE_ENTERPRISE_CACHE_USERNAME="$GRADLE_ENTERPRISE_CACHE_USER"
export GRADLE_ENTERPRISE_CACHE_PASSWORD="$GRADLE_ENTERPRISE_CACHE_PASSWORD"
export GRADLE_ENTERPRISE_ACCESS_KEY="$GRADLE_ENTERPRISE_SECRET_ACCESS_KEY"
./gradlew sonarqube -PartifactoryUsername="$ARTIFACTORY_USERNAME" -PartifactoryPassword="$ARTIFACTORY_PASSWORD" -PexcludeProjects='**/samples/**' -Dsonar.projectKey="spring-security-${GITHUB_REF#refs/heads/}" -Dsonar.projectName="spring-security-${GITHUB_REF#refs/heads/}" -Dsonar.host.url="$SONAR_URL" -Dsonar.login="$SONAR_TOKEN" --stacktrace
- name: Run Sonar on main
if: ${{ github.ref == 'refs/heads/main' }}
run: |
export GRADLE_ENTERPRISE_CACHE_USERNAME="$GRADLE_ENTERPRISE_CACHE_USER"
export GRADLE_ENTERPRISE_CACHE_PASSWORD="$GRADLE_ENTERPRISE_CACHE_PASSWORD"
export GRADLE_ENTERPRISE_ACCESS_KEY="$GRADLE_ENTERPRISE_SECRET_ACCESS_KEY"
./gradlew checkSamples --stacktrace
check_tangles:
name: Check for Package Tangles
needs: [ prerequisites ]
runs-on: ubuntu-latest
if: needs.prerequisites.outputs.runjobs
steps:
- uses: actions/checkout@v2
- name: Set up JDK
uses: actions/setup-java@v1
with:
java-version: '11'
- name: Setup gradle user name
run: |
mkdir -p ~/.gradle
echo 'systemProp.user.name=spring-builds+github' >> ~/.gradle/gradle.properties
- name: Check for package tangles
run: |
export GRADLE_ENTERPRISE_CACHE_USERNAME="$GRADLE_ENTERPRISE_CACHE_USER"
export GRADLE_ENTERPRISE_CACHE_PASSWORD="$GRADLE_ENTERPRISE_CACHE_PASSWORD"
export GRADLE_ENTERPRISE_ACCESS_KEY="$GRADLE_ENTERPRISE_SECRET_ACCESS_KEY"
./gradlew check s101 -Ps101.licenseId="$STRUCTURE101_LICENSEID" --stacktrace
./gradlew sonarqube -PartifactoryUsername="$ARTIFACTORY_USERNAME" -PartifactoryPassword="$ARTIFACTORY_PASSWORD" -PexcludeProjects='**/samples/**' -Dsonar.host.url="$SONAR_URL" -Dsonar.login="$SONAR_TOKEN" --stacktrace
deploy_artifacts:
name: Deploy Artifacts
needs: [build_jdk_11, snapshot_tests, check_samples, check_tangles]
needs: [build_jdk_11, snapshot_tests, sonar_analysis]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
@@ -134,7 +124,7 @@ jobs:
- name: Setup gradle user name
run: |
mkdir -p ~/.gradle
echo 'systemProp.user.name=spring-builds+github' >> ~/.gradle/gradle.properties
echo 'systemProp.user.name=spring-builds' >> ~/.gradle/gradle.properties
- name: Deploy artifacts
run: |
export GRADLE_ENTERPRISE_CACHE_USERNAME="$GRADLE_ENTERPRISE_CACHE_USER"
@@ -150,7 +140,7 @@ jobs:
ARTIFACTORY_PASSWORD: ${{ secrets.ARTIFACTORY_PASSWORD }}
deploy_docs:
name: Deploy Docs
needs: [build_jdk_11, snapshot_tests, check_samples, check_tangles]
needs: [build_jdk_11, snapshot_tests, sonar_analysis]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
@@ -161,7 +151,7 @@ jobs:
- name: Setup gradle user name
run: |
mkdir -p ~/.gradle
echo 'systemProp.user.name=spring-builds+github' >> ~/.gradle/gradle.properties
echo 'systemProp.user.name=spring-builds' >> ~/.gradle/gradle.properties
- name: Deploy Docs
run: |
export GRADLE_ENTERPRISE_CACHE_USERNAME="$GRADLE_ENTERPRISE_CACHE_USER"
@@ -174,7 +164,7 @@ jobs:
DOCS_HOST: ${{ secrets.DOCS_HOST }}
deploy_schema:
name: Deploy Schema
needs: [build_jdk_11, snapshot_tests, check_samples, check_tangles]
needs: [build_jdk_11, snapshot_tests, sonar_analysis]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
@@ -185,7 +175,7 @@ jobs:
- name: Setup gradle user name
run: |
mkdir -p ~/.gradle
echo 'systemProp.user.name=spring-builds+github' >> ~/.gradle/gradle.properties
echo 'systemProp.user.name=spring-builds' >> ~/.gradle/gradle.properties
- name: Deploy Schema
run: |
export GRADLE_ENTERPRISE_CACHE_USERNAME="$GRADLE_ENTERPRISE_CACHE_USER"
@@ -198,7 +188,7 @@ jobs:
DOCS_HOST: ${{ secrets.DOCS_HOST }}
notify_result:
name: Check for failures
needs: [build_jdk_11, snapshot_tests, check_samples, check_tangles, deploy_artifacts, deploy_docs, deploy_schema]
needs: [build_jdk_11, snapshot_tests, sonar_analysis, deploy_artifacts, deploy_docs, deploy_schema]
if: failure()
runs-on: ubuntu-latest
steps:
-33
View File
@@ -1,33 +0,0 @@
name: Build & Deploy Reference
on:
repository_dispatch:
types: request-build-reference
schedule:
- cron: '0 10 * * *' # Once per day at 10am UTC
workflow_dispatch: # Manual trigger
jobs:
deploy:
name: deploy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 11
uses: actions/setup-java@v2
with:
java-version: '11'
distribution: 'adopt'
cache: gradle
- name: Validate Gradle wrapper
uses: gradle/wrapper-validation-action@e6e38bacfdf1a337459f332974bb2327a31aaf4b
- name: Build with Gradle
run: ./gradlew :spring-security-docs:antora --stacktrace
- name: Cleanup Gradle Cache
# Remove some files from the Gradle cache, so they aren't cached by GitHub Actions.
# Restoring these files from a GitHub Actions cache might cause problems for future builds.
run: |
rm -f ~/.gradle/caches/modules-2/modules-2.lock
rm -f ~/.gradle/caches/modules-2/gc.properties
- name: Deploy
run: ${GITHUB_WORKSPACE}/.github/actions/algolia-deploy.sh "${{ secrets.DOCS_USERNAME }}@${{ secrets.DOCS_HOST }}" "/opt/www/domains/spring.io/docs/htdocs/spring-security/reference/" "${{ secrets.DOCS_SSH_KEY }}" "${{ secrets.DOCS_SSH_HOST_KEY }}"
@@ -1,33 +0,0 @@
name: Check Milestone
on:
milestone:
types: [created, opened, edited]
env:
DUE_ON: ${{ github.event.milestone.due_on }}
TITLE: ${{ github.event.milestone.title }}
jobs:
spring-releasetrain-checks:
name: Check DueOn is on a Release Date
runs-on: ubuntu-latest
steps:
- name: Print Milestone Being Checked
run: echo "Validating DueOn '$DUE_ON' for milestone '$TITLE'"
- name: Validate DueOn
if: env.DUE_ON != ''
run: |
export TOOL_VERSION=0.1.1
wget "https://repo.maven.apache.org/maven2/io/spring/releasetrain/spring-release-train-tools/$TOOL_VERSION/spring-release-train-tools-$TOOL_VERSION.jar"
java -cp "spring-release-train-tools-$TOOL_VERSION.jar" io.spring.releasetrain.CheckMilestoneDueOnMain --dueOn "$DUE_ON" --expectedDayOfWeek MONDAY --expectedMondayCount 3
notify_result:
name: Check for failures
needs: [spring-releasetrain-checks]
if: failure()
runs-on: ubuntu-latest
steps:
- name: Send Slack message
uses: Gamesight/slack-workflow-status@v1.0.1
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
slack_webhook_url: ${{ secrets.SLACK_WEBHOOK_URL }}
channel: '#spring-security-ci'
name: 'CI Notifier'
-6
View File
@@ -1,6 +0,0 @@
# Use sdkman to run "sdk env" to initialize with correct JDK version
# Enable auto-env through the sdkman_auto_env config
# See https://sdkman.io/usage#config
# A summary is to add the following to ~/.sdkman/etc/config
# sdkman_auto_env=true
java=11.0.14-tem
+1 -1
View File
@@ -22,7 +22,7 @@ Be sure to read the https://docs.spring.io/spring-security/site/docs/current/ref
Extensive JavaDoc for the Spring Security code is also available in the https://docs.spring.io/spring-security/site/docs/current/api/[Spring Security API Documentation].
== Quick Start
See https://docs.spring.io/spring-security/site/docs/current/reference/html5/#servlet-hello[Hello Spring Security] to get started with a "Hello, World" application.
See https://docs.spring.io/spring-security/site/docs/5.5.x/reference/html5/#servlet-hello[Hello Spring Security] to get started with a "Hello, World" application.
== Building from Source
Spring Security uses a https://gradle.org[Gradle]-based build system.
+1 -11
View File
@@ -78,16 +78,6 @@ Alternatively, you can manually check using https://github.com/spring-projects/s
Update the version number in `gradle.properties` for the release, for example `5.5.0-M1`, `5.5.0-RC1`, `5.5.0`
= Update Antora Version
You will need to update the antora.yml version.
If you are unsure of what the values should be, the following task will instruct you what the expected values are:
[source,bash]
----
./gradlew :spring-security-docs:antoraCheckVersion
----
= Build Locally
Run the build using
@@ -129,7 +119,7 @@ git push origin 5.4.0-RC1
== 7. Update to Next Development Version
* Update `gradle.properties` version to next `+SNAPSHOT+` version, update antora.yml, and then push
* Update `gradle.properties` version to next `+SNAPSHOT+` version and then push
== 8. Update version on project page
+1 -7
View File
@@ -11,15 +11,9 @@ dependencies {
optional 'net.sf.ehcache:ehcache'
testImplementation "org.assertj:assertj-core"
testImplementation "org.junit.jupiter:junit-jupiter-api"
testImplementation "org.junit.jupiter:junit-jupiter-params"
testImplementation "org.junit.jupiter:junit-jupiter-engine"
testImplementation "org.mockito:mockito-core"
testImplementation "org.mockito:mockito-junit-jupiter"
testImplementation 'org.springframework:spring-beans'
testImplementation 'org.springframework:spring-context-support'
testImplementation "org.springframework:spring-test"
testImplementation 'org.springframework:spring-test'
testRuntimeOnly 'org.hsqldb:hsqldb'
}
@@ -37,9 +37,7 @@ import org.springframework.util.Assert;
* {@link PermissionGrantingStrategy} and {@link AclAuthorizationStrategy} instances.
*
* @author Ben Alex
* @deprecated since 5.6. In favor of JCache based implementations
*/
@Deprecated
public class EhCacheBasedAclCache implements AclCache {
private final Ehcache cache;
@@ -16,7 +16,7 @@
package org.springframework.security.acls;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.security.acls.domain.AclFormattingUtils;
import org.springframework.security.acls.model.Permission;
@@ -20,7 +20,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.security.acls.domain.ObjectIdentityImpl;
import org.springframework.security.acls.model.AclService;
@@ -18,7 +18,7 @@ package org.springframework.security.acls;
import java.util.Locale;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.security.acls.model.Acl;
import org.springframework.security.acls.model.AclService;
@@ -21,7 +21,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
@@ -20,7 +20,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
@@ -16,7 +16,7 @@
package org.springframework.security.acls.domain;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.security.acls.model.AccessControlEntry;
import org.springframework.security.acls.model.Acl;
@@ -18,12 +18,12 @@ package org.springframework.security.acls.domain;
import java.util.Arrays;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.acls.model.Acl;
import org.springframework.security.authentication.TestingAuthenticationToken;
@@ -37,7 +37,7 @@ import static org.mockito.BDDMockito.given;
* @author Rob Winch
*
*/
@ExtendWith(MockitoExtension.class)
@RunWith(MockitoJUnitRunner.class)
public class AclAuthorizationStrategyImplTests {
@Mock
@@ -47,7 +47,7 @@ public class AclAuthorizationStrategyImplTests {
AclAuthorizationStrategyImpl strategy;
@BeforeEach
@Before
public void setup() {
this.authority = new SimpleGrantedAuthority("ROLE_AUTH");
TestingAuthenticationToken authentication = new TestingAuthenticationToken("foo", "bar",
@@ -56,7 +56,7 @@ public class AclAuthorizationStrategyImplTests {
SecurityContextHolder.getContext().setAuthentication(authentication);
}
@AfterEach
@After
public void cleanup() {
SecurityContextHolder.clearContext();
}
@@ -22,9 +22,9 @@ import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.acls.model.AccessControlEntry;
import org.springframework.security.acls.model.Acl;
@@ -83,7 +83,7 @@ public class AclImplTests {
private DefaultPermissionFactory permissionFactory;
@BeforeEach
@Before
public void setUp() {
SecurityContextHolder.getContext().setAuthentication(this.auth);
this.authzStrategy = mock(AclAuthorizationStrategy.class);
@@ -93,7 +93,7 @@ public class AclImplTests {
this.permissionFactory = new DefaultPermissionFactory();
}
@AfterEach
@After
public void tearDown() {
SecurityContextHolder.clearContext();
}
@@ -16,9 +16,9 @@
package org.springframework.security.acls.domain;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.acls.model.Acl;
@@ -43,12 +43,12 @@ public class AclImplementationSecurityCheckTests {
private static final String TARGET_CLASS = "org.springframework.security.acls.TargetObject";
@BeforeEach
@Before
public void setUp() {
SecurityContextHolder.clearContext();
}
@AfterEach
@After
public void tearDown() {
SecurityContextHolder.clearContext();
}
@@ -19,9 +19,9 @@ package org.springframework.security.acls.domain;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.acls.model.AccessControlEntry;
import org.springframework.security.acls.model.AuditableAccessControlEntry;
@@ -45,7 +45,7 @@ public class AuditLoggerTests {
private AuditableAccessControlEntry ace;
@BeforeEach
@Before
public void setUp() {
this.logger = new ConsoleAuditLogger();
this.ace = mock(AuditableAccessControlEntry.class);
@@ -53,7 +53,7 @@ public class AuditLoggerTests {
System.setOut(new PrintStream(this.bytes));
}
@AfterEach
@After
public void tearDown() {
System.setOut(this.console);
this.bytes.reset();
@@ -16,7 +16,7 @@
package org.springframework.security.acls.domain;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.security.acls.model.ObjectIdentity;
@@ -16,7 +16,7 @@
package org.springframework.security.acls.domain;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.security.acls.model.ObjectIdentity;
import org.springframework.security.acls.model.ObjectIdentityRetrievalStrategy;
@@ -16,8 +16,8 @@
package org.springframework.security.acls.domain;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.acls.model.Permission;
@@ -32,7 +32,7 @@ public class PermissionTests {
private DefaultPermissionFactory permissionFactory;
@BeforeEach
@Before
public void createPermissionfactory() {
this.permissionFactory = new DefaultPermissionFactory();
}
@@ -26,11 +26,11 @@ import javax.sql.DataSource;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.acls.TargetObject;
@@ -81,19 +81,19 @@ public abstract class AbstractBasicLookupStrategyTests {
public abstract DataSource getDataSource();
@BeforeAll
@BeforeClass
public static void initCacheManaer() {
cacheManager = CacheManager.create();
cacheManager.addCache(new Cache("basiclookuptestcache", 500, false, false, 30, 30));
}
@AfterAll
@AfterClass
public static void shutdownCacheManager() {
cacheManager.removalAll();
cacheManager.shutdown();
}
@BeforeEach
@Before
public void populateDatabase() {
String query = "INSERT INTO acl_sid(ID,PRINCIPAL,SID) VALUES (1,1,'ben');"
+ "INSERT INTO acl_class(ID,CLASS) VALUES (2,'" + TARGET_CLASS + "');"
@@ -107,7 +107,7 @@ public abstract class AbstractBasicLookupStrategyTests {
getJdbcTemplate().execute(query);
}
@BeforeEach
@Before
public void initializeBeans() {
this.strategy = new BasicLookupStrategy(getDataSource(), aclCache(), aclAuthStrategy(),
new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()));
@@ -123,7 +123,7 @@ public abstract class AbstractBasicLookupStrategyTests {
new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER")));
}
@AfterEach
@After
public void emptyDatabase() {
String query = "DELETE FROM acl_entry;" + "DELETE FROM acl_object_identity WHERE ID = 9;"
+ "DELETE FROM acl_object_identity WHERE ID = 8;" + "DELETE FROM acl_object_identity WHERE ID = 7;"
@@ -22,11 +22,11 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.convert.ConversionService;
@@ -39,7 +39,7 @@ import static org.mockito.BDDMockito.given;
*
* @author paulwheeler
*/
@ExtendWith(MockitoExtension.class)
@RunWith(MockitoJUnitRunner.class)
public class AclClassIdUtilsTests {
private static final Long DEFAULT_IDENTIFIER = 999L;
@@ -56,7 +56,7 @@ public class AclClassIdUtilsTests {
private AclClassIdUtils aclClassIdUtils;
@BeforeEach
@Before
public void setUp() {
this.aclClassIdUtils = new AclClassIdUtils();
}
@@ -18,8 +18,8 @@ package org.springframework.security.acls.jdbc;
import javax.sql.DataSource;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.springframework.jdbc.core.JdbcTemplate;
@@ -33,12 +33,12 @@ public class BasicLookupStrategyTests extends AbstractBasicLookupStrategyTests {
private static final BasicLookupStrategyTestsDbHelper DATABASE_HELPER = new BasicLookupStrategyTestsDbHelper();
@BeforeAll
@BeforeClass
public static void createDatabase() throws Exception {
DATABASE_HELPER.createDatabase();
}
@AfterAll
@AfterClass
public static void dropDatabase() {
DATABASE_HELPER.getDataSource().destroy();
}
@@ -21,10 +21,11 @@ import java.util.Map;
import javax.sql.DataSource;
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 junit.framework.Assert;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.core.convert.support.DefaultConversionService;
@@ -36,7 +37,6 @@ import org.springframework.security.acls.domain.ObjectIdentityImpl;
import org.springframework.security.acls.model.Acl;
import org.springframework.security.acls.model.ObjectIdentity;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
@@ -60,18 +60,18 @@ public class BasicLookupStrategyWithAclClassTypeTests extends AbstractBasicLooku
return DATABASE_HELPER.getDataSource();
}
@BeforeAll
@BeforeClass
public static void createDatabase() throws Exception {
DATABASE_HELPER.createDatabase();
}
@AfterAll
@AfterClass
public static void dropDatabase() {
DATABASE_HELPER.getDataSource().destroy();
}
@Override
@BeforeEach
@Before
public void initializeBeans() {
super.initializeBeans();
this.uuidEnabledStrategy = new BasicLookupStrategy(getDataSource(), aclCache(), aclAuthStrategy(),
@@ -81,7 +81,7 @@ public class BasicLookupStrategyWithAclClassTypeTests extends AbstractBasicLooku
this.uuidEnabledStrategy.setConversionService(new DefaultConversionService());
}
@BeforeEach
@Before
public void populateDatabaseForAclClassTypeTests() {
String query = "INSERT INTO acl_class(ID,CLASS,CLASS_ID_TYPE) VALUES (3,'" + TARGET_CLASS_WITH_UUID
+ "', 'java.util.UUID');"
@@ -99,8 +99,8 @@ public class BasicLookupStrategyWithAclClassTypeTests extends AbstractBasicLooku
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, OBJECT_IDENTITY_UUID);
Map<ObjectIdentity, Acl> foundAcls = this.uuidEnabledStrategy.readAclsById(Arrays.asList(oid),
Arrays.asList(BEN_SID));
assertThat(foundAcls).hasSize(1);
assertThat(foundAcls.get(oid)).isNotNull();
Assert.assertEquals(1, foundAcls.size());
Assert.assertNotNull(foundAcls.get(oid));
}
@Test
@@ -108,8 +108,8 @@ public class BasicLookupStrategyWithAclClassTypeTests extends AbstractBasicLooku
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 100L);
Map<ObjectIdentity, Acl> foundAcls = this.uuidEnabledStrategy.readAclsById(Arrays.asList(oid),
Arrays.asList(BEN_SID));
assertThat(foundAcls).hasSize(1);
assertThat(foundAcls.get(oid)).isNotNull();
Assert.assertEquals(1, foundAcls.size());
Assert.assertNotNull(foundAcls.get(oid));
}
@Test
@@ -26,14 +26,14 @@ import java.util.List;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.acls.domain.AclAuthorizationStrategy;
import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl;
@@ -62,7 +62,7 @@ import static org.mockito.Mockito.verify;
*
* @author Andrei Stefan
*/
@ExtendWith(MockitoExtension.class)
@RunWith(MockitoJUnitRunner.class)
public class EhCacheBasedAclCacheTests {
private static final String TARGET_CLASS = "org.springframework.security.acls.TargetObject";
@@ -77,7 +77,7 @@ public class EhCacheBasedAclCacheTests {
private MutableAcl acl;
@BeforeEach
@Before
public void setup() {
this.myCache = new EhCacheBasedAclCache(this.cache,
new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()),
@@ -89,7 +89,7 @@ public class EhCacheBasedAclCacheTests {
this.acl = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger());
}
@AfterEach
@After
public void cleanup() {
SecurityContextHolder.clearContext();
}
@@ -25,12 +25,12 @@ import java.util.UUID;
import javax.sql.DataSource;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.RowMapper;
@@ -56,7 +56,7 @@ import static org.mockito.BDDMockito.given;
*
* @author Nena Raab
*/
@ExtendWith(MockitoExtension.class)
@RunWith(MockitoJUnitRunner.class)
public class JdbcAclServiceTests {
private EmbeddedDatabase embeddedDatabase;
@@ -74,20 +74,23 @@ public class JdbcAclServiceTests {
private JdbcAclService aclService;
@BeforeEach
@Before
public void setUp() {
this.aclService = new JdbcAclService(this.jdbcOperations, this.lookupStrategy);
this.aclServiceIntegration = new JdbcAclService(this.embeddedDatabase, this.lookupStrategy);
}
@Before
public void setUpEmbeddedDatabase() {
// @formatter:off
this.embeddedDatabase = new EmbeddedDatabaseBuilder()
.addScript("createAclSchemaWithAclClassIdType.sql")
.addScript("db/sql/test_data_hierarchy.sql")
.build();
// @formatter:on
this.aclService = new JdbcAclService(this.jdbcOperations, this.lookupStrategy);
this.aclServiceIntegration = new JdbcAclService(this.embeddedDatabase, this.lookupStrategy);
}
@AfterEach
@After
public void tearDownEmbeddedDatabase() {
this.embeddedDatabase.shutdown();
}
@@ -22,8 +22,7 @@ import java.util.Map;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
@@ -50,7 +49,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.transaction.annotation.Transactional;
@@ -67,10 +66,8 @@ import static org.mockito.Mockito.spy;
* @author Ben Alex
* @author Andrei Stefan
*/
@Transactional
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = { "/jdbcMutableAclServiceTests-context.xml" })
public class JdbcMutableAclServiceTests {
public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4SpringContextTests {
private static final String TARGET_CLASS = TargetObject.class.getName();
@@ -18,7 +18,7 @@ package org.springframework.security.acls.jdbc;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.security.acls.TargetObjectWithUUID;
import org.springframework.security.acls.domain.ObjectIdentityImpl;
@@ -18,9 +18,9 @@ package org.springframework.security.acls.jdbc;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
@@ -56,7 +56,7 @@ public class SpringCacheBasedAclCacheTests {
private static CacheManager cacheManager;
@BeforeAll
@BeforeClass
public static void initCacheManaer() {
cacheManager = new ConcurrentMapCacheManager();
// Use disk caching immediately (to test for serialization issue reported in
@@ -64,7 +64,7 @@ public class SpringCacheBasedAclCacheTests {
cacheManager.getCache("springcasebasedacltests");
}
@AfterEach
@After
public void clearContext() {
SecurityContextHolder.clearContext();
}
@@ -18,7 +18,7 @@ package org.springframework.security.acls.sid;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.acls.domain.GrantedAuthoritySid;
@@ -19,7 +19,7 @@ package org.springframework.security.acls.sid;
import java.util.Collection;
import java.util.Collections;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.security.acls.domain.GrantedAuthoritySid;
import org.springframework.security.acls.domain.PrincipalSid;
-7
View File
@@ -10,13 +10,6 @@ dependencies {
api 'org.springframework:spring-core'
testImplementation 'org.springframework:spring-aop'
testImplementation "org.assertj:assertj-core"
testImplementation "org.junit.jupiter:junit-jupiter-api"
testImplementation "org.junit.jupiter:junit-jupiter-params"
testImplementation "org.junit.jupiter:junit-jupiter-engine"
testImplementation "org.mockito:mockito-core"
testImplementation "org.mockito:mockito-junit-jupiter"
testImplementation "org.springframework:spring-test"
testAspect sourceSets.main.output
}
@@ -20,9 +20,9 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@@ -74,7 +74,7 @@ public class AnnotationSecurityAspectTests {
private PrePostSecured prePostSecured = new PrePostSecured();
@BeforeEach
@Before
public final void setUp() {
MockitoAnnotations.initMocks(this);
this.interceptor = new AspectJMethodSecurityInterceptor();
@@ -88,7 +88,7 @@ public class AnnotationSecurityAspectTests {
secAspect.setSecurityInterceptor(this.interceptor);
}
@AfterEach
@After
public void clearContext() {
SecurityContextHolder.clearContext();
}
+12 -25
View File
@@ -1,10 +1,10 @@
buildscript {
dependencies {
classpath "io.spring.javaformat:spring-javaformat-gradle-plugin:$springJavaformatVersion"
classpath 'io.spring.nohttp:nohttp-gradle:0.0.10'
classpath "io.freefair.gradle:aspectj-plugin:6.2.0"
classpath 'io.spring.nohttp:nohttp-gradle:0.0.8'
classpath "io.freefair.gradle:aspectj-plugin:5.3.3.3"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
classpath "com.netflix.nebula:nebula-project-plugin:8.2.0"
classpath "com.netflix.nebula:nebula-project-plugin:8.0.0"
}
repositories {
maven { url 'https://repo.spring.io/plugins-snapshot' }
@@ -14,9 +14,7 @@ buildscript {
apply plugin: 'io.spring.nohttp'
apply plugin: 'locks'
apply plugin: 's101'
apply plugin: 'io.spring.convention.root'
apply plugin: 'io.spring.convention.include-check-remote'
apply plugin: 'org.jetbrains.kotlin.jvm'
apply plugin: 'org.springframework.security.update-dependencies'
apply plugin: 'org.springframework.security.sagan'
@@ -58,6 +56,7 @@ updateDependenciesSettings {
}
addFiles({
return [
project.file("buildSrc/src/main/java/io/spring/gradle/convention/AsciidoctorConventionPlugin.java"),
project.file("buildSrc/src/main/groovy/io/spring/gradle/convention/CheckstylePlugin.groovy")
]
})
@@ -69,12 +68,6 @@ updateDependenciesSettings {
milestoneVersions()
snapshotVersions()
addRule { components ->
components.withModule("commons-codec:commons-codec") { selection ->
ModuleComponentIdentifier candidate = selection.getCandidate();
if (!candidate.getVersion().equals(selection.getCurrentVersion())) {
selection.reject("commons-codec updates break saml tests");
}
}
components.withModule("org.python:jython") { selection ->
ModuleComponentIdentifier candidate = selection.getCandidate();
if (!candidate.getVersion().equals(selection.getCurrentVersion())) {
@@ -94,6 +87,14 @@ updateDependenciesSettings {
if (candidate.getGroup().equals("org.opensaml")) {
selection.reject("org.opensaml maintains two different versions, so it must be updated manually");
}
if (candidate.getGroup().equals("org.jetbrains.kotlin")) {
if (candidate.getVersion().endsWith("-RC")) {
selection.reject("On a maintenance branch, we should not take RC versions")
}
if (candidate.getVersion().contains("-M")) {
selection.reject("On a maintenance branch, we should not take milestone versions")
}
}
}
}
}
@@ -105,8 +106,6 @@ subprojects {
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
options.compilerArgs.add("-parameters")
options.release = 8
}
}
@@ -149,15 +148,3 @@ nohttp {
source.exclude "buildSrc/build/**"
}
tasks.register('checkSamples') {
includeCheckRemote {
repository = 'spring-projects/spring-security-samples'
ref = samplesBranch
}
dependsOn checkRemote
}
s101 {
configurationDirectory = project.file("etc/s101")
}
+13 -28
View File
@@ -9,6 +9,7 @@ plugins {
sourceCompatibility = 1.8
repositories {
jcenter()
gradlePluginPortal()
mavenCentral()
maven { url 'https://repo.spring.io/plugins-release/' }
@@ -27,10 +28,6 @@ sourceSets {
gradlePlugin {
plugins {
checkAntoraVersion {
id = "org.springframework.antora.check-version"
implementationClass = "org.springframework.gradle.antora.CheckAntoraVersionPlugin"
}
trang {
id = "trang"
implementationClass = "trang.TrangPlugin"
@@ -59,10 +56,6 @@ gradlePlugin {
id = "org.springframework.github.changelog"
implementationClass = "org.springframework.gradle.github.changelog.GitHubChangelogPlugin"
}
s101 {
id = "s101"
implementationClass = "s101.S101Plugin"
}
}
}
@@ -76,39 +69,31 @@ dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.thaiopensource:trang:20091111'
implementation 'net.sourceforge.saxon:saxon:9.1.0.8'
implementation 'org.yaml:snakeyaml:1.30'
implementation localGroovy()
implementation 'io.github.gradle-nexus:publish-plugin:1.1.0'
implementation 'io.projectreactor:reactor-core:3.4.15'
implementation 'io.projectreactor:reactor-core:3.4.9'
implementation 'gradle.plugin.org.gretty:gretty:3.0.1'
implementation 'com.apollographql.apollo:apollo-runtime:2.4.5'
implementation 'com.github.ben-manes:gradle-versions-plugin:0.38.0'
implementation 'com.github.spullara.mustache.java:compiler:0.9.4'
implementation 'io.spring.gradle:docbook-reference-plugin:0.3.1'
implementation 'io.spring.gradle:propdeps-plugin:0.0.10.RELEASE'
implementation 'io.spring.javaformat:spring-javaformat-gradle-plugin:0.0.15'
implementation 'io.spring.nohttp:nohttp-gradle:0.0.10'
implementation 'net.sourceforge.htmlunit:htmlunit:2.37.0'
implementation 'io.spring.nohttp:nohttp-gradle:0.0.8'
implementation 'org.aim42:htmlSanityCheck:1.1.6'
implementation 'org.asciidoctor:asciidoctor-gradle-jvm:3.1.0'
implementation 'org.asciidoctor:asciidoctor-gradle-jvm-pdf:3.1.0'
implementation 'org.hidetake:gradle-ssh-plugin:2.10.1'
implementation 'org.jfrog.buildinfo:build-info-extractor-gradle:4.24.20'
implementation 'org.jfrog.buildinfo:build-info-extractor-gradle:4.9.10'
implementation 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.7.1'
testImplementation platform('org.junit:junit-bom:5.8.2')
testImplementation "org.junit.jupiter:junit-jupiter-api"
testImplementation "org.junit.jupiter:junit-jupiter-params"
testImplementation "org.junit.jupiter:junit-jupiter-engine"
testImplementation 'junit:junit:4.12'
testImplementation 'org.apache.commons:commons-io:1.3.2'
testImplementation 'org.assertj:assertj-core:3.13.2'
testImplementation 'org.mockito:mockito-core:3.12.4'
testImplementation 'org.mockito:mockito-junit-jupiter:3.12.4'
testImplementation 'org.mockito:mockito-core:3.0.0'
testImplementation 'org.spockframework:spock-core:1.3-groovy-2.5'
testImplementation "com.squareup.okhttp3:mockwebserver:3.14.9"
}
tasks.named('test', Test).configure {
onlyIf { !project.hasProperty("buildSrc.skipTests") }
useJUnitPlatform()
jvmArgs(
'--add-opens', 'java.base/java.lang=ALL-UNNAMED',
'--add-opens', 'java.base/java.util=ALL-UNNAMED'
)
}
test.onlyIf { !project.hasProperty("buildSrc.skipTests") }
Binary file not shown.
+1 -1
View File
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
@@ -1,104 +0,0 @@
/*
* Copyright 2002-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 io.spring.gradle
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import groovy.transform.TypeCheckingMode
import org.gradle.api.DefaultTask
import org.gradle.api.Task
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
/**
* Checkout a project template from a git repository.
*
* @author Marcus Da Coregio
*/
@CompileStatic
abstract class IncludeRepoTask extends DefaultTask {
private static final String DEFAULT_URI_PREFIX = 'https://github.com/'
/**
* Git repository to use. Will be prefixed with {@link #DEFAULT_URI_PREFIX} if it isn't already
* @return
*/
@Input
abstract Property<String> getRepository();
/**
* Git reference to use.
*/
@Input
abstract Property<String> getRef()
/**
* Directory where the project template should be copied.
*/
@OutputDirectory
final File outputDirectory = project.file("$project.buildDir/$name")
@TaskAction
void checkoutAndCopy() {
outputDirectory.deleteDir()
File checkoutDir = checkout(this, getRemoteUri(), ref.get())
moveToOutputDir(checkoutDir, outputDirectory)
}
private static File cleanTemporaryDir(Task task, File tmpDir) {
if (tmpDir.exists()) {
task.project.delete(tmpDir)
}
return tmpDir
}
static File checkout(Task task, String remoteUri, String ref) {
checkout(task, remoteUri, ref, task.getTemporaryDir())
}
@TypeChecked(TypeCheckingMode.SKIP)
static File checkout(Task task, String remoteUri, String ref, File checkoutDir) {
cleanTemporaryDir(task, checkoutDir)
task.project.exec {
commandLine = ["git", "clone", "--no-checkout", remoteUri, checkoutDir.absolutePath]
errorOutput = System.err
}
task.project.exec {
commandLine = ["git", "checkout", ref]
workingDir = checkoutDir
errorOutput = System.err
}
return checkoutDir
}
private static void moveToOutputDir(File tmpDir, File outputDirectory) {
File baseDir = tmpDir
baseDir.renameTo(outputDirectory)
}
private String getRemoteUri() {
String remoteUri = this.repository.get()
if (remoteUri.startsWith(DEFAULT_URI_PREFIX)) {
return remoteUri
}
return DEFAULT_URI_PREFIX + remoteUri
}
}
@@ -16,17 +16,20 @@
package io.spring.gradle.convention;
import io.spring.gradle.propdeps.PropDepsMavenPlugin;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.plugins.GroovyPlugin;
import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.plugins.MavenPlugin;
import org.gradle.api.plugins.PluginManager;
import org.gradle.internal.impldep.org.apache.maven.Maven;
import org.gradle.plugins.ide.eclipse.EclipseWtpPlugin;
import org.gradle.plugins.ide.idea.IdeaPlugin;
import org.springframework.gradle.CopyPropertiesPlugin
import org.springframework.gradle.propdeps.PropDepsEclipsePlugin
import org.springframework.gradle.propdeps.PropDepsIdeaPlugin
import org.springframework.gradle.propdeps.PropDepsPlugin;
import io.spring.gradle.propdeps.PropDepsEclipsePlugin;
import io.spring.gradle.propdeps.PropDepsIdeaPlugin;
import io.spring.gradle.propdeps.PropDepsPlugin
import org.springframework.gradle.CopyPropertiesPlugin;
/**
* @author Rob Winch
@@ -37,7 +40,7 @@ public abstract class AbstractSpringJavaPlugin implements Plugin<Project> {
public final void apply(Project project) {
PluginManager pluginManager = project.getPluginManager();
pluginManager.apply(JavaPlugin.class);
pluginManager.apply(ManagementConfigurationPlugin.class)
pluginManager.apply(ManagementConfigurationPlugin.class);
if (project.file("src/main/groovy").exists()
|| project.file("src/test/groovy").exists()
|| project.file("src/integration-test/groovy").exists()) {
@@ -49,8 +52,12 @@ public abstract class AbstractSpringJavaPlugin implements Plugin<Project> {
pluginManager.apply(PropDepsPlugin);
pluginManager.apply(PropDepsEclipsePlugin);
pluginManager.apply(PropDepsIdeaPlugin);
project.getPlugins().withType(MavenPlugin) {
pluginManager.apply(PropDepsMavenPlugin);
}
pluginManager.apply("io.spring.convention.tests-configuration");
pluginManager.apply("io.spring.convention.integration-test");
pluginManager.apply("io.spring.convention.dependency-set");
pluginManager.apply("io.spring.convention.javadoc-options");
pluginManager.apply("io.spring.convention.checkstyle");
pluginManager.apply(CopyPropertiesPlugin);
@@ -62,9 +69,6 @@ public abstract class AbstractSpringJavaPlugin implements Plugin<Project> {
manifest.attributes["Implementation-Version"] = project.version
manifest.attributes["Automatic-Module-Name"] = project.name.replace('-', '.')
}
project.test {
useJUnitPlatform()
}
additionalPlugins(project);
}
@@ -36,7 +36,7 @@ class CheckstylePlugin implements Plugin<Project> {
if (checkstyleDir.exists() && checkstyleDir.directory) {
project.getPluginManager().apply('checkstyle')
project.dependencies.add('checkstyle', 'io.spring.javaformat:spring-javaformat-checkstyle:0.0.15')
project.dependencies.add('checkstyle', 'io.spring.nohttp:nohttp-checkstyle:0.0.10')
project.dependencies.add('checkstyle', 'io.spring.nohttp:nohttp-checkstyle:0.0.8')
project.checkstyle {
configDirectory = checkstyleDir
@@ -0,0 +1,126 @@
/*
* Copyright 2002-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.
*/
package io.spring.gradle.convention;
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPlugin
/**
* Adds sets of dependencies to make it easy to add a grouping of dependencies. The
* dependencies added are:
*
* <ul>
* <li>sockDependencies</li>
* <li>seleniumDependencies</li>
* <li>gebDependencies</li>
* <li>powerMockDependencies</li>
* <li>slf4jDependencies</li>
* <li>jstlDependencies</li>
* <li>apachedsDependencies</li>
* </ul>
*
* @author Rob Winch
*/
public class DependencySetPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.ext.spockDependencies = [
project.dependencies.create("org.spockframework:spock-spring") {
exclude group: 'junit', module: 'junit-dep'
},
project.dependencies.create("org.spockframework:spock-core") {
exclude group: 'junit', module: 'junit-dep'
}
]
project.ext.seleniumDependencies = [
"org.seleniumhq.selenium:htmlunit-driver",
"org.seleniumhq.selenium:selenium-support"
]
project.ext.gebDependencies = project.spockDependencies +
project.seleniumDependencies + [
"org.gebish:geb-spock",
'commons-httpclient:commons-httpclient',
"org.codehaus.groovy:groovy",
"org.codehaus.groovy:groovy-all"
]
project.ext.powerMockDependencies = [
"org.powermock:powermock-core",
"org.powermock:powermock-api-support",
"org.powermock:powermock-module-junit4-common",
"org.powermock:powermock-module-junit4",
project.dependencies.create("org.powermock:powermock-api-mockito") {
exclude group: 'org.mockito', module: 'mockito-all'
},
"org.powermock:powermock-reflect"
]
project.ext.powerMock2Dependencies = [
"org.powermock:powermock-core",
"org.powermock:powermock-api-support",
"org.powermock:powermock-module-junit4-common",
"org.powermock:powermock-module-junit4",
project.dependencies.create("org.powermock:powermock-api-mockito2") {
exclude group: 'org.mockito', module: 'mockito-all'
},
"org.powermock:powermock-reflect"
]
project.ext.slf4jDependencies = [
"org.slf4j:slf4j-api",
"org.slf4j:jcl-over-slf4j",
"org.slf4j:log4j-over-slf4j",
"ch.qos.logback:logback-classic"
]
project.ext.springCoreDependency = [
project.dependencies.create("org.springframework:spring-core") {
exclude(group: 'commons-logging', module: 'commons-logging')
}
]
project.ext.testDependencies = [
"junit:junit",
"org.mockito:mockito-core",
"org.springframework:spring-test",
"org.assertj:assertj-core"
]
project.ext.jstlDependencies = [
"javax.servlet.jsp.jstl:javax.servlet.jsp.jstl-api",
"org.apache.taglibs:taglibs-standard-jstlel"
]
project.ext.apachedsDependencies = [
"org.apache.directory.server:apacheds-core",
"org.apache.directory.server:apacheds-core-entry",
"org.apache.directory.server:apacheds-protocol-shared",
"org.apache.directory.server:apacheds-protocol-ldap",
"org.apache.directory.server:apacheds-server-jndi",
'org.apache.directory.shared:shared-ldap'
]
project.plugins.withType(JavaPlugin) {
project.dependencies {
testImplementation project.testDependencies
}
}
}
}
@@ -1,9 +1,12 @@
package io.spring.gradle.convention
import org.aim42.htmlsanitycheck.HtmlSanityCheckPlugin
import org.aim42.htmlsanitycheck.HtmlSanityCheckTask
import org.aim42.htmlsanitycheck.check.BrokenHttpLinksChecker
import org.asciidoctor.gradle.jvm.AbstractAsciidoctorTask
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.plugins.BasePlugin
import org.gradle.api.plugins.PluginManager
import org.gradle.api.tasks.bundling.Zip
@@ -16,18 +19,54 @@ public class DocsPlugin implements Plugin<Project> {
public void apply(Project project) {
PluginManager pluginManager = project.getPluginManager();
pluginManager.apply(BasePlugin);
pluginManager.apply("org.asciidoctor.jvm.convert");
pluginManager.apply("org.asciidoctor.jvm.pdf");
pluginManager.apply(AsciidoctorConventionPlugin);
pluginManager.apply(DeployDocsPlugin);
pluginManager.apply(JavadocApiPlugin);
pluginManager.apply(HtmlSanityCheckPlugin)
String projectName = Utils.getProjectName(project);
String pdfFilename = projectName + "-reference.pdf";
project.tasks.withType(AbstractAsciidoctorTask) { t ->
project.configure(t) {
sources {
include "**/*.adoc"
exclude '_*/**'
}
}
}
project.tasks.withType(HtmlSanityCheckTask) { HtmlSanityCheckTask t ->
project.configure(t) {
t.dependsOn 'asciidoctor'
t.checkerClasses = [BrokenHttpLinksChecker]
t.checkingResultsDir = new File(project.getBuildDir(), "/report/htmlchecks")
t.failOnErrors = false
t.httpConnectionTimeout = 3000
t.sourceDir = new File(project.getBuildDir(), "/docs/asciidoc/")
t.sourceDocuments = project.files(new File(project.getBuildDir(), "/docs/asciidoc/index.html"))
}
}
Task docsZip = project.tasks.create('docsZip', Zip) {
dependsOn 'api'
dependsOn 'api', 'asciidoctor'
group = 'Distribution'
archiveBaseName = project.rootProject.name
archiveClassifier = 'docs'
description = "Builds -${archiveClassifier.get()} archive containing all " +
description = "Builds -${classifier} archive containing all " +
"Docs for deployment at docs.spring.io"
from(project.tasks.asciidoctor.outputs) {
into 'reference/html5'
include '**'
}
from(project.tasks.asciidoctorPdf.outputs) {
into 'reference/pdf'
include '**'
rename "index.pdf", pdfFilename
}
from(project.tasks.api.outputs) {
into 'api'
}
@@ -1,65 +0,0 @@
/*
* Copyright 2002-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 io.spring.gradle.convention
import io.spring.gradle.IncludeRepoTask
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.provider.Property
import org.gradle.api.tasks.GradleBuild
import org.gradle.api.tasks.TaskProvider
/**
* Adds a set of tasks that make easy to clone a remote repository and perform some task
*
* @author Marcus Da Coregio
*/
class IncludeCheckRemotePlugin implements Plugin<Project> {
@Override
void apply(Project project) {
IncludeCheckRemoteExtension extension = project.extensions.create('includeCheckRemote', IncludeCheckRemoteExtension)
TaskProvider<IncludeRepoTask> includeRepoTask = project.tasks.register('includeRepo', IncludeRepoTask) { IncludeRepoTask it ->
it.repository = extension.repository
it.ref = extension.ref
}
project.tasks.register('checkRemote', GradleBuild) {
it.dependsOn 'includeRepo'
it.dir = includeRepoTask.get().outputDirectory
it.tasks = extension.getTasks()
}
}
abstract static class IncludeCheckRemoteExtension {
/**
* Git repository to clone
*/
String repository;
/**
* Git ref to checkout
*/
String ref
/**
* Task to run in the repository
*/
List<String> tasks = ['check']
}
}
@@ -15,6 +15,7 @@
*/
package io.spring.gradle.convention
import io.spring.gradle.propdeps.PropDepsPlugin
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
@@ -23,7 +24,6 @@ import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.tasks.testing.Test
import org.gradle.plugins.ide.eclipse.EclipsePlugin
import org.gradle.plugins.ide.idea.IdeaPlugin
import org.springframework.gradle.propdeps.PropDepsPlugin
/**
*
@@ -54,7 +54,7 @@ public class IntegrationTestPlugin implements Plugin<Project> {
}
project.configurations {
integrationTestCompile {
extendsFrom testImplementation
extendsFrom testCompile, testImplementation
}
integrationTestRuntime {
extendsFrom integrationTestCompile, testRuntime, testRuntimeOnly
@@ -77,7 +77,6 @@ public class IntegrationTestPlugin implements Plugin<Project> {
testClassesDirs = project.sourceSets.integrationTest.output.classesDirs
classpath = project.sourceSets.integrationTest.runtimeClasspath
shouldRunAfter project.tasks.test
useJUnitPlatform()
}
project.tasks.check.dependsOn integrationTestTask
@@ -1,21 +1,7 @@
/*
* Copyright 2002-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 io.spring.gradle.convention;
import io.spring.gradle.propdeps.PropDepsPlugin;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.ConfigurationContainer;
@@ -26,8 +12,6 @@ import org.gradle.api.publish.PublishingExtension;
import org.gradle.api.publish.maven.MavenPublication;
import org.gradle.api.publish.maven.plugins.MavenPublishPlugin;
import org.springframework.gradle.propdeps.PropDepsPlugin;
/**
* Creates a Management configuration that is appropriate for adding a platform to that is not exposed externally. If
* the JavaPlugin is applied, the compileClasspath, runtimeClasspath, testCompileClasspath, and testRuntimeClasspath
@@ -71,4 +55,5 @@ public class ManagementConfigurationPlugin implements Plugin<Project> {
}));
});
}
}
}
@@ -0,0 +1,26 @@
package io.spring.gradle.convention
import org.gradle.api.Plugin
import org.gradle.api.Project
public class OssrhPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
if(project.hasProperty('ossrhUsername')) {
project.uploadArchives {
repositories {
mavenDeployer {
repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
authentication(userName: project.ossrhUsername, password: project.ossrhPassword)
}
snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") {
authentication(userName: project.ossrhUsername, password: project.ossrhPassword)
}
}
}
}
}
}
}
@@ -35,6 +35,11 @@ class RepositoryConventionPlugin implements Plugin<Project> {
mavenLocal()
}
mavenCentral()
jcenter() {
content {
includeGroup "org.gretty"
}
}
if (isSnapshot) {
maven {
name = 'artifactory-snapshot'
@@ -21,7 +21,6 @@ import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.BasePlugin
import org.gradle.api.plugins.PluginManager
import org.springframework.gradle.classpath.CheckProhibitedDependenciesLifecyclePlugin
import org.springframework.gradle.maven.SpringNexusPublishPlugin
class RootProjectPlugin implements Plugin<Project> {
@@ -33,7 +32,6 @@ class RootProjectPlugin implements Plugin<Project> {
pluginManager.apply(SchemaPlugin)
pluginManager.apply(NoHttpPlugin)
pluginManager.apply(SpringNexusPublishPlugin)
pluginManager.apply(CheckProhibitedDependenciesLifecyclePlugin)
pluginManager.apply("org.sonarqube")
project.repositories.mavenCentral()
@@ -20,7 +20,6 @@ import org.gradle.api.Project
import org.gradle.api.plugins.JavaLibraryPlugin;
import org.gradle.api.plugins.MavenPlugin;
import org.gradle.api.plugins.PluginManager
import org.springframework.gradle.classpath.CheckClasspathForProhibitedDependenciesPlugin;
import org.springframework.gradle.maven.SpringMavenPlugin;
/**
@@ -33,13 +32,15 @@ class SpringModulePlugin extends AbstractSpringJavaPlugin {
PluginManager pluginManager = project.getPluginManager();
pluginManager.apply(JavaLibraryPlugin.class)
pluginManager.apply(SpringMavenPlugin.class);
pluginManager.apply(CheckClasspathForProhibitedDependenciesPlugin.class);
pluginManager.apply("io.spring.convention.jacoco");
def deployArtifacts = project.task("deployArtifacts")
deployArtifacts.group = 'Deploy tasks'
deployArtifacts.description = "Deploys the artifacts to either Artifactory or Maven Central"
if (!Utils.isRelease(project)) {
if (Utils.isRelease(project)) {
deployArtifacts.dependsOn project.tasks.uploadArchives
}
else {
deployArtifacts.dependsOn project.tasks.artifactoryPublish
}
}
@@ -0,0 +1,208 @@
/*
* Copyright 2019-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 io.spring.gradle.convention;
import org.asciidoctor.gradle.base.AsciidoctorAttributeProvider;
import org.asciidoctor.gradle.jvm.AbstractAsciidoctorTask;
import org.asciidoctor.gradle.jvm.AsciidoctorJExtension;
import org.asciidoctor.gradle.jvm.AsciidoctorJPlugin;
import org.asciidoctor.gradle.jvm.AsciidoctorTask;
import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.DependencySet;
import org.gradle.api.artifacts.dsl.RepositoryHandler;
import org.gradle.api.file.CopySpec;
import org.gradle.api.file.FileTree;
import org.gradle.api.tasks.Sync;
import java.io.File;
import java.net.URI;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
/**
* Conventions that are applied in the presence of the {@link AsciidoctorJPlugin}. When
* the plugin is applied:
*
* <ul>
* <li>All warnings are made fatal.
* <li>A task is created to resolve and unzip our documentation resources (CSS and
* Javascript).
* <li>For each {@link AsciidoctorTask} (HTML only):
* <ul>
* <li>A configuration named asciidoctorExtensions is ued to add the
* <a href="https://github.com/spring-io/spring-asciidoctor-extensions#block-switch">block
* switch</a> extension
* <li>{@code doctype} {@link AsciidoctorTask#options(Map) option} is configured.
* <li>{@link AsciidoctorTask#attributes(Map) Attributes} are configured for syntax
* highlighting, CSS styling, docinfo, etc.
* </ul>
* <li>For each {@link AbstractAsciidoctorTask} (HTML and PDF):
* <ul>
* <li>{@link AsciidoctorTask#attributes(Map) Attributes} are configured to enable
* warnings for references to missing attributes, the year is added as @{code today-year},
* etc
* <li>{@link AbstractAsciidoctorTask#baseDirFollowsSourceDir() baseDirFollowsSourceDir()}
* is enabled.
* </ul>
* </ul>
*
* @author Andy Wilkinson
* @author Rob Winch
*/
public class AsciidoctorConventionPlugin implements Plugin<Project> {
public void apply(Project project) {
project.getPlugins().withType(AsciidoctorJPlugin.class, (asciidoctorPlugin) -> {
createDefaultAsciidoctorRepository(project);
makeAllWarningsFatal(project);
Sync unzipResources = createUnzipDocumentationResourcesTask(project);
project.getTasks().withType(AbstractAsciidoctorTask.class, (asciidoctorTask) -> {
asciidoctorTask.dependsOn(unzipResources);
configureExtensions(project, asciidoctorTask);
configureCommonAttributes(project, asciidoctorTask);
configureOptions(asciidoctorTask);
asciidoctorTask.baseDirFollowsSourceDir();
asciidoctorTask.useIntermediateWorkDir();
asciidoctorTask.resources(new Action<CopySpec>() {
@Override
public void execute(CopySpec resourcesSpec) {
resourcesSpec.from(unzipResources);
resourcesSpec.from(asciidoctorTask.getSourceDir(), new Action<CopySpec>() {
@Override
public void execute(CopySpec resourcesSrcDirSpec) {
// https://github.com/asciidoctor/asciidoctor-gradle-plugin/issues/523
// For now copy the entire sourceDir over so that include files are
// available in the intermediateWorkDir
// resourcesSrcDirSpec.include("images/**");
}
});
}
});
if (asciidoctorTask instanceof AsciidoctorTask) {
configureHtmlOnlyAttributes(project, asciidoctorTask);
}
});
});
}
private void createDefaultAsciidoctorRepository(Project project) {
project.getGradle().afterProject(new Action<Project>() {
@Override
public void execute(Project project) {
RepositoryHandler repositories = project.getRepositories();
if (repositories.isEmpty()) {
repositories.mavenCentral();
repositories.maven(repo -> {
repo.setUrl(URI.create("https://repo.spring.io/release"));
});
}
}
});
}
private void makeAllWarningsFatal(Project project) {
project.getExtensions().getByType(AsciidoctorJExtension.class).fatalWarnings(".*");
}
private void configureExtensions(Project project, AbstractAsciidoctorTask asciidoctorTask) {
Configuration extensionsConfiguration = project.getConfigurations().maybeCreate("asciidoctorExtensions");
extensionsConfiguration.defaultDependencies(new Action<DependencySet>() {
@Override
public void execute(DependencySet dependencies) {
dependencies.add(project.getDependencies().create("io.spring.asciidoctor:spring-asciidoctor-extensions-block-switch:0.4.2.RELEASE"));
}
});
asciidoctorTask.configurations(extensionsConfiguration);
}
private Sync createUnzipDocumentationResourcesTask(Project project) {
Configuration documentationResources = project.getConfigurations().maybeCreate("documentationResources");
documentationResources.getDependencies()
.add(project.getDependencies().create("io.spring.docresources:spring-doc-resources:0.2.5"));
Sync unzipResources = project.getTasks().create("unzipDocumentationResources",
Sync.class, new Action<Sync>() {
@Override
public void execute(Sync sync) {
sync.dependsOn(documentationResources);
sync.from(new Callable<List<FileTree>>() {
@Override
public List<FileTree> call() throws Exception {
List<FileTree> result = new ArrayList<>();
documentationResources.getAsFileTree().forEach(new Consumer<File>() {
@Override
public void accept(File file) {
result.add(project.zipTree(file));
}
});
return result;
}
});
File destination = new File(project.getBuildDir(), "docs/resources");
sync.into(project.relativePath(destination));
}
});
return unzipResources;
}
private void configureOptions(AbstractAsciidoctorTask asciidoctorTask) {
asciidoctorTask.options(Collections.singletonMap("doctype", "book"));
}
private void configureHtmlOnlyAttributes(Project project, AbstractAsciidoctorTask asciidoctorTask) {
Map<String, Object> attributes = new HashMap<>();
attributes.put("source-highlighter", "highlight.js");
attributes.put("highlightjsdir", "js/highlight");
attributes.put("highlightjs-theme", "github");
attributes.put("linkcss", true);
attributes.put("icons", "font");
attributes.put("stylesheet", "css/spring.css");
asciidoctorTask.getAttributeProviders().add(new AsciidoctorAttributeProvider() {
@Override
public Map<String, Object> getAttributes() {
Object version = project.getVersion();
Map<String, Object> attrs = new HashMap<>();
if (version != null && version.toString() != Project.DEFAULT_VERSION) {
attrs.put("revnumber", version);
}
return attrs;
}
});
asciidoctorTask.attributes(attributes);
}
private void configureCommonAttributes(Project project, AbstractAsciidoctorTask asciidoctorTask) {
Map<String, Object> attributes = new HashMap<>();
attributes.put("attribute-missing", "warn");
attributes.put("icons", "font");
attributes.put("idprefix", "");
attributes.put("idseparator", "-");
attributes.put("docinfo", "shared");
attributes.put("sectanchors", "");
attributes.put("sectnums", "");
attributes.put("today-year", LocalDate.now().getYear());
asciidoctorTask.attributes(attributes);
}
}
@@ -1,85 +0,0 @@
package org.springframework.gradle.antora;
import org.gradle.api.Action;
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.tasks.TaskProvider;
import org.gradle.language.base.plugins.LifecycleBasePlugin;
public class CheckAntoraVersionPlugin implements Plugin<Project> {
public static final String ANTORA_CHECK_VERSION_TASK_NAME = "antoraCheckVersion";
@Override
public void apply(Project project) {
TaskProvider<CheckAntoraVersionTask> antoraCheckVersion = project.getTasks().register(ANTORA_CHECK_VERSION_TASK_NAME, CheckAntoraVersionTask.class, new Action<CheckAntoraVersionTask>() {
@Override
public void execute(CheckAntoraVersionTask antoraCheckVersion) {
antoraCheckVersion.setGroup(LifecycleBasePlugin.VERIFICATION_GROUP);
antoraCheckVersion.setDescription("Checks the antora.yml version properties match the Gradle version");
antoraCheckVersion.getAntoraVersion().convention(project.provider(() -> getDefaultAntoraVersion(project)));
antoraCheckVersion.getAntoraPrerelease().convention(project.provider(() -> getDefaultAntoraPrerelease(project)));
antoraCheckVersion.getAntoraDisplayVersion().convention(project.provider(() -> getDefaultAntoraDisplayVersion(project)));
antoraCheckVersion.getAntoraYmlFile().fileProvider(project.provider(() -> project.file("antora.yml")));
}
});
project.getPlugins().withType(LifecycleBasePlugin.class, new Action<LifecycleBasePlugin>() {
@Override
public void execute(LifecycleBasePlugin lifecycleBasePlugin) {
project.getTasks().named(LifecycleBasePlugin.CHECK_TASK_NAME).configure(new Action<Task>() {
@Override
public void execute(Task check) {
check.dependsOn(antoraCheckVersion);
}
});
}
});
}
private static String getDefaultAntoraVersion(Project project) {
String projectVersion = getProjectVersion(project);
int preReleaseIndex = getSnapshotIndex(projectVersion);
return isSnapshot(projectVersion) ? projectVersion.substring(0, preReleaseIndex) : projectVersion;
}
private static String getDefaultAntoraPrerelease(Project project) {
String projectVersion = getProjectVersion(project);
if (isSnapshot(projectVersion)) {
int preReleaseIndex = getSnapshotIndex(projectVersion);
return projectVersion.substring(preReleaseIndex);
}
if (isPreRelease(projectVersion)) {
return Boolean.TRUE.toString();
}
return null;
}
private static String getDefaultAntoraDisplayVersion(Project project) {
String projectVersion = getProjectVersion(project);
if (!isSnapshot(projectVersion) && isPreRelease(projectVersion)) {
return getDefaultAntoraVersion(project);
}
return null;
}
private static String getProjectVersion(Project project) {
Object projectVersion = project.getVersion();
if (projectVersion == null) {
throw new GradleException("Please define antoraVersion and antoraPrerelease on " + ANTORA_CHECK_VERSION_TASK_NAME + " or provide a Project version so they can be defaulted");
}
return String.valueOf(projectVersion);
}
private static boolean isSnapshot(String projectVersion) {
return getSnapshotIndex(projectVersion) >= 0;
}
private static int getSnapshotIndex(String projectVersion) {
return projectVersion.lastIndexOf("-SNAPSHOT");
}
private static boolean isPreRelease(String projectVersion) {
return projectVersion.lastIndexOf("-") >= 0;
}
}
@@ -1,96 +0,0 @@
package org.springframework.gradle.antora;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.Optional;
import org.gradle.api.tasks.TaskAction;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.representer.Representer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public abstract class CheckAntoraVersionTask extends DefaultTask {
@TaskAction
public void check() throws FileNotFoundException {
File antoraYmlFile = getAntoraYmlFile().getAsFile().get();
String expectedAntoraVersion = getAntoraVersion().get();
String expectedAntoraPrerelease = getAntoraPrerelease().getOrElse(null);
String expectedAntoraDisplayVersion = getAntoraDisplayVersion().getOrElse(null);
Representer representer = new Representer();
representer.getPropertyUtils().setSkipMissingProperties(true);
Yaml yaml = new Yaml(new Constructor(AntoraYml.class), representer);
AntoraYml antoraYml = yaml.load(new FileInputStream(antoraYmlFile));
String actualAntoraPrerelease = antoraYml.getPrerelease();
boolean preReleaseMatches = antoraYml.getPrerelease() == null && expectedAntoraPrerelease == null ||
(actualAntoraPrerelease != null && actualAntoraPrerelease.equals(expectedAntoraPrerelease));
String actualAntoraDisplayVersion = antoraYml.getDisplay_version();
boolean displayVersionMatches = antoraYml.getDisplay_version() == null && expectedAntoraDisplayVersion == null ||
(actualAntoraDisplayVersion != null && actualAntoraDisplayVersion.equals(expectedAntoraDisplayVersion));
String actualAntoraVersion = antoraYml.getVersion();
if (!preReleaseMatches ||
!displayVersionMatches ||
!expectedAntoraVersion.equals(actualAntoraVersion)) {
throw new GradleException("The Gradle version of '" + getProject().getVersion() + "' should have version: '"
+ expectedAntoraVersion + "' prerelease: '" + expectedAntoraPrerelease + "' display_version: '"
+ expectedAntoraDisplayVersion + "' defined in " + antoraYmlFile + " but got version: '"
+ actualAntoraVersion + "' prerelease: '" + actualAntoraPrerelease + "' display_version: '" + actualAntoraDisplayVersion + "'");
}
}
@InputFile
public abstract RegularFileProperty getAntoraYmlFile();
@Input
public abstract Property<String> getAntoraVersion();
@Input
@Optional
public abstract Property<String> getAntoraPrerelease();
@Input
@Optional
public abstract Property<String> getAntoraDisplayVersion();
public static class AntoraYml {
private String version;
private String prerelease;
private String display_version;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getPrerelease() {
return prerelease;
}
public void setPrerelease(String prerelease) {
this.prerelease = prerelease;
}
public String getDisplay_version() {
return display_version;
}
public void setDisplay_version(String display_version) {
this.display_version = display_version;
}
}
}
@@ -1,99 +0,0 @@
/*
* Copyright 2012-2022 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.gradle.classpath;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.Task;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ModuleVersionIdentifier;
import org.gradle.api.artifacts.ResolvedConfiguration;
import org.gradle.api.file.FileCollection;
import org.gradle.api.tasks.Classpath;
import org.gradle.api.tasks.TaskAction;
import java.io.IOException;
import java.util.TreeSet;
import java.util.stream.Collectors;
/**
* A {@link Task} for checking the classpath for prohibited dependencies.
*
* @author Andy Wilkinson
*/
public class CheckClasspathForProhibitedDependencies extends DefaultTask {
private Configuration classpath;
public CheckClasspathForProhibitedDependencies() {
getOutputs().upToDateWhen((task) -> true);
}
public void setClasspath(Configuration classpath) {
this.classpath = classpath;
}
@Classpath
public FileCollection getClasspath() {
return this.classpath;
}
@TaskAction
public void checkForProhibitedDependencies() throws IOException {
ResolvedConfiguration resolvedConfiguration = this.classpath.getResolvedConfiguration();
TreeSet<String> prohibited = resolvedConfiguration.getResolvedArtifacts().stream()
.map((artifact) -> artifact.getModuleVersion().getId()).filter(this::prohibited)
.map((id) -> id.getGroup() + ":" + id.getName()).collect(Collectors.toCollection(TreeSet::new));
if (!prohibited.isEmpty()) {
StringBuilder message = new StringBuilder(String.format("Found prohibited dependencies in '%s':%n", this.classpath.getName()));
for (String dependency : prohibited) {
message.append(String.format(" %s%n", dependency));
}
throw new GradleException(message.toString());
}
}
private boolean prohibited(ModuleVersionIdentifier id) {
String group = id.getGroup();
if (group.equals("javax.batch")) {
return false;
}
if (group.equals("javax.cache")) {
return false;
}
if (group.equals("javax.money")) {
return false;
}
if (group.startsWith("javax")) {
return true;
}
if (group.equals("commons-logging")) {
return true;
}
if (group.equals("org.slf4j") && id.getName().equals("jcl-over-slf4j")) {
return true;
}
if (group.startsWith("org.jboss.spec")) {
return true;
}
if (group.equals("org.apache.geronimo.specs")) {
return true;
}
return false;
}
}
@@ -1,67 +0,0 @@
/*
* Copyright 2012-2022 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.gradle.classpath;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.plugins.JavaBasePlugin;
import org.gradle.api.tasks.SourceSetContainer;
import org.gradle.api.tasks.TaskProvider;
import org.gradle.language.base.plugins.LifecycleBasePlugin;
import org.springframework.util.StringUtils;
/**
* @author Andy Wilkinson
* @author Rob Winch
*/
public class CheckClasspathForProhibitedDependenciesPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.getPlugins().apply(CheckProhibitedDependenciesLifecyclePlugin.class);
project.getPlugins().withType(JavaBasePlugin.class, javaBasePlugin -> {
configureProhibitedDependencyChecks(project);
});
}
private void configureProhibitedDependencyChecks(Project project) {
SourceSetContainer sourceSets = project.getExtensions().getByType(SourceSetContainer.class);
sourceSets.all((sourceSet) -> createProhibitedDependenciesChecks(project,
sourceSet.getCompileClasspathConfigurationName(), sourceSet.getRuntimeClasspathConfigurationName()));
}
private void createProhibitedDependenciesChecks(Project project, String... configurationNames) {
ConfigurationContainer configurations = project.getConfigurations();
for (String configurationName : configurationNames) {
Configuration configuration = configurations.getByName(configurationName);
createProhibitedDependenciesCheck(configuration, project);
}
}
private void createProhibitedDependenciesCheck(Configuration classpath, Project project) {
String taskName = "check" + StringUtils.capitalize(classpath.getName() + "ForProhibitedDependencies");
TaskProvider<CheckClasspathForProhibitedDependencies> checkClasspathTask = project.getTasks().register(taskName,
CheckClasspathForProhibitedDependencies.class, checkClasspath -> {
checkClasspath.setGroup(LifecycleBasePlugin.CHECK_TASK_NAME);
checkClasspath.setDescription("Checks " + classpath.getName() + " for prohibited dependencies");
checkClasspath.setClasspath(classpath);
});
project.getTasks().named(CheckProhibitedDependenciesLifecyclePlugin.CHECK_PROHIBITED_DEPENDENCIES_TASK_NAME, checkProhibitedTask -> checkProhibitedTask.dependsOn(checkClasspathTask));
}
}
@@ -1,41 +0,0 @@
/*
* Copyright 2012-2022 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.gradle.classpath;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.plugins.JavaBasePlugin;
import org.gradle.api.tasks.TaskProvider;
/**
* @author Rob Winch
*/
public class CheckProhibitedDependenciesLifecyclePlugin implements Plugin<Project> {
public static final String CHECK_PROHIBITED_DEPENDENCIES_TASK_NAME = "checkForProhibitedDependencies";
@Override
public void apply(Project project) {
TaskProvider<Task> checkProhibitedDependencies = project.getTasks().register(CheckProhibitedDependenciesLifecyclePlugin.CHECK_PROHIBITED_DEPENDENCIES_TASK_NAME, task -> {
task.setGroup(JavaBasePlugin.VERIFICATION_GROUP);
task.setDescription("Checks both the compile/runtime classpath of every SourceSet for prohibited dependencies");
});
project.getTasks().named(JavaBasePlugin.CHECK_TASK_NAME, checkTask -> {
checkTask.dependsOn(checkProhibitedDependencies);
});
}
}
@@ -1,43 +0,0 @@
/*
* Copyright 2002-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.gradle.propdeps
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.plugins.ide.eclipse.EclipsePlugin
/**
* Plugin to allow optional and provided dependency configurations to work with the
* standard gradle 'eclipse' plugin
*
* @author Phillip Webb
*/
class PropDepsEclipsePlugin implements Plugin<Project> {
public void apply(Project project) {
project.plugins.apply(PropDepsPlugin)
project.plugins.apply(EclipsePlugin)
project.eclipse {
classpath {
plusConfigurations += [project.configurations.provided, project.configurations.optional]
}
}
}
}
@@ -1,46 +0,0 @@
/*
* Copyright 2002-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.gradle.propdeps
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.plugins.ide.idea.IdeaPlugin
/**
* Plugin to allow optional and provided dependency configurations to work with the
* standard gradle 'idea' plugin
*
* @author Phillip Webb
* @author Brian Clozel
* @link https://youtrack.jetbrains.com/issue/IDEA-107046
* @link https://youtrack.jetbrains.com/issue/IDEA-117668
*/
class PropDepsIdeaPlugin implements Plugin<Project> {
public void apply(Project project) {
project.plugins.apply(PropDepsPlugin)
project.plugins.apply(IdeaPlugin)
project.idea.module {
// IDEA internally deals with 4 scopes : COMPILE, TEST, PROVIDED, RUNTIME
// but only PROVIDED seems to be picked up
scopes.PROVIDED.plus += [project.configurations.provided]
scopes.PROVIDED.plus += [project.configurations.optional]
}
}
}
@@ -1,76 +0,0 @@
/*
* Copyright 2002-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.gradle.propdeps
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
import org.gradle.api.plugins.JavaLibraryPlugin
import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.tasks.javadoc.Javadoc
/**
* Plugin to allow 'optional' and 'provided' dependency configurations
*
* As stated in the maven documentation, provided scope "is only available on the compilation and test classpath,
* and is not transitive".
*
* This plugin creates two new configurations, and each one:
* <ul>
* <li>is a parent of the compile configuration</li>
* <li>is not visible, not transitive</li>
* <li>all dependencies are excluded from the default configuration</li>
* </ul>
*
* @author Phillip Webb
* @author Brian Clozel
* @author Rob Winch
*
* @see <a href="https://www.gradle.org/docs/current/userguide/java_plugin.html#N121CF">Maven documentation</a>
* @see <a href="https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope">Gradle configurations</a>
* @see PropDepsEclipsePlugin
* @see PropDepsIdeaPlugin
*/
class PropDepsPlugin implements Plugin<Project> {
public void apply(Project project) {
project.plugins.apply(JavaPlugin)
Configuration provided = addConfiguration(project, "provided")
Configuration optional = addConfiguration(project, "optional")
Javadoc javadoc = project.tasks.getByName(JavaPlugin.JAVADOC_TASK_NAME)
javadoc.classpath = javadoc.classpath.plus(provided).plus(optional)
}
private Configuration addConfiguration(Project project, String name) {
Configuration configuration = project.configurations.create(name)
configuration.extendsFrom(project.configurations.implementation)
project.plugins.withType(JavaLibraryPlugin, {
configuration.extendsFrom(project.configurations.api)
})
project.sourceSets.all {
compileClasspath += configuration
runtimeClasspath += configuration
}
return configuration
}
}
@@ -166,7 +166,7 @@ public class UpdateDependenciesExtension {
}
public DependencyExcludes releaseCandidatesVersions() {
this.actions.add(excludeVersionWithRegex("(?i).*?rc.*", "a release candidate version"));
this.actions.add(excludeVersionWithRegex("(?i).*?rc\\d+.*", "a release candidate version"));
return this;
}
@@ -1,35 +0,0 @@
/*
* Copyright 2002-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 s101;
import java.io.File;
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;
public class S101Configure extends DefaultTask {
@TaskAction
public void configure() throws Exception {
S101PluginExtension extension = getProject().getExtensions().getByType(S101PluginExtension.class);
File buildDirectory = extension.getInstallationDirectory().get();
File projectDirectory = extension.getConfigurationDirectory().get();
S101Configurer configurer = new S101Configurer(getProject());
configurer.configure(buildDirectory, projectDirectory);
}
}
@@ -1,307 +0,0 @@
/*
* Copyright 2002-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 s101;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import org.apache.commons.io.IOUtils;
import org.gradle.api.Project;
import org.gradle.api.logging.Logger;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.SourceSetContainer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class S101Configurer {
private static final Pattern VERSION = Pattern.compile("<local-project .* version=\"(.*?)\"");
private static final int BUFFER = 1024;
private static final long TOOBIG = 0x10000000; // ~268M
private static final int TOOMANY = 200;
private final MustacheFactory mustache = new DefaultMustacheFactory();
private final Mustache hspTemplate;
private final Mustache repositoryTemplate;
private final Path licenseDirectory;
private final Project project;
private final Logger logger;
public S101Configurer(Project project) {
this.project = project;
this.logger = project.getLogger();
Resource template = new ClassPathResource("s101/project.java.hsp");
try (InputStream is = template.getInputStream()) {
this.hspTemplate = this.mustache.compile(new InputStreamReader(is), "project");
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
template = new ClassPathResource("s101/repository.xml");
try (InputStream is = template.getInputStream()) {
this.repositoryTemplate = this.mustache.compile(new InputStreamReader(is), "repository");
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
this.licenseDirectory = new File(System.getProperty("user.home") + "/.Structure101/java").toPath();
}
public void license(String licenseId) {
Path licenseFile = this.licenseDirectory.resolve(".structure101license.properties");
if (needsLicense(licenseFile, licenseId)) {
writeLicense(licenseFile, licenseId);
}
}
private boolean needsLicense(Path licenseFile, String licenseId) {
if (!licenseFile.toFile().exists()) {
return true;
}
try {
String license = new String(Files.readAllBytes(licenseFile));
return !license.contains(licenseId);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private void writeLicense(Path licenseFile, String licenseId) {
if (!this.licenseDirectory.toFile().mkdirs()) {
this.licenseDirectory.forEach((path) -> path.toFile().delete());
}
try (PrintWriter pw = new PrintWriter(licenseFile.toFile())) {
pw.println("licensecode=" + licenseId);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public void install(File installationDirectory, File configurationDirectory) {
deleteDirectory(installationDirectory);
installBuildTool(installationDirectory, configurationDirectory);
}
public void configure(File installationDirectory, File configurationDirectory) {
deleteDirectory(configurationDirectory);
String version = computeVersionFromInstallation(installationDirectory);
configureProject(version, configurationDirectory);
}
private String computeVersionFromInstallation(File installationDirectory) {
File buildJar = new File(installationDirectory, "structure101-java-build.jar");
try (JarInputStream input = new JarInputStream(new FileInputStream(buildJar))) {
JarEntry entry;
while ((entry = input.getNextJarEntry()) != null) {
if (entry.getName().contains("structure101-build.properties")) {
Properties properties = new Properties();
properties.load(input);
return properties.getProperty("s101-build");
}
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
throw new IllegalStateException("Unable to determine Structure101 version");
}
private boolean deleteDirectory(File directoryToBeDeleted) {
File[] allContents = directoryToBeDeleted.listFiles();
if (allContents != null) {
for (File file : allContents) {
deleteDirectory(file);
}
}
return directoryToBeDeleted.delete();
}
private String installBuildTool(File installationDirectory, File configurationDirectory) {
String source = "https://structure101.com/binaries/v6";
try (final WebClient webClient = new WebClient()) {
HtmlPage page = webClient.getPage(source);
for (HtmlAnchor anchor : page.getAnchors()) {
Matcher matcher = Pattern.compile("(structure101-build-java-all-)(.*).zip").matcher(anchor.getHrefAttribute());
if (matcher.find()) {
copyZipToFilesystem(source, installationDirectory, matcher.group(1) + matcher.group(2));
return matcher.group(2);
}
}
return null;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private void copyZipToFilesystem(String source, File destination, String name) {
try (ZipInputStream in = new ZipInputStream(new URL(source + "/" + name + ".zip").openStream())) {
ZipEntry entry;
String build = destination.getName();
int entries = 0;
long size = 0;
while ((entry = in.getNextEntry()) != null) {
if (entry.getName().equals(name + "/")) {
destination.mkdirs();
} else if (entry.getName().startsWith(name)) {
if (entries++ > TOOMANY) {
throw new IllegalArgumentException("Zip file has more entries than expected");
}
if (size + BUFFER > TOOBIG) {
throw new IllegalArgumentException("Zip file is larger than expected");
}
String filename = entry.getName().replace(name, build);
if (filename.contains("maven")) {
continue;
}
if (filename.contains("jxbrowser")) {
continue;
}
if (filename.contains("jetty")) {
continue;
}
if (filename.contains("jfreechart")) {
continue;
}
if (filename.contains("piccolo2d")) {
continue;
}
if (filename.contains("plexus")) {
continue;
}
if (filename.contains("websocket")) {
continue;
}
validateFilename(filename, build);
this.logger.info("Downloading " + filename);
try (OutputStream out = new FileOutputStream(new File(destination.getParentFile(), filename))) {
byte[] data = new byte[BUFFER];
int read;
while ((read = in.read(data, 0, BUFFER)) != -1 && TOOBIG - size >= read) {
out.write(data, 0, read);
size += read;
}
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String validateFilename(String filename, String intendedDir)
throws java.io.IOException {
File f = new File(filename);
String canonicalPath = f.getCanonicalPath();
File iD = new File(intendedDir);
String canonicalID = iD.getCanonicalPath();
if (canonicalPath.startsWith(canonicalID)) {
return canonicalPath;
} else {
throw new IllegalArgumentException("File is outside extraction target directory.");
}
}
private void configureProject(String version, File configurationDirectory) {
configurationDirectory.mkdirs();
Map<String, Object> model = hspTemplateValues(version, configurationDirectory);
copyToProject(this.hspTemplate, model, new File(configurationDirectory, "project.java.hsp"));
copyToProject("s101/config.xml", new File(configurationDirectory, "config.xml"));
File repository = new File(configurationDirectory, "repository");
File snapshots = new File(repository, "snapshots");
if (!snapshots.exists() && !snapshots.mkdirs()) {
throw new IllegalStateException("Unable to create snapshots directory");
}
copyToProject(this.repositoryTemplate, model, new File(repository, "repository.xml"));
}
private void copyToProject(String location, File destination) {
Resource resource = new ClassPathResource(location);
try (InputStream is = resource.getInputStream();
OutputStream os = new FileOutputStream(destination)) {
IOUtils.copy(is, os);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
private void copyToProject(Mustache view, Map<String, Object> model, File destination) {
try (OutputStream os = new FileOutputStream(destination)) {
view.execute(new OutputStreamWriter(os), model).flush();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
private Map<String, Object> hspTemplateValues(String version, File configurationDirectory) {
Map<String, Object> values = new LinkedHashMap<>();
values.put("version", version);
values.put("patchVersion", version.split("\\.")[2]);
values.put("relativeTo", "const(THIS_FILE)/" + configurationDirectory.toPath().relativize(this.project.getProjectDir().toPath()));
List<Map<String, Object>> entries = new ArrayList<>();
Set<Project> projects = this.project.getAllprojects();
for (Project p : projects) {
SourceSetContainer sourceSets = (SourceSetContainer) p.getExtensions().findByName("sourceSets");
if (sourceSets == null) {
continue;
}
for (SourceSet source : sourceSets) {
Set<File> classDirs = source.getOutput().getClassesDirs().getFiles();
for (File directory : classDirs) {
Map<String, Object> entry = new HashMap<>();
entry.put("path", this.project.getProjectDir().toPath().relativize(directory.toPath()));
entry.put("module", p.getName());
entries.add(entry);
}
}
}
values.put("entries", entries);
return values;
}
}
@@ -1,35 +0,0 @@
/*
* Copyright 2002-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 s101;
import java.io.File;
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;
public class S101Install extends DefaultTask {
@TaskAction
public void install() throws Exception {
S101PluginExtension extension = getProject().getExtensions().getByType(S101PluginExtension.class);
File installationDirectory = extension.getInstallationDirectory().get();
File configurationDirectory = extension.getConfigurationDirectory().get();
S101Configurer configurer = new S101Configurer(getProject());
configurer.install(installationDirectory, configurationDirectory);
}
}
-161
View File
@@ -1,161 +0,0 @@
/*
* Copyright 2002-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 s101;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.JavaExec;
public class S101Plugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.getExtensions().add("s101", new S101PluginExtension(project));
project.getTasks().register("s101Install", S101Install.class, this::configure);
project.getTasks().register("s101Configure", S101Configure.class, this::configure);
project.getTasks().register("s101", JavaExec.class, this::configure);
}
private void configure(S101Install install) {
install.setDescription("Installs Structure101 to your filesystem");
}
private void configure(S101Configure configure) {
configure.setDescription("Applies a default Structure101 configuration to the project");
}
private void configure(JavaExec exec) {
exec.setDescription("Runs Structure101 headless analysis, installing and configuring if necessary");
exec.dependsOn("check");
Project project = exec.getProject();
S101PluginExtension extension = project.getExtensions().getByType(S101PluginExtension.class);
exec
.workingDir(extension.getInstallationDirectory())
.classpath(new File(extension.getInstallationDirectory().get(), "structure101-java-build.jar"))
.args(new File(new File(project.getBuildDir(), "s101"), "config.xml"))
.systemProperty("s101.label", computeLabel(extension).get())
.doFirst((task) -> {
installAndConfigureIfNeeded(project);
copyConfigurationToBuildDirectory(extension, project);
})
.doLast((task) -> {
copyResultsBackToConfigurationDirectory(extension, project);
});
}
private Property<String> computeLabel(S101PluginExtension extension) {
boolean hasBaseline = extension.getConfigurationDirectory().get().toPath()
.resolve("repository").resolve("snapshots").resolve("baseline").toFile().exists();
if (!hasBaseline) {
return extension.getLabel().convention("baseline");
}
return extension.getLabel().convention("recent");
}
private void installAndConfigureIfNeeded(Project project) {
S101Configurer configurer = new S101Configurer(project);
S101PluginExtension extension = project.getExtensions().getByType(S101PluginExtension.class);
String licenseId = extension.getLicenseId().getOrNull();
if (licenseId != null) {
configurer.license(licenseId);
}
File installationDirectory = extension.getInstallationDirectory().get();
File configurationDirectory = extension.getConfigurationDirectory().get();
if (!installationDirectory.exists()) {
configurer.install(installationDirectory, configurationDirectory);
}
if (!configurationDirectory.exists()) {
configurer.configure(installationDirectory, configurationDirectory);
}
}
private void copyConfigurationToBuildDirectory(S101PluginExtension extension, Project project) {
Path configurationDirectory = extension.getConfigurationDirectory().get().toPath();
Path buildDirectory = project.getBuildDir().toPath();
copyDirectory(project, configurationDirectory, buildDirectory);
}
private void copyResultsBackToConfigurationDirectory(S101PluginExtension extension, Project project) {
Path buildConfigurationDirectory = project.getBuildDir().toPath().resolve("s101");
String label = extension.getLabel().get();
if ("baseline".equals(label)) { // a new baseline was created
copyDirectory(project, buildConfigurationDirectory.resolve("repository").resolve("snapshots"),
extension.getConfigurationDirectory().get().toPath().resolve("repository"));
copyDirectory(project, buildConfigurationDirectory.resolve("repository"),
extension.getConfigurationDirectory().get().toPath());
}
}
private void copyDirectory(Project project, Path source, Path destination) {
try {
Files.walk(source)
.forEach(each -> {
Path relativeToSource = source.getParent().relativize(each);
Path resolvedDestination = destination.resolve(relativeToSource);
if (each.toFile().isDirectory()) {
resolvedDestination.toFile().mkdirs();
return;
}
InputStream input;
if ("project.java.hsp".equals(each.toFile().getName())) {
Path relativeTo = project.getBuildDir().toPath().resolve("s101").relativize(project.getProjectDir().toPath());
String value = "const(THIS_FILE)/" + relativeTo;
input = replace(each, "<property name=\"relative-to\" value=\"(.*)\" />", "<property name=\"relative-to\" value=\"" + value + "\" />");
} else if (each.toFile().toString().endsWith(".xml")) {
input = replace(each, "\\r\\n", "\n");
} else {
input = input(each);
}
try {
Files.copy(input, resolvedDestination, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private InputStream replace(Path file, String search, String replace) {
try {
byte[] b = Files.readAllBytes(file);
String contents = new String(b).replaceAll(search, replace);
return new ByteArrayInputStream(contents.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private InputStream input(Path file) {
try {
return new FileInputStream(file.toFile());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@@ -1,82 +0,0 @@
/*
* Copyright 2002-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 s101;
import java.io.File;
import org.gradle.api.Project;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputDirectory;
public class S101PluginExtension {
private final Property<String> licenseId;
private final Property<File> installationDirectory;
private final Property<File> configurationDirectory;
private final Property<String> label;
@Input
public Property<String> getLicenseId() {
return this.licenseId;
}
public void setLicenseId(String licenseId) {
this.licenseId.set(licenseId);
}
@InputDirectory
public Property<File> getInstallationDirectory() {
return this.installationDirectory;
}
public void setInstallationDirectory(String installationDirectory) {
this.installationDirectory.set(new File(installationDirectory));
}
@InputDirectory
public Property<File> getConfigurationDirectory() {
return this.configurationDirectory;
}
public void setConfigurationDirectory(String configurationDirectory) {
this.configurationDirectory.set(new File(configurationDirectory));
}
@Input
public Property<String> getLabel() {
return this.label;
}
public void setLabel(String label) {
this.label.set(label);
}
public S101PluginExtension(Project project) {
this.licenseId = project.getObjects().property(String.class);
if (project.hasProperty("s101.licenseId")) {
setLicenseId((String) project.findProperty("s101.licenseId"));
}
this.installationDirectory = project.getObjects().property(File.class)
.convention(new File(project.getBuildDir(), "s101"));
this.configurationDirectory = project.getObjects().property(File.class)
.convention(new File(project.getProjectDir(), "s101"));
this.label = project.getObjects().property(String.class);
if (project.hasProperty("s101.label")) {
setLabel((String) project.findProperty("s101.label"));
}
}
}
@@ -0,0 +1 @@
implementation-class=io.spring.gradle.convention.DependencySetPlugin
@@ -1 +0,0 @@
implementation-class=io.spring.gradle.convention.IncludeCheckRemotePlugin
@@ -0,0 +1 @@
implementation-class=io.spring.gradle.convention.OssrhPlugin
@@ -1,32 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<headless version="1.0">
<operations>
<operation type="publish">
<argument name="overwrite" value="true"/>
<argument name="diagrams" value="true"/>
</operation>
<operation type="check-key-measures">
<argument name="baseline" value="baseline"/>
<argument name="useProjectFileSpec" value="true"/>
<argument name="useProjectFileDiagrams" value="true"/>
<argument name="fail-on-architecture-violations" value="false"/>
<argument name="fail-on-fat-package" value="false"/>
<argument name="fail-on-fat-class" value="false"/>
<argument name="fail-on-fat-method" value="false"/>
<argument name="fail-on-feedback-dependencies" value="true"/>
<argument name="fail-on-spec-violation-dependencies" value="false"/>
<argument name="fail-on-total-problem-dependencies" value="false"/>
<argument name="fail-on-spec-item-violations" value="false"/>
<argument name="fail-on-biggest-class-tangle" value="true"/>
<argument name="fail-on-tangled-package" value="true"/>
<argument name="fail-on-architecture-violations" value="false"/>
<argument name="fail-on-total-problem-dependencies" value="true"/>
<argument name="identifier-on-violation" value="S101 key measure violation"/>
</operation>
</operations>
<arguments>
<argument name="local-project" value="const(THIS_FILE)/project.java.hsp"/>
<argument name="repository" value="const(THIS_FILE)/repository"/>
<argument name="project" value="snapshots"/>
</arguments>
</headless>
@@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<local-project language="java" version="{{version}}" xml-version="3" flavor="j2se">
<property name="show-as-module" value="false" />
<property name="publish-architecture-artifacts" value="true" />
<property name="force-classpath" value="false" />
<property name="project-type" value="classpath" />
<property name="hide-externals" value="true" />
<property name="parse-archive-in-archive" value="false" />
<property name="include-injected-dependency" value="false" />
<property name="relative-to" value="{{relativeTo}}" />
<property name="action-set-mod" value="1" />
<property name="detail-mode" value="true" />
<property name="hide-deprecated" value="false" />
<property name="resolve-name-clashes" value="true" />
<property name="project-excluded" />
<property name="show-needs-to-compile" value="false" />
<classpath>
{{#entries}}
<classpathentry kind="lib" path="{{path}}" module="{{module}}" />
{{/entries}}
</classpath>
<pom-root-files />
<modules-in-scope />
<restructuring>
<set version="3" name="Action list 1" hiview="Codemap" active="true" todo="false" list="0" />
</restructuring>
<grid-set sep="." version="{{version}}" />
</local-project>
@@ -1,14 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<structure101-repository language="java" version="{{patchVersion}}">
<xs-configuration>
<entry metric="Tangled" scope="design" threshold="0" color="153,53,0" />
<entry metric="Fat" scope="design" threshold="120" color="255,153,0" />
<entry metric="Fat" scope="leaf package" threshold="120" color="0,153,153" />
<entry metric="Fat" scope="class" threshold="120" color="255,153,153" />
<entry metric="Fat" scope="method" threshold="15" color="51,255,51" />
</xs-configuration>
<!--Note: All date strings are stored in short US format e.g. 2/1/06 for 1st Feb 2006-->
<project name="snapshots" dir="snapshots" baselineSnapshot="default" version="{{patchVersion}}">
<snapshot label="baseline" location="baseline" timestamp="3/16/21, 4:42 PM" version="{{patchVersion}}" detail="true" good="true" size="20" />
</project>
</structure101-repository>
@@ -0,0 +1,37 @@
/*
* Copyright 2002-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.
*/
package io.spring.gradle.convention
import io.spring.gradle.testkit.junit.rules.TestKit
import org.gradle.testkit.runner.BuildResult
import org.junit.Rule
import spock.lang.Specification
import static org.gradle.testkit.runner.TaskOutcome.SUCCESS
class DependencySetPluginITest extends Specification {
@Rule final TestKit testKit = new TestKit()
def "dependencies"() {
when:
BuildResult result = testKit.withProjectResource("samples/dependencyset")
.withArguments('dependencies')
.build();
then:
result.task(":dependencies").outcome == SUCCESS
!result.output.contains("FAILED")
}
}
@@ -0,0 +1,95 @@
/*
* Copyright 2002-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.
*/
package io.spring.gradle.convention
import io.spring.gradle.testkit.junit.rules.TestKit
import org.gradle.testkit.runner.BuildResult
import org.junit.Rule
import spock.lang.Specification
import java.util.zip.ZipFile
import static org.gradle.testkit.runner.TaskOutcome.FAILED
import static org.gradle.testkit.runner.TaskOutcome.SUCCESS
class DocsPluginITest extends Specification {
@Rule final TestKit testKit = new TestKit()
def "build triggers docs"() {
when:
BuildResult result = testKit.withProjectResource("samples/docs/simple/")
.withArguments('build')
.build();
then:
result.task(":build").outcome == SUCCESS
and:
result.task(":docs").outcome == SUCCESS
and:
result.task(":docsZip").outcome == SUCCESS
and:
def zip = new File(testKit.getRootDir(), 'build/distributions/simple-1.0.0.BUILD-SNAPSHOT-docs.zip')
def names = new ZipFile(zip).entries()*.name
names.contains("docs/reference/html5/index.html")
names.contains("docs/reference/pdf/simple-reference.pdf")
}
def "asciidoc copies images"() {
when:
BuildResult result = testKit.withProjectResource("samples/docs/simple/")
.withArguments('asciidoctor')
.build();
then:
result.task(":asciidoctor").outcome == SUCCESS
new File(testKit.getRootDir(), "build/docs/asciidoc/images").exists()
}
def "asciidoc docinfo from resources used"() {
when:
BuildResult result = testKit.withProjectResource("samples/docs/simple/")
.withArguments('asciidoctor')
.build();
then:
result.task(":asciidoctor").outcome == SUCCESS
new File(testKit.getRootDir(), "build/docs/asciidoc/index.html").getText().contains("""<script type="text/javascript" src="js/tocbot/tocbot.min.js"></script>""")
}
def "missing attribute fails"() {
when:
BuildResult result = testKit.withProjectResource("samples/docs/missing-attribute/")
.withArguments(':asciidoctor')
.buildAndFail();
then:
result.task(":asciidoctor").outcome == FAILED
}
def "missing include"() {
when:
BuildResult result = testKit.withProjectResource("samples/docs/missing-include/")
.withArguments(':asciidoctor')
.buildAndFail();
then:
result.task(":asciidoctor").outcome == FAILED
}
def "missing cross reference"() {
when:
BuildResult result = testKit.withProjectResource("samples/docs/missing-cross-reference/")
.withArguments(':asciidoctor')
.buildAndFail();
then:
result.task(":asciidoctor").outcome == FAILED
}
}
@@ -0,0 +1,63 @@
/*
* Copyright 2016-2018 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 io.spring.gradle.convention
import io.spring.gradle.testkit.junit.rules.TestKit
import org.gradle.testkit.runner.BuildResult
import org.junit.Rule
import spock.lang.Specification
import static org.gradle.testkit.runner.TaskOutcome.SUCCESS
class IntegrationTestPluginITest extends Specification {
@Rule final TestKit testKit = new TestKit()
def "check with java plugin"() {
when:
BuildResult result = testKit.withProjectResource("samples/integrationtest/withjava/")
.withArguments('check')
.build();
then:
result.task(":check").outcome == SUCCESS
and:
new File(testKit.getRootDir(), 'build/test-results/integrationTest/').exists()
new File(testKit.getRootDir(), 'build/reports/tests/integrationTest/').exists()
}
def "check with propdeps"() {
when:
BuildResult result = testKit.withProjectResource("samples/integrationtest/withpropdeps/")
.withArguments('check')
.build();
then:
result.task(":check").outcome == SUCCESS
and:
new File(testKit.getRootDir(), 'build/test-results/integrationTest/').exists()
new File(testKit.getRootDir(), 'build/reports/tests/integrationTest/').exists()
}
def "check with groovy plugin"() {
when:
BuildResult result = testKit.withProjectResource("samples/integrationtest/withgroovy/")
.withArguments('check')
.build();
then:
result.task(":check").outcome == SUCCESS
and:
new File(testKit.getRootDir(), 'build/test-results/integrationTest/').exists()
new File(testKit.getRootDir(), 'build/reports/tests/integrationTest/').exists()
}
}
@@ -0,0 +1,39 @@
/*
* Copyright 2002-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.
*/
package io.spring.gradle.convention
import io.spring.gradle.testkit.junit.rules.TestKit
import org.gradle.testkit.runner.BuildResult
import org.junit.Rule
import spock.lang.Specification
import static org.gradle.testkit.runner.TaskOutcome.SUCCESS
class JacocoPluginITest extends Specification {
@Rule final TestKit testKit = new TestKit()
def "check with java plugin"() {
when:
BuildResult result = testKit.withProjectResource("samples/jacoco/java/")
.withArguments('check')
.build();
then:
result.task(":check").outcome == SUCCESS
and:
new File(testKit.getRootDir(), 'build/jacoco').exists()
new File(testKit.getRootDir(), 'build/reports/jacoco/test/html/').exists()
}
}
@@ -0,0 +1,48 @@
/*
* Copyright 2002-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.
*/
package io.spring.gradle.convention
import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.GradleRunner
import org.junit.Rule
import org.junit.rules.TemporaryFolder
import spock.lang.Specification
import static org.gradle.testkit.runner.TaskOutcome.*;
import io.spring.gradle.testkit.junit.rules.TestKit
import org.apache.commons.io.FileUtils
class JavadocApiPluginITest extends Specification {
@Rule final TestKit testKit = new TestKit()
def "multimodule api"() {
when:
BuildResult result = testKit.withProjectResource("samples/javadocapi/multimodule/")
.withArguments('api')
.build();
then:
result.task(":api").outcome == SUCCESS
and:
File allClasses = new File(testKit.getRootDir(), 'build/api/allclasses-noframe.html');
File index = new File(testKit.getRootDir(), 'build/api/allclasses.html');
new File(testKit.getRootDir(), "build/api/").listFiles().each { println it }
File listing = allClasses.exists() ? allClasses : index
listing.text.contains('sample/Api.html')
listing.text.contains('sample/Impl.html')
!listing.text.contains('sample/Sample.html')
}
}
@@ -0,0 +1,126 @@
/*
* 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 io.spring.gradle.convention
import io.spring.gradle.testkit.junit.rules.TestKit
import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.TaskOutcome
import org.junit.Rule
import spock.lang.Ignore
import spock.lang.Specification
class ShowcaseITest extends Specification {
@Rule final TestKit testKit = new TestKit()
def "build"() {
when:
BuildResult result = testKit.withProjectResource("samples/showcase/")
.withArguments('build','--stacktrace')
.forwardOutput()
.build();
then: 'entire build passes'
result.output.contains("BUILD SUCCESSFUL")
}
@Ignore
def "install"() {
when:
BuildResult result = testKit.withProjectResource("samples/showcase/")
.withArguments('install','--stacktrace')
.build();
then:
result.output.contains("SUCCESS")
and: 'pom exists'
File pom = new File(testKit.getRootDir(), 'sgbcs-core/build/poms/pom-default.xml')
pom.exists()
String pomText = pom.getText()
and: 'pom does not contain <dependencyManagement>'
!pomText.contains('<dependencyManagement>')
and: 'creates optional dependencies correctly'
pomText.replaceAll('\\s','').contains("""<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
<version>4.3.6.RELEASE</version>
</dependency>""".replaceAll('\\s',''))
and: 'adds author'
pomText.replaceAll('\\s','').contains("""<developers>
<developer>
<id>rwinch</id>
<name>Rob Winch</name>
<email>rwinch@pivotal.io</email>
</developer>
<developer>
<id>jgrandja</id>
<name>Joe Grandja</name>
<email>jgrandja@pivotal.io</email>
</developer>
</developers>""".replaceAll('\\s',''))
and: 'adds repositories'
pomText.replaceAll('\\s','').contains("""<scm>
<connection>scm:git:git://github.com/spring-projects/spring-security</connection>
<developerConnection>scm:git:git://github.com/spring-projects/spring-security</developerConnection>
<url>https://github.com/spring-projects/spring-security</url>
</scm>""".replaceAll('\\s',''))
and: 'adds description & url'
pomText.contains('<description>sgbcs-core</description>')
pomText.contains('<url>https://spring.io/spring-security</url>')
and: 'adds organization'
pomText.replaceAll('\\s','').contains('''<organization>
<name>spring.io</name>
<url>https://spring.io/</url>
</organization>'''.replaceAll('\\s',''))
and: 'adds licenses'
pomText.replaceAll('\\s','').contains(''' <licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>'''.replaceAll('\\s',''))
and: 'adds scm'
pomText.replaceAll('\\s','').replaceAll('\\s','').contains("""<scm>
<connection>scm:git:git://github.com/spring-projects/spring-security</connection>
<developerConnection>scm:git:git://github.com/spring-projects/spring-security</developerConnection>
<url>https://github.com/spring-projects/spring-security</url>
</scm>""".replaceAll('\\s',''))
and: 'bom created'
File bom = new File(testKit.getRootDir(), 'bom/build/poms/pom-default.xml')
bom.exists()
String bomText = bom.getText()
bomText.contains("""<artifactId>sgbcs-core</artifactId>""")
when: 'mavenBom ran again'
result = testKit.withProjectResource("samples/showcase/")
.withArguments('mavenBom','--stacktrace')
.build();
then: 'mavenBom is not up to date since install is never up to date'
result.task(':bom:mavenBom').getOutcome() == TaskOutcome.SUCCESS
}
}
@@ -0,0 +1,91 @@
/*
* 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 io.spring.gradle.convention
import io.spring.gradle.testkit.junit.rules.TestKit
import org.gradle.testkit.runner.BuildResult
import org.junit.Rule
import spock.lang.Ignore
import spock.lang.Specification
import static org.gradle.testkit.runner.TaskOutcome.SUCCESS
class SpringMavenPluginITest extends Specification {
@Rule final TestKit testKit = new TestKit()
@Ignore
def "install"() {
when:
BuildResult result = testKit.withProjectResource("samples/maven/install")
.withArguments('install')
.build();
then: 'pom contains optional'
result.output.contains("SUCCESS")
File pom = new File(testKit.getRootDir(), 'build/poms/pom-default.xml')
pom.exists()
String pomText = pom.getText()
pomText.replaceAll('\\s','').contains("""<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>""".replaceAll('\\s',''))
}
@Ignore
def "signArchives when in memory"() {
when:
BuildResult result = testKit.withProjectResource("samples/maven/signing")
.withArguments('signArchives')
.withEnvironment(["ORG_GRADLE_PROJECT_signingKey" : signingKey,
"ORG_GRADLE_PROJECT_signingPassword" : "password"])
.forwardOutput()
.build();
then:
result.output.contains("SUCCESS")
File jar = new File(testKit.getRootDir(), 'build/libs/signing-1.0.0.RELEASE.jar')
jar.exists()
File signature = new File("${jar.absolutePath}.asc")
signature.exists()
}
def "upload"() {
when:
BuildResult result = testKit.withProjectResource("samples/maven/upload")
.withArguments('uploadArchives')
.forwardOutput()
.build();
then: 'pom contains optional'
result.output.contains("SUCCESS")
File pom = new File(testKit.getRootDir(), 'build/poms/pom-default.xml')
pom.exists()
String pomText = pom.getText()
pomText.replaceAll('\\s','').contains("""<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>""".replaceAll('\\s',''))
}
def getSigningKey() {
getClass().getResource("/test-private.pgp").text
}
}
@@ -0,0 +1,36 @@
/*
* Copyright 2002-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.
*/
package io.spring.gradle.convention
import io.spring.gradle.testkit.junit.rules.TestKit
import org.gradle.testkit.runner.BuildResult
import org.junit.Rule
import spock.lang.Specification
import static org.gradle.testkit.runner.TaskOutcome.SUCCESS
class TestsConfigurationPluginITest extends Specification {
@Rule final TestKit testKit = new TestKit()
def "can find dependency"() {
when:
BuildResult result = testKit.withProjectResource("samples/testsconfiguration")
.withArguments('check')
.build();
then:
result.task(":web:check").outcome == SUCCESS
}
}
@@ -13,25 +13,42 @@
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.spring.gradle;
import org.apache.commons.io.FileUtils;
import org.gradle.testkit.runner.GradleRunner;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
package io.spring.gradle.testkit.junit.rules;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.Enumeration;
public class TestKit {
final File buildDir;
import org.apache.commons.io.FileUtils;
import org.gradle.testkit.runner.GradleRunner;
import org.junit.rules.TemporaryFolder;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public TestKit(File buildDir) {
this.buildDir = buildDir;
public class TestKit implements TestRule {
final TemporaryFolder testProjectDir = new TemporaryFolder();
File buildDir;
@Override
public Statement apply(Statement base, Description description) {
Statement wrapped = new Statement() {
@Override
public void evaluate() throws Throwable {
try {
buildDir = testProjectDir.newFolder();
} catch(IOException e) {
throw new RuntimeException(e);
}
base.evaluate();
}
};
return testProjectDir.apply(wrapped, description);
}
public File getRootDir() {
@@ -1,111 +0,0 @@
/*
* Copyright 2002-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 io.spring.gradle.convention;
import io.spring.gradle.IncludeRepoTask;
import org.apache.commons.io.FileUtils;
import org.gradle.api.Project;
import org.gradle.api.tasks.GradleBuild;
import org.gradle.testfixtures.ProjectBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
class IncludeCheckRemotePluginTest {
Project rootProject;
@AfterEach
public void cleanup() throws Exception {
if (rootProject != null) {
FileUtils.deleteDirectory(rootProject.getProjectDir());
}
}
@Test
void applyWhenExtensionPropertiesNoTasksThenCreateCheckRemoteTaskWithDefaultTask() {
this.rootProject = ProjectBuilder.builder().build();
this.rootProject.getPluginManager().apply(IncludeCheckRemotePlugin.class);
this.rootProject.getExtensions().configure(IncludeCheckRemotePlugin.IncludeCheckRemoteExtension.class,
(includeCheckRemoteExtension) -> {
includeCheckRemoteExtension.setProperty("repository", "my-project/my-repository");
includeCheckRemoteExtension.setProperty("ref", "main");
});
GradleBuild checkRemote = (GradleBuild) this.rootProject.getTasks().named("checkRemote").get();
assertThat(checkRemote.getTasks()).containsExactly("check");
}
@Test
void applyWhenExtensionPropertiesTasksThenCreateCheckRemoteWithProvidedTasks() {
this.rootProject = ProjectBuilder.builder().build();
this.rootProject.getPluginManager().apply(IncludeCheckRemotePlugin.class);
this.rootProject.getExtensions().configure(IncludeCheckRemotePlugin.IncludeCheckRemoteExtension.class,
(includeCheckRemoteExtension) -> {
includeCheckRemoteExtension.setProperty("repository", "my-project/my-repository");
includeCheckRemoteExtension.setProperty("ref", "main");
includeCheckRemoteExtension.setProperty("tasks", Arrays.asList("clean", "build", "test"));
});
GradleBuild checkRemote = (GradleBuild) this.rootProject.getTasks().named("checkRemote").get();
assertThat(checkRemote.getTasks()).containsExactly("clean", "build", "test");
}
@Test
void applyWhenExtensionPropertiesThenRegisterIncludeRepoTaskWithExtensionProperties() {
this.rootProject = ProjectBuilder.builder().build();
this.rootProject.getPluginManager().apply(IncludeCheckRemotePlugin.class);
this.rootProject.getExtensions().configure(IncludeCheckRemotePlugin.IncludeCheckRemoteExtension.class,
(includeCheckRemoteExtension) -> {
includeCheckRemoteExtension.setProperty("repository", "my-project/my-repository");
includeCheckRemoteExtension.setProperty("ref", "main");
});
IncludeRepoTask includeRepo = (IncludeRepoTask) this.rootProject.getTasks().named("includeRepo").get();
assertThat(includeRepo).isNotNull();
assertThat(includeRepo.getRepository().get()).isEqualTo("my-project/my-repository");
assertThat(includeRepo.getRef().get()).isEqualTo("main");
}
@Test
void applyWhenRegisterTasksThenCheckRemoteDirSameAsIncludeRepoOutputDir() {
this.rootProject = ProjectBuilder.builder().build();
this.rootProject.getPluginManager().apply(IncludeCheckRemotePlugin.class);
this.rootProject.getExtensions().configure(IncludeCheckRemotePlugin.IncludeCheckRemoteExtension.class,
(includeCheckRemoteExtension) -> {
includeCheckRemoteExtension.setProperty("repository", "my-project/my-repository");
includeCheckRemoteExtension.setProperty("ref", "main");
});
IncludeRepoTask includeRepo = (IncludeRepoTask) this.rootProject.getTasks().named("includeRepo").get();
GradleBuild checkRemote = (GradleBuild) this.rootProject.getTasks().named("checkRemote").get();
assertThat(checkRemote.getDir()).isEqualTo(includeRepo.getOutputDirectory());
}
@Test
void applyWhenNoExtensionPropertiesThenRegisterTasks() {
this.rootProject = ProjectBuilder.builder().build();
this.rootProject.getPluginManager().apply(IncludeCheckRemotePlugin.class);
IncludeRepoTask includeRepo = (IncludeRepoTask) this.rootProject.getTasks().named("includeRepo").get();
GradleBuild checkRemote = (GradleBuild) this.rootProject.getTasks().named("checkRemote").get();
assertThat(includeRepo).isNotNull();
assertThat(checkRemote).isNotNull();
}
}
@@ -19,9 +19,10 @@ package io.spring.gradle.convention;
import org.apache.commons.io.FileUtils;
import org.gradle.api.Project;
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.tasks.javadoc.Javadoc;
import org.gradle.testfixtures.ProjectBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.After;
import org.junit.Test;
import java.io.File;
@@ -33,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class IntegrationPluginTest {
Project rootProject;
@AfterEach
@After
public void cleanup() throws Exception {
if (rootProject != null) {
FileUtils.deleteDirectory(rootProject.getProjectDir());
@@ -1,52 +0,0 @@
package io.spring.gradle.convention;
import io.spring.gradle.TestKit;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.TaskOutcome;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.assertThat;
public class IntegrationTestPluginITest {
private io.spring.gradle.TestKit testKit;
@BeforeEach
void setup(@TempDir Path tempDir) {
this.testKit = new TestKit(tempDir.toFile());
}
@Test
public void checkWithJavaPlugin() throws Exception {
BuildResult result = this.testKit.withProjectResource("samples/integrationtest/withjava/")
.withArguments("check")
.build();
assertThat(result.task(":check").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
assertThat(new File(testKit.getRootDir(), "build/test-results/integrationTest/")).exists();
assertThat(new File(testKit.getRootDir(), "build/reports/tests/integrationTest/")).exists();
}
@Test
public void checkWithPropdeps() throws Exception {
BuildResult result = this.testKit.withProjectResource("samples/integrationtest/withpropdeps/")
.withArguments("check")
.build();
assertThat(result.task(":check").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
assertThat(new File(testKit.getRootDir(), "build/test-results/integrationTest/")).exists();
assertThat(new File(testKit.getRootDir(), "build/reports/tests/integrationTest/")).exists();
}
@Test
public void checkWithGroovy() throws Exception {
BuildResult result = this.testKit.withProjectResource("samples/integrationtest/withgroovy/")
.withArguments("check")
.build();
assertThat(result.task(":check").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
assertThat(new File(testKit.getRootDir(), "build/test-results/integrationTest/")).exists();
assertThat(new File(testKit.getRootDir(), "build/reports/tests/integrationTest/")).exists();
}
}
@@ -1,31 +0,0 @@
package io.spring.gradle.convention;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.TaskOutcome;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.assertThat;
public class JacocoPluginITest{
private io.spring.gradle.TestKit testKit;
@BeforeEach
void setup(@TempDir Path tempDir) {
this.testKit = new io.spring.gradle.TestKit(tempDir.toFile());
}
@Test
public void checkWithJavaPlugin() throws Exception {
BuildResult result = this.testKit.withProjectResource("samples/jacoco/java/")
.withArguments("check")
.build();
assertThat(result.task(":check").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
assertThat(new File(testKit.getRootDir(), "build/jacoco")).exists();
assertThat(new File(testKit.getRootDir(), "build/reports/jacoco/test/html/")).exists();
}
}
@@ -1,38 +0,0 @@
package io.spring.gradle.convention;
import io.spring.gradle.TestKit;
import org.apache.commons.io.FileUtils;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.TaskOutcome;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.assertThat;
public class JavadocApiPluginITest {
private TestKit testKit;
@BeforeEach
void setup(@TempDir Path tempDir) {
this.testKit = new TestKit(tempDir.toFile());
}
@Test
public void multiModuleApi() throws Exception {
BuildResult result = this.testKit.withProjectResource("samples/javadocapi/multimodule/")
.withArguments("api")
.build();
assertThat(result.task(":api").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
File allClasses = new File(testKit.getRootDir(), "build/api/allclasses-noframe.html");
File index = new File(testKit.getRootDir(), "build/api/allclasses.html");
File listing = allClasses.exists() ? allClasses : index;
String listingText = FileUtils.readFileToString(listing);
assertThat(listingText).contains("sample/Api.html");
assertThat(listingText).contains("sample/Impl.html");
assertThat(listingText).doesNotContain("sample/Sample.html");
}
}
@@ -23,8 +23,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import org.gradle.api.Project;
import org.gradle.api.tasks.javadoc.Javadoc;
import org.gradle.testfixtures.ProjectBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.After;
import org.junit.Test;
/**
* @author Rob Winch
@@ -32,7 +32,7 @@ import org.junit.jupiter.api.Test;
public class JavadocApiPluginTest {
Project rootProject;
@AfterEach
@After
public void cleanup() throws Exception {
if (rootProject != null) {
FileUtils.deleteDirectory(rootProject.getProjectDir());
@@ -22,8 +22,8 @@ import org.gradle.api.artifacts.repositories.ArtifactRepository;
import org.gradle.api.artifacts.repositories.MavenArtifactRepository;
import org.gradle.api.plugins.ExtraPropertiesExtension;
import org.gradle.testfixtures.ProjectBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -34,7 +34,7 @@ public class RepositoryConventionPluginTests {
private Project project = ProjectBuilder.builder().build();
@BeforeEach
@Before
public void setUp() {
this.project.getProperties().clear();
}
@@ -107,7 +107,7 @@ public class RepositoryConventionPluginTests {
this.project.getPluginManager().apply(RepositoryConventionPlugin.class);
RepositoryHandler repositories = this.project.getRepositories();
assertThat(repositories).hasSize(4);
assertThat(repositories).hasSize(5);
assertThat((repositories.get(0)).getName()).isEqualTo("MavenLocal");
}
@@ -119,33 +119,39 @@ public class RepositoryConventionPluginTests {
this.project.getPluginManager().apply(RepositoryConventionPlugin.class);
RepositoryHandler repositories = this.project.getRepositories();
assertThat(repositories).hasSize(5);
assertThat(repositories).hasSize(6);
assertThat((repositories.get(0)).getName()).isEqualTo("MavenLocal");
}
private void assertSnapshotRepository(RepositoryHandler repositories) {
assertThat(repositories).extracting(ArtifactRepository::getName).hasSize(5);
assertThat(repositories).extracting(ArtifactRepository::getName).hasSize(6);
assertThat(((MavenArtifactRepository) repositories.get(0)).getUrl().toString())
.isEqualTo("https://repo.maven.apache.org/maven2/");
assertThat(((MavenArtifactRepository) repositories.get(1)).getUrl().toString())
.isEqualTo("https://repo.spring.io/snapshot/");
.isEqualTo("https://jcenter.bintray.com/");
assertThat(((MavenArtifactRepository) repositories.get(2)).getUrl().toString())
.isEqualTo("https://repo.spring.io/snapshot/");
assertThat(((MavenArtifactRepository) repositories.get(3)).getUrl().toString())
.isEqualTo("https://repo.spring.io/milestone/");
}
private void assertMilestoneRepository(RepositoryHandler repositories) {
assertThat(repositories).extracting(ArtifactRepository::getName).hasSize(4);
assertThat(repositories).extracting(ArtifactRepository::getName).hasSize(5);
assertThat(((MavenArtifactRepository) repositories.get(0)).getUrl().toString())
.isEqualTo("https://repo.maven.apache.org/maven2/");
assertThat(((MavenArtifactRepository) repositories.get(1)).getUrl().toString())
.isEqualTo("https://jcenter.bintray.com/");
assertThat(((MavenArtifactRepository) repositories.get(2)).getUrl().toString())
.isEqualTo("https://repo.spring.io/milestone/");
}
private void assertReleaseRepository(RepositoryHandler repositories) {
assertThat(repositories).extracting(ArtifactRepository::getName).hasSize(3);
assertThat(repositories).extracting(ArtifactRepository::getName).hasSize(4);
assertThat(((MavenArtifactRepository) repositories.get(0)).getUrl().toString())
.isEqualTo("https://repo.maven.apache.org/maven2/");
assertThat(((MavenArtifactRepository) repositories.get(1)).getUrl().toString())
.isEqualTo("https://jcenter.bintray.com/");
assertThat(((MavenArtifactRepository) repositories.get(2)).getUrl().toString())
.isEqualTo("https://repo.spring.io/release/");
}
@@ -1,70 +0,0 @@
package io.spring.gradle.convention;
import io.spring.gradle.TestKit;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.TaskOutcome;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.assertThat;
public class ShowcaseITest {
private TestKit testKit;
@BeforeEach
void setup(@TempDir Path tempDir) {
this.testKit = new TestKit(tempDir.toFile());
}
@Test
public void build() throws Exception {
BuildResult result = this.testKit.withProjectResource("samples/showcase/")
.withArguments("build", "--stacktrace")
.forwardOutput()
.build();
assertThat(result.getOutput()).contains("BUILD SUCCESSFUL");
}
@Test
@Disabled
public void install() throws Exception {
BuildResult result = this.testKit
.withProjectResource("samples/showcase/")
.withArguments("install", "--stacktrace")
.build();
assertThat(result.getOutput()).contains("SUCCESS");
File pom = new File(testKit.getRootDir(), "sgbcs-core/build/poms/pom-default.xml");
assertThat(pom).exists();
String pomText = new String(Files.readAllBytes(pom.toPath()));
String pomTextNoSpace = pomText.replaceAll("\\s", "");
assertThat(pomText).doesNotContain("<dependencyManagement>");
assertThat(pomTextNoSpace).contains("<dependency>\n <groupId>org.springframework</groupId>\n <artifactId>spring-test</artifactId>\n <scope>test</scope>\n <version>4.3.6.RELEASE</version>\n </dependency>".replaceAll("\\s", ""));
assertThat(pomTextNoSpace).contains("<developers>\n <developer>\n <id>rwinch</id>\n <name>Rob Winch</name>\n <email>rwinch@pivotal.io</email>\n </developer>\n <developer>\n <id>jgrandja</id>\n <name>Joe Grandja</name>\n <email>jgrandja@pivotal.io</email>\n </developer>\n </developers>".replaceAll("\\s", ""));
assertThat(pomTextNoSpace).contains("<scm>\n <connection>scm:git:git://github.com/spring-projects/spring-security</connection>\n <developerConnection>scm:git:git://github.com/spring-projects/spring-security</developerConnection>\n <url>https://github.com/spring-projects/spring-security</url>\n </scm>".replaceAll("\\s", ""));
assertThat(pomTextNoSpace).contains("<description>sgbcs-core</description>");
assertThat(pomTextNoSpace).contains("<url>https://spring.io/spring-security</url>");
assertThat(pomTextNoSpace).contains("<organization>\n <name>spring.io</name>\n <url>https://spring.io/</url>\n </organization>".replaceAll("\\s", ""));
assertThat(pomTextNoSpace).contains(" <licenses>\n <license>\n <name>The Apache Software License, Version 2.0</name>\n <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>\n <distribution>repo</distribution>\n </license>\n </licenses>".replaceAll("\\s", ""));
assertThat(pomTextNoSpace).contains("<scm>\n <connection>scm:git:git://github.com/spring-projects/spring-security</connection>\n <developerConnection>scm:git:git://github.com/spring-projects/spring-security</developerConnection>\n <url>https://github.com/spring-projects/spring-security</url>\n </scm>".replaceAll("\\s", ""));
File bom = new File(testKit.getRootDir(), "bom/build/poms/pom-default.xml");
assertThat(bom).exists();
assertThat(bom).hasContent("<artifactId>sgbcs-core</artifactId>");
BuildResult secondBuild = this.testKit.withProjectResource("samples/showcase/").withArguments("mavenBom", "--stacktrace").build();
// mavenBom is not up to date since install is never up to date
assertThat(result.task(":bom:mavenBom").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
}
}
@@ -1,61 +0,0 @@
package io.spring.gradle.convention;
import io.spring.gradle.TestKit;
import org.apache.commons.io.IOUtils;
import org.gradle.testkit.runner.BuildResult;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import static org.assertj.core.api.Assertions.assertThat;
public class SpringMavenPluginITest {
private TestKit testKit;
@BeforeEach
void setup(@TempDir Path tempDir) {
this.testKit = new TestKit(tempDir.toFile());
}
@Disabled
@Test
public void install() throws Exception {
BuildResult result = this.testKit.withProjectResource("samples/maven/install")
.withArguments("install")
.build();
assertThat(result.getOutput()).contains("SUCCESS");
File pom = new File(testKit.getRootDir(), "build/poms/pom-default.xml");
assertThat(pom).exists();
String pomText = new String(Files.readAllBytes(pom.toPath()));
assertThat(pomText.replaceAll("\\s", "")).contains("<dependency>\n <groupId>aopalliance</groupId>\n <artifactId>aopalliance</artifactId>\n <version>1.0</version>\n <scope>compile</scope>\n <optional>true</optional>\n </dependency>".replaceAll("\\s", ""));
}
@Disabled
@Test
public void signArchivesWhenInMemory() throws Exception {
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(2);
map.put("ORG_GRADLE_PROJECT_signingKey", getSigningKey());
map.put("ORG_GRADLE_PROJECT_signingPassword", "password");
BuildResult result = this.testKit.withProjectResource("samples/maven/signing")
.withArguments("signArchives")
.withEnvironment(map)
.forwardOutput()
.build();
assertThat(result.getOutput()).contains("SUCCESS");
final File jar = new File(testKit.getRootDir(), "build/libs/signing-1.0.0.RELEASE.jar");
assertThat(jar).exists();
File signature = new File(jar.getAbsolutePath() + ".asc");
assertThat(signature).exists();
}
public String getSigningKey() throws Exception {
return IOUtils.toString(getClass().getResource("/test-private.pgp"));
}
}
@@ -1,31 +0,0 @@
package io.spring.gradle.convention;
import io.spring.gradle.TestKit;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.TaskOutcome;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.assertThat;
public class TestsConfigurationPluginITest {
private TestKit testKit;
@BeforeEach
void setup(@TempDir Path tempDir) {
this.testKit = new TestKit(tempDir.toFile());
}
@Test
public void canFindDepencency() throws Exception {
BuildResult result = this.testKit.withProjectResource("samples/testsconfiguration")
.withArguments("check")
.build();
assertThat(result.task(":web:check").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
}
}
@@ -5,21 +5,26 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import org.gradle.api.Project;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoJUnitRunner;
@ExtendWith(MockitoExtension.class)
@RunWith(MockitoJUnitRunner.class)
public class UtilsTest {
@Mock
Project project;
@Mock
Project rootProject;
@Before
public void setup() {
when(project.getRootProject()).thenReturn(rootProject);
}
@Test
public void getProjectName() {
when(project.getRootProject()).thenReturn(rootProject);
when(rootProject.getName()).thenReturn("spring-security");
assertThat(Utils.getProjectName(project)).isEqualTo("spring-security");
@@ -27,7 +32,6 @@ public class UtilsTest {
@Test
public void getProjectNameWhenEndsWithBuildThenStrippedOut() {
when(project.getRootProject()).thenReturn(rootProject);
when(rootProject.getName()).thenReturn("spring-security-build");
assertThat(Utils.getProjectName(project)).isEqualTo("spring-security");

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