repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
spring-security-main/buildSrc/src/test/java/org/springframework/security/convention/versions/DependencyExcludesTests.java
/* * 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 org.springframework.security.convention.versions; import com.github.benmanes.gradle.versions.updates.resolutionstrategy.ComponentSelectionWithCurrent; import org.gradle.api.Action; import org.gradle.api.artifacts.ComponentSelection; import org.gradle.api.artifacts.component.ModuleComponentIdentifier; import org.junit.jupiter.api.Test; import java.util.Collections; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.*; public class DependencyExcludesTests { @Test public void createExcludeMinorVersionBumpWhenMajorVersionBumpThenReject() { ComponentSelection componentSelection = executeCreateExcludeMinorVersionBump("1.0.0", "2.0.0"); verify(componentSelection).reject(any()); } @Test public void createExcludeMinorVersionBumpWhenMajorCalVersionBumpThenReject() { ComponentSelection componentSelection = executeCreateExcludeMinorVersionBump("2000.0.0", "2001.0.0"); verify(componentSelection).reject(any()); } @Test public void createExcludeMinorVersionBumpWhenMinorVersionBumpThenReject() { ComponentSelection componentSelection = executeCreateExcludeMinorVersionBump("1.0.0", "1.1.0"); verify(componentSelection).reject(any()); } @Test public void createExcludeMinorVersionBumpWhenMinorCalVersionBumpThenReject() { ComponentSelection componentSelection = executeCreateExcludeMinorVersionBump("2000.0.0", "2000.1.0"); verify(componentSelection).reject(any()); } @Test public void createExcludeMinorVersionBumpWhenMinorAndPatchVersionBumpThenReject() { ComponentSelection componentSelection = executeCreateExcludeMinorVersionBump("1.0.0", "1.1.1"); verify(componentSelection).reject(any()); } @Test public void createExcludeMinorVersionBumpWhenPatchVersionBumpThenDoesNotReject() { ComponentSelection componentSelection = executeCreateExcludeMinorVersionBump("1.0.0", "1.0.1"); verify(componentSelection, times(0)).reject(any()); } private ComponentSelection executeCreateExcludeMinorVersionBump(String currentVersion, String candidateVersion) { ComponentSelection componentSelection = mock(ComponentSelection.class); UpdateDependenciesExtension.DependencyExcludes excludes = new UpdateDependenciesExtension(() -> Collections.emptyList()).new DependencyExcludes(); Action<ComponentSelectionWithCurrent> excludeMinorVersionBump = excludes.createExcludeMinorVersionBump(); ComponentSelectionWithCurrent selection = currentVersionAndCandidateVersion(componentSelection, currentVersion, candidateVersion); excludeMinorVersionBump.execute(selection); return componentSelection; } private ComponentSelectionWithCurrent currentVersionAndCandidateVersion(ComponentSelection componentSelection, String currentVersion, String candidateVersion) { ModuleComponentIdentifier candidate = mock(ModuleComponentIdentifier.class); given(componentSelection.getCandidate()).willReturn(candidate); ComponentSelectionWithCurrent selection = new ComponentSelectionWithCurrent(currentVersion, componentSelection); given(candidate.getVersion()).willReturn(candidateVersion); given(componentSelection.getCandidate()).willReturn(candidate); return selection; } }
3,827
43
161
java
null
spring-security-main/buildSrc/src/test/java/org/springframework/security/convention/versions/TransitiveDependencyLookupUtilsTest.java
/* * 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 org.springframework.security.convention.versions; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class TransitiveDependencyLookupUtilsTest { @Test public void lookupJwtVersionWhen93Then961() { String s = TransitiveDependencyLookupUtils.lookupJwtVersion("9.3"); assertThat(s).isEqualTo("9.6.1"); } }
995
30.125
75
java
null
spring-security-main/buildSrc/src/test/java/org/springframework/gradle/github/user/GitHubUserApiTests.java
/* * Copyright 2020-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.gradle.github.user; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Steve Riesenberg */ public class GitHubUserApiTests { private GitHubUserApi gitHubUserApi; private MockWebServer server; private String baseUrl; @BeforeEach public void setup() throws Exception { this.server = new MockWebServer(); this.server.start(); this.baseUrl = this.server.url("/api").toString(); this.gitHubUserApi = new GitHubUserApi("mock-oauth-token"); this.gitHubUserApi.setBaseUrl(this.baseUrl); } @AfterEach public void cleanup() throws Exception { this.server.shutdown(); } @Test public void getUserWhenValidParametersThenSuccess() { // @formatter:off String responseJson = "{\n" + " \"avatar_url\": \"https://avatars.githubusercontent.com/u/583231?v=4\",\n" + " \"bio\": null,\n" + " \"blog\": \"https://github.blog\",\n" + " \"company\": \"@github\",\n" + " \"created_at\": \"2011-01-25T18:44:36Z\",\n" + " \"email\": null,\n" + " \"events_url\": \"https://api.github.com/users/octocat/events{/privacy}\",\n" + " \"followers\": 8481,\n" + " \"followers_url\": \"https://api.github.com/users/octocat/followers\",\n" + " \"following\": 9,\n" + " \"following_url\": \"https://api.github.com/users/octocat/following{/other_user}\",\n" + " \"gists_url\": \"https://api.github.com/users/octocat/gists{/gist_id}\",\n" + " \"gravatar_id\": \"\",\n" + " \"hireable\": null,\n" + " \"html_url\": \"https://github.com/octocat\",\n" + " \"id\": 583231,\n" + " \"location\": \"San Francisco\",\n" + " \"login\": \"octocat\",\n" + " \"name\": \"The Octocat\",\n" + " \"node_id\": \"MDQ6VXNlcjU4MzIzMQ==\",\n" + " \"organizations_url\": \"https://api.github.com/users/octocat/orgs\",\n" + " \"public_gists\": 8,\n" + " \"public_repos\": 8,\n" + " \"received_events_url\": \"https://api.github.com/users/octocat/received_events\",\n" + " \"repos_url\": \"https://api.github.com/users/octocat/repos\",\n" + " \"site_admin\": false,\n" + " \"starred_url\": \"https://api.github.com/users/octocat/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\": \"https://api.github.com/users/octocat/subscriptions\",\n" + " \"twitter_username\": null,\n" + " \"type\": \"User\",\n" + " \"updated_at\": \"2023-02-25T12:14:58Z\",\n" + " \"url\": \"https://api.github.com/users/octocat\"\n" + "}"; // @formatter:on this.server.enqueue(new MockResponse().setBody(responseJson)); User user = this.gitHubUserApi.getUser(); assertThat(user.getId()).isEqualTo(583231); assertThat(user.getLogin()).isEqualTo("octocat"); assertThat(user.getName()).isEqualTo("The Octocat"); assertThat(user.getUrl()).isEqualTo("https://api.github.com/users/octocat"); } @Test public void getUserWhenErrorResponseThenException() { this.server.enqueue(new MockResponse().setResponseCode(400)); // @formatter:off assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> this.gitHubUserApi.getUser()); // @formatter:on } }
4,107
37.392523
97
java
null
spring-security-main/buildSrc/src/test/java/org/springframework/gradle/github/milestones/SpringReleaseTrainTests.java
/* * Copyright 2002-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.github.milestones; import java.time.LocalDate; import java.time.Year; import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.springframework.gradle.github.milestones.SpringReleaseTrainSpec.Train; import static org.assertj.core.api.Assertions.assertThat; /** * @author Steve Riesenberg */ public class SpringReleaseTrainTests { @ParameterizedTest @CsvSource({ "2019-12-31, ONE, 2020", "2020-01-01, ONE, 2020", "2020-01-31, ONE, 2020", "2020-02-01, TWO, 2020", "2020-07-31, TWO, 2020", "2020-08-01, ONE, 2021" }) public void nextTrainWhenBoundaryConditionsThenSuccess(LocalDate startDate, Train expectedTrain, Year expectedYear) { SpringReleaseTrainSpec releaseTrainSpec = SpringReleaseTrainSpec.builder() .nextTrain(startDate) .version("1.0.0") .weekOfMonth(2) .dayOfWeek(2) .build(); assertThat(releaseTrainSpec.getTrain()).isEqualTo(expectedTrain); assertThat(releaseTrainSpec.getYear()).isEqualTo(expectedYear); } @Test public void getTrainDatesWhenTrainOneIsSecondTuesdayOf2020ThenSuccess() { SpringReleaseTrainSpec releaseTrainSpec = SpringReleaseTrainSpec.builder() .train(1) .version("1.0.0") .weekOfMonth(2) .dayOfWeek(2) .year(2020) .build(); SpringReleaseTrain releaseTrain = new SpringReleaseTrain(releaseTrainSpec); Map<String, LocalDate> trainDates = releaseTrain.getTrainDates(); assertThat(trainDates).hasSize(5); assertThat(trainDates.get("1.0.0-M1")).isEqualTo(LocalDate.of(2020, 1, 14)); assertThat(trainDates.get("1.0.0-M2")).isEqualTo(LocalDate.of(2020, 2, 11)); assertThat(trainDates.get("1.0.0-M3")).isEqualTo(LocalDate.of(2020, 3, 10)); assertThat(trainDates.get("1.0.0-RC1")).isEqualTo(LocalDate.of(2020, 4, 14)); assertThat(trainDates.get("1.0.0")).isEqualTo(LocalDate.of(2020, 5, 12)); } @Test public void getTrainDatesWhenTrainTwoIsSecondTuesdayOf2020ThenSuccess() { SpringReleaseTrainSpec releaseTrainSpec = SpringReleaseTrainSpec.builder() .train(2) .version("1.0.0") .weekOfMonth(2) .dayOfWeek(2) .year(2020) .build(); SpringReleaseTrain releaseTrain = new SpringReleaseTrain(releaseTrainSpec); Map<String, LocalDate> trainDates = releaseTrain.getTrainDates(); assertThat(trainDates).hasSize(5); assertThat(trainDates.get("1.0.0-M1")).isEqualTo(LocalDate.of(2020, 7, 14)); assertThat(trainDates.get("1.0.0-M2")).isEqualTo(LocalDate.of(2020, 8, 11)); assertThat(trainDates.get("1.0.0-M3")).isEqualTo(LocalDate.of(2020, 9, 15)); assertThat(trainDates.get("1.0.0-RC1")).isEqualTo(LocalDate.of(2020, 10, 13)); assertThat(trainDates.get("1.0.0")).isEqualTo(LocalDate.of(2020, 11, 10)); } @Test public void getTrainDatesWhenTrainOneIsSecondTuesdayOf2022ThenSuccess() { SpringReleaseTrainSpec releaseTrainSpec = SpringReleaseTrainSpec.builder() .train(1) .version("1.0.0") .weekOfMonth(2) .dayOfWeek(2) .year(2022) .build(); SpringReleaseTrain releaseTrain = new SpringReleaseTrain(releaseTrainSpec); Map<String, LocalDate> trainDates = releaseTrain.getTrainDates(); assertThat(trainDates).hasSize(5); assertThat(trainDates.get("1.0.0-M1")).isEqualTo(LocalDate.of(2022, 1, 11)); assertThat(trainDates.get("1.0.0-M2")).isEqualTo(LocalDate.of(2022, 2, 15)); assertThat(trainDates.get("1.0.0-M3")).isEqualTo(LocalDate.of(2022, 3, 15)); assertThat(trainDates.get("1.0.0-RC1")).isEqualTo(LocalDate.of(2022, 4, 12)); assertThat(trainDates.get("1.0.0")).isEqualTo(LocalDate.of(2022, 5, 10)); } @Test public void getTrainDatesWhenTrainTwoIsSecondTuesdayOf2022ThenSuccess() { SpringReleaseTrainSpec releaseTrainSpec = SpringReleaseTrainSpec.builder() .train(2) .version("1.0.0") .weekOfMonth(2) .dayOfWeek(2) .year(2022) .build(); SpringReleaseTrain releaseTrain = new SpringReleaseTrain(releaseTrainSpec); Map<String, LocalDate> trainDates = releaseTrain.getTrainDates(); assertThat(trainDates).hasSize(5); assertThat(trainDates.get("1.0.0-M1")).isEqualTo(LocalDate.of(2022, 7, 12)); assertThat(trainDates.get("1.0.0-M2")).isEqualTo(LocalDate.of(2022, 8, 9)); assertThat(trainDates.get("1.0.0-M3")).isEqualTo(LocalDate.of(2022, 9, 13)); assertThat(trainDates.get("1.0.0-RC1")).isEqualTo(LocalDate.of(2022, 10, 11)); assertThat(trainDates.get("1.0.0")).isEqualTo(LocalDate.of(2022, 11, 15)); } @Test public void getTrainDatesWhenTrainOneIsThirdMondayOf2022ThenSuccess() { SpringReleaseTrainSpec releaseTrainSpec = SpringReleaseTrainSpec.builder() .train(1) .version("1.0.0") .weekOfMonth(3) .dayOfWeek(1) .year(2022) .build(); SpringReleaseTrain releaseTrain = new SpringReleaseTrain(releaseTrainSpec); Map<String, LocalDate> trainDates = releaseTrain.getTrainDates(); assertThat(trainDates).hasSize(5); assertThat(trainDates.get("1.0.0-M1")).isEqualTo(LocalDate.of(2022, 1, 17)); assertThat(trainDates.get("1.0.0-M2")).isEqualTo(LocalDate.of(2022, 2, 21)); assertThat(trainDates.get("1.0.0-M3")).isEqualTo(LocalDate.of(2022, 3, 21)); assertThat(trainDates.get("1.0.0-RC1")).isEqualTo(LocalDate.of(2022, 4, 18)); assertThat(trainDates.get("1.0.0")).isEqualTo(LocalDate.of(2022, 5, 16)); } @Test public void getTrainDatesWhenTrainTwoIsThirdMondayOf2022ThenSuccess() { SpringReleaseTrainSpec releaseTrainSpec = SpringReleaseTrainSpec.builder() .train(2) .version("1.0.0") .weekOfMonth(3) .dayOfWeek(1) .year(2022) .build(); SpringReleaseTrain releaseTrain = new SpringReleaseTrain(releaseTrainSpec); Map<String, LocalDate> trainDates = releaseTrain.getTrainDates(); assertThat(trainDates).hasSize(5); assertThat(trainDates.get("1.0.0-M1")).isEqualTo(LocalDate.of(2022, 7, 18)); assertThat(trainDates.get("1.0.0-M2")).isEqualTo(LocalDate.of(2022, 8, 15)); assertThat(trainDates.get("1.0.0-M3")).isEqualTo(LocalDate.of(2022, 9, 19)); assertThat(trainDates.get("1.0.0-RC1")).isEqualTo(LocalDate.of(2022, 10, 17)); assertThat(trainDates.get("1.0.0")).isEqualTo(LocalDate.of(2022, 11, 21)); } @Test public void isTrainDateWhenTrainOneIsThirdMondayOf2022ThenSuccess() { SpringReleaseTrainSpec releaseTrainSpec = SpringReleaseTrainSpec.builder() .train(1) .version("1.0.0") .weekOfMonth(3) .dayOfWeek(1) .year(2022) .build(); SpringReleaseTrain releaseTrain = new SpringReleaseTrain(releaseTrainSpec); for (int dayOfMonth = 1; dayOfMonth <= 31; dayOfMonth++) { assertThat(releaseTrain.isTrainDate("1.0.0-M1", LocalDate.of(2022, 1, dayOfMonth))).isEqualTo(dayOfMonth == 17); } for (int dayOfMonth = 1; dayOfMonth <= 28; dayOfMonth++) { assertThat(releaseTrain.isTrainDate("1.0.0-M2", LocalDate.of(2022, 2, dayOfMonth))).isEqualTo(dayOfMonth == 21); } for (int dayOfMonth = 1; dayOfMonth <= 31; dayOfMonth++) { assertThat(releaseTrain.isTrainDate("1.0.0-M3", LocalDate.of(2022, 3, dayOfMonth))).isEqualTo(dayOfMonth == 21); } for (int dayOfMonth = 1; dayOfMonth <= 30; dayOfMonth++) { assertThat(releaseTrain.isTrainDate("1.0.0-RC1", LocalDate.of(2022, 4, dayOfMonth))).isEqualTo(dayOfMonth == 18); } for (int dayOfMonth = 1; dayOfMonth <= 31; dayOfMonth++) { assertThat(releaseTrain.isTrainDate("1.0.0", LocalDate.of(2022, 5, dayOfMonth))).isEqualTo(dayOfMonth == 16); } } @ParameterizedTest @CsvSource({ "2022-01-01, 2022-02-21", "2022-02-01, 2022-02-21", "2022-02-21, 2022-04-18", "2022-03-01, 2022-04-18", "2022-04-01, 2022-04-18", "2022-04-18, 2022-06-20", "2022-05-01, 2022-06-20", "2022-06-01, 2022-06-20", "2022-06-20, 2022-08-15", "2022-07-01, 2022-08-15", "2022-08-01, 2022-08-15", "2022-08-15, 2022-10-17", "2022-09-01, 2022-10-17", "2022-10-01, 2022-10-17", "2022-10-17, 2022-12-19", "2022-11-01, 2022-12-19", "2022-12-01, 2022-12-19", "2022-12-19, 2023-02-20" }) public void getNextReleaseDateWhenBoundaryConditionsThenSuccess(LocalDate startDate, LocalDate expectedDate) { SpringReleaseTrainSpec releaseTrainSpec = SpringReleaseTrainSpec.builder() .train(1) .version("1.0.0") .weekOfMonth(3) .dayOfWeek(1) .year(2022) .build(); SpringReleaseTrain releaseTrain = new SpringReleaseTrain(releaseTrainSpec); assertThat(releaseTrain.getNextReleaseDate(startDate)).isEqualTo(expectedDate); } }
9,217
36.471545
118
java
null
spring-security-main/buildSrc/src/test/java/org/springframework/gradle/github/milestones/GitHubMilestoneApiTests.java
package org.springframework.gradle.github.milestones; import java.nio.charset.Charset; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.util.concurrent.TimeUnit; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.gradle.github.RepositoryRef; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class GitHubMilestoneApiTests { private GitHubMilestoneApi github; private RepositoryRef repositoryRef = RepositoryRef.owner("spring-projects").repository("spring-security").build(); private MockWebServer server; private String baseUrl; @BeforeEach public void setup() throws Exception { this.server = new MockWebServer(); this.server.start(); this.github = new GitHubMilestoneApi("mock-oauth-token"); this.baseUrl = this.server.url("/api").toString(); this.github.setBaseUrl(this.baseUrl); } @AfterEach public void cleanup() throws Exception { this.server.shutdown(); } @Test public void findMilestoneNumberByTitleWhenFoundThenSuccess() throws Exception { String responseJson = "[\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/207\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207/labels\",\n" + " \"id\":6611880,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNjYxMTg4MA==\",\n" + " \"number\":207,\n" + " \"title\":\"5.6.x\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jgrandja\",\n" + " \"id\":10884212,\n" + " \"node_id\":\"MDQ6VXNlcjEwODg0MjEy\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/10884212?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jgrandja\",\n" + " \"html_url\":\"https://github.com/jgrandja\",\n" + " \"followers_url\":\"https://api.github.com/users/jgrandja/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jgrandja/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jgrandja/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jgrandja/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jgrandja/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jgrandja/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jgrandja/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jgrandja/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jgrandja/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":1,\n" + " \"closed_issues\":0,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2021-03-31T11:29:17Z\",\n" + " \"updated_at\":\"2021-03-31T11:30:47Z\",\n" + " \"due_on\":null,\n" + " \"closed_at\":null\n" + " },\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/191\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191/labels\",\n" + " \"id\":5884208,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNTg4NDIwOA==\",\n" + " \"number\":191,\n" + " \"title\":\"5.5.0-RC1\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jzheaux\",\n" + " \"id\":3627351,\n" + " \"node_id\":\"MDQ6VXNlcjM2MjczNTE=\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/3627351?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jzheaux\",\n" + " \"html_url\":\"https://github.com/jzheaux\",\n" + " \"followers_url\":\"https://api.github.com/users/jzheaux/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jzheaux/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jzheaux/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jzheaux/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jzheaux/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jzheaux/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jzheaux/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jzheaux/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jzheaux/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":21,\n" + " \"closed_issues\":23,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2020-09-16T13:28:03Z\",\n" + " \"updated_at\":\"2021-04-06T23:47:10Z\",\n" + " \"due_on\":\"2021-04-12T07:00:00Z\",\n" + " \"closed_at\":null\n" + " }\n" + "]"; this.server.enqueue(new MockResponse().setBody(responseJson)); long milestoneNumberByTitle = this.github.findMilestoneNumberByTitle(this.repositoryRef, "5.5.0-RC1"); RecordedRequest recordedRequest = this.server.takeRequest(1, TimeUnit.SECONDS); assertThat(recordedRequest.getMethod()).isEqualToIgnoringCase("get"); assertThat(recordedRequest.getRequestUrl().toString()).isEqualTo(this.baseUrl + "/repos/spring-projects/spring-security/milestones?per_page=100"); assertThat(milestoneNumberByTitle).isEqualTo(191); } @Test public void findMilestoneNumberByTitleWhenNotFoundThenException() throws Exception { String responseJson = "[\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/207\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207/labels\",\n" + " \"id\":6611880,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNjYxMTg4MA==\",\n" + " \"number\":207,\n" + " \"title\":\"5.6.x\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jgrandja\",\n" + " \"id\":10884212,\n" + " \"node_id\":\"MDQ6VXNlcjEwODg0MjEy\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/10884212?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jgrandja\",\n" + " \"html_url\":\"https://github.com/jgrandja\",\n" + " \"followers_url\":\"https://api.github.com/users/jgrandja/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jgrandja/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jgrandja/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jgrandja/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jgrandja/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jgrandja/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jgrandja/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jgrandja/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jgrandja/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":1,\n" + " \"closed_issues\":0,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2021-03-31T11:29:17Z\",\n" + " \"updated_at\":\"2021-03-31T11:30:47Z\",\n" + " \"due_on\":null,\n" + " \"closed_at\":null\n" + " },\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/191\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191/labels\",\n" + " \"id\":5884208,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNTg4NDIwOA==\",\n" + " \"number\":191,\n" + " \"title\":\"5.5.0-RC1\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jzheaux\",\n" + " \"id\":3627351,\n" + " \"node_id\":\"MDQ6VXNlcjM2MjczNTE=\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/3627351?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jzheaux\",\n" + " \"html_url\":\"https://github.com/jzheaux\",\n" + " \"followers_url\":\"https://api.github.com/users/jzheaux/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jzheaux/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jzheaux/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jzheaux/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jzheaux/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jzheaux/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jzheaux/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jzheaux/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jzheaux/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":21,\n" + " \"closed_issues\":23,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2020-09-16T13:28:03Z\",\n" + " \"updated_at\":\"2021-04-06T23:47:10Z\",\n" + " \"due_on\":\"2021-04-12T07:00:00Z\",\n" + " \"closed_at\":null\n" + " }\n" + "]"; this.server.enqueue(new MockResponse().setBody(responseJson)); assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> this.github.findMilestoneNumberByTitle(this.repositoryRef, "missing")); } @Test public void isOpenIssuesForMilestoneNumberWhenAllClosedThenFalse() throws Exception { String responseJson = "[]"; long milestoneNumber = 202; this.server.enqueue(new MockResponse().setBody(responseJson)); assertThat(this.github.isOpenIssuesForMilestoneNumber(this.repositoryRef, milestoneNumber)).isFalse(); RecordedRequest recordedRequest = this.server.takeRequest(1, TimeUnit.SECONDS); assertThat(recordedRequest.getMethod()).isEqualToIgnoringCase("get"); assertThat(recordedRequest.getRequestUrl().toString()).isEqualTo(this.baseUrl + "/repos/spring-projects/spring-security/issues?per_page=1&milestone=" + milestoneNumber); } @Test public void isOpenIssuesForMilestoneNumberWhenOpenIssuesThenTrue() throws Exception { String responseJson = "[\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/issues/9562\",\n" + " \"repository_url\":\"https://api.github.com/repos/spring-projects/spring-security\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/issues/9562/labels{/name}\",\n" + " \"comments_url\":\"https://api.github.com/repos/spring-projects/spring-security/issues/9562/comments\",\n" + " \"events_url\":\"https://api.github.com/repos/spring-projects/spring-security/issues/9562/events\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/pull/9562\",\n" + " \"id\":851886504,\n" + " \"node_id\":\"MDExOlB1bGxSZXF1ZXN0NjEwMjMzMDcw\",\n" + " \"number\":9562,\n" + " \"title\":\"Add package-list\",\n" + " \"user\":{\n" + " \"login\":\"jzheaux\",\n" + " \"id\":3627351,\n" + " \"node_id\":\"MDQ6VXNlcjM2MjczNTE=\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/3627351?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jzheaux\",\n" + " \"html_url\":\"https://github.com/jzheaux\",\n" + " \"followers_url\":\"https://api.github.com/users/jzheaux/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jzheaux/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jzheaux/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jzheaux/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jzheaux/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jzheaux/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jzheaux/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jzheaux/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jzheaux/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"labels\":[\n" + " {\n" + " \"id\":322225043,\n" + " \"node_id\":\"MDU6TGFiZWwzMjIyMjUwNDM=\",\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/labels/in:%20build\",\n" + " \"name\":\"in: build\",\n" + " \"color\":\"e8f9de\",\n" + " \"default\":false,\n" + " \"description\":\"An issue in the build\"\n" + " },\n" + " {\n" + " \"id\":322225079,\n" + " \"node_id\":\"MDU6TGFiZWwzMjIyMjUwNzk=\",\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/labels/type:%20bug\",\n" + " \"name\":\"type: bug\",\n" + " \"color\":\"e3d9fc\",\n" + " \"default\":false,\n" + " \"description\":\"A general bug\"\n" + " }\n" + " ],\n" + " \"state\":\"open\",\n" + " \"locked\":false,\n" + " \"assignee\":{\n" + " \"login\":\"rwinch\",\n" + " \"id\":362503,\n" + " \"node_id\":\"MDQ6VXNlcjM2MjUwMw==\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/362503?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/rwinch\",\n" + " \"html_url\":\"https://github.com/rwinch\",\n" + " \"followers_url\":\"https://api.github.com/users/rwinch/followers\",\n" + " \"following_url\":\"https://api.github.com/users/rwinch/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/rwinch/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/rwinch/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/rwinch/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/rwinch/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/rwinch/repos\",\n" + " \"events_url\":\"https://api.github.com/users/rwinch/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/rwinch/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"assignees\":[\n" + " {\n" + " \"login\":\"rwinch\",\n" + " \"id\":362503,\n" + " \"node_id\":\"MDQ6VXNlcjM2MjUwMw==\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/362503?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/rwinch\",\n" + " \"html_url\":\"https://github.com/rwinch\",\n" + " \"followers_url\":\"https://api.github.com/users/rwinch/followers\",\n" + " \"following_url\":\"https://api.github.com/users/rwinch/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/rwinch/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/rwinch/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/rwinch/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/rwinch/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/rwinch/repos\",\n" + " \"events_url\":\"https://api.github.com/users/rwinch/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/rwinch/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " }\n" + " ],\n" + " \"milestone\":{\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/191\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191/labels\",\n" + " \"id\":5884208,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNTg4NDIwOA==\",\n" + " \"number\":191,\n" + " \"title\":\"5.5.0-RC1\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jzheaux\",\n" + " \"id\":3627351,\n" + " \"node_id\":\"MDQ6VXNlcjM2MjczNTE=\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/3627351?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jzheaux\",\n" + " \"html_url\":\"https://github.com/jzheaux\",\n" + " \"followers_url\":\"https://api.github.com/users/jzheaux/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jzheaux/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jzheaux/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jzheaux/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jzheaux/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jzheaux/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jzheaux/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jzheaux/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jzheaux/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":21,\n" + " \"closed_issues\":23,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2020-09-16T13:28:03Z\",\n" + " \"updated_at\":\"2021-04-06T23:47:10Z\",\n" + " \"due_on\":\"2021-04-12T07:00:00Z\",\n" + " \"closed_at\":null\n" + " },\n" + " \"comments\":0,\n" + " \"created_at\":\"2021-04-06T23:47:10Z\",\n" + " \"updated_at\":\"2021-04-07T17:00:00Z\",\n" + " \"closed_at\":null,\n" + " \"author_association\":\"MEMBER\",\n" + " \"active_lock_reason\":null,\n" + " \"pull_request\":{\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/pulls/9562\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/pull/9562\",\n" + " \"diff_url\":\"https://github.com/spring-projects/spring-security/pull/9562.diff\",\n" + " \"patch_url\":\"https://github.com/spring-projects/spring-security/pull/9562.patch\"\n" + " },\n" + " \"body\":\"Closes gh-9528\\r\\n\\r\\n<!--\\r\\nFor Security Vulnerabilities, please use https://pivotal.io/security#reporting\\r\\n-->\\r\\n\\r\\n<!--\\r\\nBefore creating new features, we recommend creating an issue to discuss the feature. This ensures that everyone is on the same page before extensive work is done.\\r\\n\\r\\nThanks for contributing to Spring Security. Please provide a brief description of your pull-request and reference any related issue numbers (prefix references with gh-).\\r\\n-->\\r\\n\",\n" + " \"performed_via_github_app\":null\n" + " }\n" + "]"; long milestoneNumber = 191; this.server.enqueue(new MockResponse().setBody(responseJson)); assertThat(this.github.isOpenIssuesForMilestoneNumber(this.repositoryRef, milestoneNumber)).isTrue(); RecordedRequest recordedRequest = this.server.takeRequest(1, TimeUnit.SECONDS); assertThat(recordedRequest.getMethod()).isEqualToIgnoringCase("get"); assertThat(recordedRequest.getRequestUrl().toString()).isEqualTo(this.baseUrl + "/repos/spring-projects/spring-security/issues?per_page=1&milestone=" + milestoneNumber); } @Test public void isMilestoneDueTodayWhenNotFoundThenException() throws Exception { String responseJson = "[\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/207\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207/labels\",\n" + " \"id\":6611880,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNjYxMTg4MA==\",\n" + " \"number\":207,\n" + " \"title\":\"5.6.x\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jgrandja\",\n" + " \"id\":10884212,\n" + " \"node_id\":\"MDQ6VXNlcjEwODg0MjEy\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/10884212?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jgrandja\",\n" + " \"html_url\":\"https://github.com/jgrandja\",\n" + " \"followers_url\":\"https://api.github.com/users/jgrandja/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jgrandja/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jgrandja/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jgrandja/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jgrandja/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jgrandja/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jgrandja/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jgrandja/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jgrandja/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":1,\n" + " \"closed_issues\":0,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2021-03-31T11:29:17Z\",\n" + " \"updated_at\":\"2021-03-31T11:30:47Z\",\n" + " \"due_on\":null,\n" + " \"closed_at\":null\n" + " },\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/191\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191/labels\",\n" + " \"id\":5884208,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNTg4NDIwOA==\",\n" + " \"number\":191,\n" + " \"title\":\"5.5.0-RC1\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jzheaux\",\n" + " \"id\":3627351,\n" + " \"node_id\":\"MDQ6VXNlcjM2MjczNTE=\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/3627351?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jzheaux\",\n" + " \"html_url\":\"https://github.com/jzheaux\",\n" + " \"followers_url\":\"https://api.github.com/users/jzheaux/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jzheaux/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jzheaux/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jzheaux/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jzheaux/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jzheaux/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jzheaux/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jzheaux/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jzheaux/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":21,\n" + " \"closed_issues\":23,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2020-09-16T13:28:03Z\",\n" + " \"updated_at\":\"2021-04-06T23:47:10Z\",\n" + " \"due_on\":\"2021-04-12T07:00:00Z\",\n" + " \"closed_at\":null\n" + " }\n" + "]"; this.server.enqueue(new MockResponse().setBody(responseJson)); assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> this.github.isMilestoneDueToday(this.repositoryRef, "missing")); } @Test public void isMilestoneDueTodayWhenPastDueThenTrue() throws Exception { String responseJson = "[\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/207\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207/labels\",\n" + " \"id\":6611880,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNjYxMTg4MA==\",\n" + " \"number\":207,\n" + " \"title\":\"5.6.x\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jgrandja\",\n" + " \"id\":10884212,\n" + " \"node_id\":\"MDQ6VXNlcjEwODg0MjEy\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/10884212?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jgrandja\",\n" + " \"html_url\":\"https://github.com/jgrandja\",\n" + " \"followers_url\":\"https://api.github.com/users/jgrandja/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jgrandja/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jgrandja/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jgrandja/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jgrandja/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jgrandja/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jgrandja/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jgrandja/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jgrandja/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":1,\n" + " \"closed_issues\":0,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2021-03-31T11:29:17Z\",\n" + " \"updated_at\":\"2021-03-31T11:30:47Z\",\n" + " \"due_on\":null,\n" + " \"closed_at\":null\n" + " },\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/191\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191/labels\",\n" + " \"id\":5884208,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNTg4NDIwOA==\",\n" + " \"number\":191,\n" + " \"title\":\"5.5.0-RC1\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jzheaux\",\n" + " \"id\":3627351,\n" + " \"node_id\":\"MDQ6VXNlcjM2MjczNTE=\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/3627351?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jzheaux\",\n" + " \"html_url\":\"https://github.com/jzheaux\",\n" + " \"followers_url\":\"https://api.github.com/users/jzheaux/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jzheaux/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jzheaux/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jzheaux/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jzheaux/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jzheaux/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jzheaux/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jzheaux/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jzheaux/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":21,\n" + " \"closed_issues\":23,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2020-09-16T13:28:03Z\",\n" + " \"updated_at\":\"2021-04-06T23:47:10Z\",\n" + " \"due_on\":\"2021-04-12T07:00:00Z\",\n" + " \"closed_at\":null\n" + " }\n" + "]"; this.server.enqueue(new MockResponse().setBody(responseJson)); boolean dueToday = this.github.isMilestoneDueToday(this.repositoryRef, "5.5.0-RC1"); RecordedRequest recordedRequest = this.server.takeRequest(1, TimeUnit.SECONDS); assertThat(recordedRequest.getMethod()).isEqualToIgnoringCase("get"); assertThat(recordedRequest.getRequestUrl().toString()).isEqualTo(this.baseUrl + "/repos/spring-projects/spring-security/milestones?per_page=100"); assertThat(dueToday).isTrue(); } @Test public void isMilestoneDueTodayWhenDueTodayThenTrue() throws Exception { String responseJson = "[\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/207\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207/labels\",\n" + " \"id\":6611880,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNjYxMTg4MA==\",\n" + " \"number\":207,\n" + " \"title\":\"5.6.x\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jgrandja\",\n" + " \"id\":10884212,\n" + " \"node_id\":\"MDQ6VXNlcjEwODg0MjEy\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/10884212?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jgrandja\",\n" + " \"html_url\":\"https://github.com/jgrandja\",\n" + " \"followers_url\":\"https://api.github.com/users/jgrandja/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jgrandja/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jgrandja/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jgrandja/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jgrandja/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jgrandja/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jgrandja/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jgrandja/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jgrandja/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":1,\n" + " \"closed_issues\":0,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2021-03-31T11:29:17Z\",\n" + " \"updated_at\":\"2021-03-31T11:30:47Z\",\n" + " \"due_on\":null,\n" + " \"closed_at\":null\n" + " },\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/191\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191/labels\",\n" + " \"id\":5884208,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNTg4NDIwOA==\",\n" + " \"number\":191,\n" + " \"title\":\"5.5.0-RC1\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jzheaux\",\n" + " \"id\":3627351,\n" + " \"node_id\":\"MDQ6VXNlcjM2MjczNTE=\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/3627351?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jzheaux\",\n" + " \"html_url\":\"https://github.com/jzheaux\",\n" + " \"followers_url\":\"https://api.github.com/users/jzheaux/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jzheaux/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jzheaux/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jzheaux/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jzheaux/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jzheaux/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jzheaux/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jzheaux/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jzheaux/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":21,\n" + " \"closed_issues\":23,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2020-09-16T13:28:03Z\",\n" + " \"updated_at\":\"2021-04-06T23:47:10Z\",\n" + " \"due_on\":\"" + LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant().toString() + "\",\n" + " \"closed_at\":null\n" + " }\n" + "]"; this.server.enqueue(new MockResponse().setBody(responseJson)); boolean dueToday = this.github.isMilestoneDueToday(this.repositoryRef, "5.5.0-RC1"); RecordedRequest recordedRequest = this.server.takeRequest(1, TimeUnit.SECONDS); assertThat(recordedRequest.getMethod()).isEqualToIgnoringCase("get"); assertThat(recordedRequest.getRequestUrl().toString()).isEqualTo(this.baseUrl + "/repos/spring-projects/spring-security/milestones?per_page=100"); assertThat(dueToday).isTrue(); } @Test public void isMilestoneDueTodayWhenNoDueDateThenFalse() throws Exception { String responseJson = "[\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/207\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207/labels\",\n" + " \"id\":6611880,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNjYxMTg4MA==\",\n" + " \"number\":207,\n" + " \"title\":\"5.6.x\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jgrandja\",\n" + " \"id\":10884212,\n" + " \"node_id\":\"MDQ6VXNlcjEwODg0MjEy\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/10884212?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jgrandja\",\n" + " \"html_url\":\"https://github.com/jgrandja\",\n" + " \"followers_url\":\"https://api.github.com/users/jgrandja/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jgrandja/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jgrandja/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jgrandja/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jgrandja/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jgrandja/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jgrandja/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jgrandja/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jgrandja/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":1,\n" + " \"closed_issues\":0,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2021-03-31T11:29:17Z\",\n" + " \"updated_at\":\"2021-03-31T11:30:47Z\",\n" + " \"due_on\":null,\n" + " \"closed_at\":null\n" + " },\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/191\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191/labels\",\n" + " \"id\":5884208,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNTg4NDIwOA==\",\n" + " \"number\":191,\n" + " \"title\":\"5.5.0-RC1\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jzheaux\",\n" + " \"id\":3627351,\n" + " \"node_id\":\"MDQ6VXNlcjM2MjczNTE=\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/3627351?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jzheaux\",\n" + " \"html_url\":\"https://github.com/jzheaux\",\n" + " \"followers_url\":\"https://api.github.com/users/jzheaux/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jzheaux/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jzheaux/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jzheaux/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jzheaux/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jzheaux/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jzheaux/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jzheaux/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jzheaux/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":21,\n" + " \"closed_issues\":23,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2020-09-16T13:28:03Z\",\n" + " \"updated_at\":\"2021-04-06T23:47:10Z\",\n" + " \"due_on\":null,\n" + " \"closed_at\":null\n" + " }\n" + "]"; this.server.enqueue(new MockResponse().setBody(responseJson)); boolean dueToday = this.github.isMilestoneDueToday(this.repositoryRef, "5.5.0-RC1"); RecordedRequest recordedRequest = this.server.takeRequest(1, TimeUnit.SECONDS); assertThat(recordedRequest.getMethod()).isEqualToIgnoringCase("get"); assertThat(recordedRequest.getRequestUrl().toString()).isEqualTo(this.baseUrl + "/repos/spring-projects/spring-security/milestones?per_page=100"); assertThat(dueToday).isFalse(); } @Test public void isMilestoneDueTodayWhenDueDateInFutureThenFalse() throws Exception { String responseJson = "[\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/207\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207/labels\",\n" + " \"id\":6611880,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNjYxMTg4MA==\",\n" + " \"number\":207,\n" + " \"title\":\"5.6.x\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jgrandja\",\n" + " \"id\":10884212,\n" + " \"node_id\":\"MDQ6VXNlcjEwODg0MjEy\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/10884212?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jgrandja\",\n" + " \"html_url\":\"https://github.com/jgrandja\",\n" + " \"followers_url\":\"https://api.github.com/users/jgrandja/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jgrandja/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jgrandja/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jgrandja/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jgrandja/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jgrandja/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jgrandja/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jgrandja/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jgrandja/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":1,\n" + " \"closed_issues\":0,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2021-03-31T11:29:17Z\",\n" + " \"updated_at\":\"2021-03-31T11:30:47Z\",\n" + " \"due_on\":null,\n" + " \"closed_at\":null\n" + " },\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/191\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191/labels\",\n" + " \"id\":5884208,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNTg4NDIwOA==\",\n" + " \"number\":191,\n" + " \"title\":\"5.5.0-RC1\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jzheaux\",\n" + " \"id\":3627351,\n" + " \"node_id\":\"MDQ6VXNlcjM2MjczNTE=\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/3627351?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jzheaux\",\n" + " \"html_url\":\"https://github.com/jzheaux\",\n" + " \"followers_url\":\"https://api.github.com/users/jzheaux/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jzheaux/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jzheaux/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jzheaux/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jzheaux/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jzheaux/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jzheaux/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jzheaux/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jzheaux/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":21,\n" + " \"closed_issues\":23,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2020-09-16T13:28:03Z\",\n" + " \"updated_at\":\"2021-04-06T23:47:10Z\",\n" + " \"due_on\":\"3000-04-12T07:00:00Z\",\n" + " \"closed_at\":null\n" + " }\n" + "]"; this.server.enqueue(new MockResponse().setBody(responseJson)); boolean dueToday = this.github.isMilestoneDueToday(this.repositoryRef, "5.5.0-RC1"); RecordedRequest recordedRequest = this.server.takeRequest(1, TimeUnit.SECONDS); assertThat(recordedRequest.getMethod()).isEqualToIgnoringCase("get"); assertThat(recordedRequest.getRequestUrl().toString()).isEqualTo(this.baseUrl + "/repos/spring-projects/spring-security/milestones?per_page=100"); assertThat(dueToday).isFalse(); } @Test public void calculateNextReleaseMilestoneWhenCurrentVersionIsNotSnapshotThenException() { assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> this.github.getNextReleaseMilestone(this.repositoryRef, "5.5.0-RC1")); } @Test public void calculateNextReleaseMilestoneWhenPatchSegmentGreaterThan0ThenReturnsVersionWithoutSnapshot() { String nextVersion = this.github.getNextReleaseMilestone(this.repositoryRef, "5.5.1-SNAPSHOT"); assertThat(nextVersion).isEqualTo("5.5.1"); } @Test public void calculateNextReleaseMilestoneWhenMilestoneAndRcExistThenReturnsMilestone() throws Exception { String responseJson = "[\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/207\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207/labels\",\n" + " \"id\":6611880,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNjYxMTg4MA==\",\n" + " \"number\":207,\n" + " \"title\":\"5.5.0-M1\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jgrandja\",\n" + " \"id\":10884212,\n" + " \"node_id\":\"MDQ6VXNlcjEwODg0MjEy\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/10884212?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jgrandja\",\n" + " \"html_url\":\"https://github.com/jgrandja\",\n" + " \"followers_url\":\"https://api.github.com/users/jgrandja/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jgrandja/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jgrandja/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jgrandja/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jgrandja/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jgrandja/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jgrandja/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jgrandja/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jgrandja/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":1,\n" + " \"closed_issues\":0,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2021-03-31T11:29:17Z\",\n" + " \"updated_at\":\"2021-03-31T11:30:47Z\",\n" + " \"due_on\":null,\n" + " \"closed_at\":null\n" + " },\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/191\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191/labels\",\n" + " \"id\":5884208,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNTg4NDIwOA==\",\n" + " \"number\":191,\n" + " \"title\":\"5.5.0-RC1\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jzheaux\",\n" + " \"id\":3627351,\n" + " \"node_id\":\"MDQ6VXNlcjM2MjczNTE=\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/3627351?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jzheaux\",\n" + " \"html_url\":\"https://github.com/jzheaux\",\n" + " \"followers_url\":\"https://api.github.com/users/jzheaux/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jzheaux/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jzheaux/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jzheaux/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jzheaux/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jzheaux/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jzheaux/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jzheaux/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jzheaux/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":21,\n" + " \"closed_issues\":23,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2020-09-16T13:28:03Z\",\n" + " \"updated_at\":\"2021-04-06T23:47:10Z\",\n" + " \"due_on\":\"3000-04-12T07:00:00Z\",\n" + " \"closed_at\":null\n" + " }\n" + "]"; this.server.enqueue(new MockResponse().setBody(responseJson)); String nextVersion = this.github.getNextReleaseMilestone(this.repositoryRef, "5.5.0-SNAPSHOT"); RecordedRequest recordedRequest = this.server.takeRequest(1, TimeUnit.SECONDS); assertThat(recordedRequest.getMethod()).isEqualToIgnoringCase("get"); assertThat(recordedRequest.getRequestUrl().toString()).isEqualTo(this.baseUrl + "/repos/spring-projects/spring-security/milestones?per_page=100"); assertThat(nextVersion).isEqualTo("5.5.0-M1"); } @Test public void calculateNextReleaseMilestoneWhenTwoMilestonesExistThenReturnsSmallerMilestone() throws Exception { String responseJson = "[\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/207\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207/labels\",\n" + " \"id\":6611880,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNjYxMTg4MA==\",\n" + " \"number\":207,\n" + " \"title\":\"5.5.0-M9\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jgrandja\",\n" + " \"id\":10884212,\n" + " \"node_id\":\"MDQ6VXNlcjEwODg0MjEy\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/10884212?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jgrandja\",\n" + " \"html_url\":\"https://github.com/jgrandja\",\n" + " \"followers_url\":\"https://api.github.com/users/jgrandja/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jgrandja/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jgrandja/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jgrandja/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jgrandja/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jgrandja/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jgrandja/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jgrandja/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jgrandja/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":1,\n" + " \"closed_issues\":0,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2021-03-31T11:29:17Z\",\n" + " \"updated_at\":\"2021-03-31T11:30:47Z\",\n" + " \"due_on\":null,\n" + " \"closed_at\":null\n" + " },\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/191\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191/labels\",\n" + " \"id\":5884208,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNTg4NDIwOA==\",\n" + " \"number\":191,\n" + " \"title\":\"5.5.0-M10\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jzheaux\",\n" + " \"id\":3627351,\n" + " \"node_id\":\"MDQ6VXNlcjM2MjczNTE=\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/3627351?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jzheaux\",\n" + " \"html_url\":\"https://github.com/jzheaux\",\n" + " \"followers_url\":\"https://api.github.com/users/jzheaux/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jzheaux/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jzheaux/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jzheaux/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jzheaux/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jzheaux/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jzheaux/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jzheaux/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jzheaux/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":21,\n" + " \"closed_issues\":23,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2020-09-16T13:28:03Z\",\n" + " \"updated_at\":\"2021-04-06T23:47:10Z\",\n" + " \"due_on\":\"3000-04-12T07:00:00Z\",\n" + " \"closed_at\":null\n" + " }\n" + "]"; this.server.enqueue(new MockResponse().setBody(responseJson)); String nextVersion = this.github.getNextReleaseMilestone(this.repositoryRef, "5.5.0-SNAPSHOT"); RecordedRequest recordedRequest = this.server.takeRequest(1, TimeUnit.SECONDS); assertThat(recordedRequest.getMethod()).isEqualToIgnoringCase("get"); assertThat(recordedRequest.getRequestUrl().toString()).isEqualTo(this.baseUrl + "/repos/spring-projects/spring-security/milestones?per_page=100"); assertThat(nextVersion).isEqualTo("5.5.0-M9"); } @Test public void calculateNextReleaseMilestoneWhenTwoRcsExistThenReturnsSmallerRc() throws Exception { String responseJson = "[\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/207\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207/labels\",\n" + " \"id\":6611880,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNjYxMTg4MA==\",\n" + " \"number\":207,\n" + " \"title\":\"5.5.0-RC9\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jgrandja\",\n" + " \"id\":10884212,\n" + " \"node_id\":\"MDQ6VXNlcjEwODg0MjEy\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/10884212?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jgrandja\",\n" + " \"html_url\":\"https://github.com/jgrandja\",\n" + " \"followers_url\":\"https://api.github.com/users/jgrandja/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jgrandja/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jgrandja/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jgrandja/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jgrandja/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jgrandja/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jgrandja/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jgrandja/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jgrandja/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":1,\n" + " \"closed_issues\":0,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2021-03-31T11:29:17Z\",\n" + " \"updated_at\":\"2021-03-31T11:30:47Z\",\n" + " \"due_on\":null,\n" + " \"closed_at\":null\n" + " },\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/191\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191/labels\",\n" + " \"id\":5884208,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNTg4NDIwOA==\",\n" + " \"number\":191,\n" + " \"title\":\"5.5.0-RC10\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jzheaux\",\n" + " \"id\":3627351,\n" + " \"node_id\":\"MDQ6VXNlcjM2MjczNTE=\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/3627351?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jzheaux\",\n" + " \"html_url\":\"https://github.com/jzheaux\",\n" + " \"followers_url\":\"https://api.github.com/users/jzheaux/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jzheaux/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jzheaux/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jzheaux/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jzheaux/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jzheaux/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jzheaux/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jzheaux/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jzheaux/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":21,\n" + " \"closed_issues\":23,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2020-09-16T13:28:03Z\",\n" + " \"updated_at\":\"2021-04-06T23:47:10Z\",\n" + " \"due_on\":\"3000-04-12T07:00:00Z\",\n" + " \"closed_at\":null\n" + " }\n" + "]"; this.server.enqueue(new MockResponse().setBody(responseJson)); String nextVersion = this.github.getNextReleaseMilestone(this.repositoryRef, "5.5.0-SNAPSHOT"); RecordedRequest recordedRequest = this.server.takeRequest(1, TimeUnit.SECONDS); assertThat(recordedRequest.getMethod()).isEqualToIgnoringCase("get"); assertThat(recordedRequest.getRequestUrl().toString()).isEqualTo(this.baseUrl + "/repos/spring-projects/spring-security/milestones?per_page=100"); assertThat(nextVersion).isEqualTo("5.5.0-RC9"); } @Test public void calculateNextReleaseMilestoneWhenNoPreReleaseThenReturnsVersionWithoutSnapshot() throws Exception { String responseJson = "[\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/207\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/207/labels\",\n" + " \"id\":6611880,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNjYxMTg4MA==\",\n" + " \"number\":207,\n" + " \"title\":\"5.6.x\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jgrandja\",\n" + " \"id\":10884212,\n" + " \"node_id\":\"MDQ6VXNlcjEwODg0MjEy\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/10884212?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jgrandja\",\n" + " \"html_url\":\"https://github.com/jgrandja\",\n" + " \"followers_url\":\"https://api.github.com/users/jgrandja/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jgrandja/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jgrandja/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jgrandja/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jgrandja/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jgrandja/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jgrandja/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jgrandja/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jgrandja/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":1,\n" + " \"closed_issues\":0,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2021-03-31T11:29:17Z\",\n" + " \"updated_at\":\"2021-03-31T11:30:47Z\",\n" + " \"due_on\":null,\n" + " \"closed_at\":null\n" + " },\n" + " {\n" + " \"url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191\",\n" + " \"html_url\":\"https://github.com/spring-projects/spring-security/milestone/191\",\n" + " \"labels_url\":\"https://api.github.com/repos/spring-projects/spring-security/milestones/191/labels\",\n" + " \"id\":5884208,\n" + " \"node_id\":\"MDk6TWlsZXN0b25lNTg4NDIwOA==\",\n" + " \"number\":191,\n" + " \"title\":\"5.4.3\",\n" + " \"description\":\"\",\n" + " \"creator\":{\n" + " \"login\":\"jzheaux\",\n" + " \"id\":3627351,\n" + " \"node_id\":\"MDQ6VXNlcjM2MjczNTE=\",\n" + " \"avatar_url\":\"https://avatars.githubusercontent.com/u/3627351?v=4\",\n" + " \"gravatar_id\":\"\",\n" + " \"url\":\"https://api.github.com/users/jzheaux\",\n" + " \"html_url\":\"https://github.com/jzheaux\",\n" + " \"followers_url\":\"https://api.github.com/users/jzheaux/followers\",\n" + " \"following_url\":\"https://api.github.com/users/jzheaux/following{/other_user}\",\n" + " \"gists_url\":\"https://api.github.com/users/jzheaux/gists{/gist_id}\",\n" + " \"starred_url\":\"https://api.github.com/users/jzheaux/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\":\"https://api.github.com/users/jzheaux/subscriptions\",\n" + " \"organizations_url\":\"https://api.github.com/users/jzheaux/orgs\",\n" + " \"repos_url\":\"https://api.github.com/users/jzheaux/repos\",\n" + " \"events_url\":\"https://api.github.com/users/jzheaux/events{/privacy}\",\n" + " \"received_events_url\":\"https://api.github.com/users/jzheaux/received_events\",\n" + " \"type\":\"User\",\n" + " \"site_admin\":false\n" + " },\n" + " \"open_issues\":21,\n" + " \"closed_issues\":23,\n" + " \"state\":\"open\",\n" + " \"created_at\":\"2020-09-16T13:28:03Z\",\n" + " \"updated_at\":\"2021-04-06T23:47:10Z\",\n" + " \"due_on\":\"2021-04-12T07:00:00Z\",\n" + " \"closed_at\":null\n" + " }\n" + "]"; this.server.enqueue(new MockResponse().setBody(responseJson)); String nextVersion = this.github.getNextReleaseMilestone(this.repositoryRef, "5.5.0-SNAPSHOT"); RecordedRequest recordedRequest = this.server.takeRequest(1, TimeUnit.SECONDS); assertThat(recordedRequest.getMethod()).isEqualToIgnoringCase("get"); assertThat(recordedRequest.getRequestUrl().toString()).isEqualTo(this.baseUrl + "/repos/spring-projects/spring-security/milestones?per_page=100"); assertThat(nextVersion).isEqualTo("5.5.0"); } @Test public void createMilestoneWhenValidParametersThenSuccess() throws Exception { this.server.enqueue(new MockResponse().setResponseCode(204)); Milestone milestone = new Milestone(); milestone.setTitle("1.0.0"); milestone.setDueOn(LocalDate.of(2022, 5, 4).atTime(LocalTime.NOON)); this.github.createMilestone(this.repositoryRef, milestone); RecordedRequest recordedRequest = this.server.takeRequest(1, TimeUnit.SECONDS); assertThat(recordedRequest.getMethod()).isEqualToIgnoringCase("post"); assertThat(recordedRequest.getRequestUrl().toString()) .isEqualTo(this.baseUrl + "/repos/spring-projects/spring-security/milestones"); assertThat(recordedRequest.getBody().readString(Charset.defaultCharset())) .isEqualTo("{\"title\":\"1.0.0\",\"due_on\":\"2022-05-04T12:00:00Z\"}"); } @Test public void createMilestoneWhenErrorResponseThenException() throws Exception { this.server.enqueue(new MockResponse().setResponseCode(400)); assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> this.github.createMilestone(this.repositoryRef, new Milestone())); } }
69,708
55.812551
533
java
null
spring-security-main/buildSrc/src/test/java/org/springframework/gradle/github/release/GitHubReleaseApiTests.java
/* * Copyright 2002-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.github.release; import java.nio.charset.Charset; import java.util.concurrent.TimeUnit; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.gradle.github.RepositoryRef; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Steve Riesenberg */ public class GitHubReleaseApiTests { private GitHubReleaseApi gitHubReleaseApi; private MockWebServer server; private String baseUrl; private RepositoryRef repository; @BeforeEach public void setup() throws Exception { this.server = new MockWebServer(); this.server.start(); this.baseUrl = this.server.url("/api").toString(); this.gitHubReleaseApi = new GitHubReleaseApi("mock-oauth-token"); this.gitHubReleaseApi.setBaseUrl(this.baseUrl); this.repository = new RepositoryRef("spring-projects", "spring-security"); } @AfterEach public void cleanup() throws Exception { this.server.shutdown(); } @Test public void publishReleaseWhenValidParametersThenSuccess() throws Exception { String responseJson = "{\n" + " \"url\": \"https://api.github.com/spring-projects/spring-security/releases/1\",\n" + " \"html_url\": \"https://github.com/spring-projects/spring-security/releases/tags/v1.0.0\",\n" + " \"assets_url\": \"https://api.github.com/spring-projects/spring-security/releases/1/assets\",\n" + " \"upload_url\": \"https://uploads.github.com/spring-projects/spring-security/releases/1/assets{?name,label}\",\n" + " \"tarball_url\": \"https://api.github.com/spring-projects/spring-security/tarball/v1.0.0\",\n" + " \"zipball_url\": \"https://api.github.com/spring-projects/spring-security/zipball/v1.0.0\",\n" + " \"discussion_url\": \"https://github.com/spring-projects/spring-security/discussions/90\",\n" + " \"id\": 1,\n" + " \"node_id\": \"MDc6UmVsZWFzZTE=\",\n" + " \"tag_name\": \"v1.0.0\",\n" + " \"target_commitish\": \"main\",\n" + " \"name\": \"v1.0.0\",\n" + " \"body\": \"Description of the release\",\n" + " \"draft\": false,\n" + " \"prerelease\": false,\n" + " \"created_at\": \"2013-02-27T19:35:32Z\",\n" + " \"published_at\": \"2013-02-27T19:35:32Z\",\n" + " \"author\": {\n" + " \"login\": \"sjohnr\",\n" + " \"id\": 1,\n" + " \"node_id\": \"MDQ6VXNlcjE=\",\n" + " \"avatar_url\": \"https://github.com/images/avatar.gif\",\n" + " \"gravatar_id\": \"\",\n" + " \"url\": \"https://api.github.com/users/sjohnr\",\n" + " \"html_url\": \"https://github.com/sjohnr\",\n" + " \"followers_url\": \"https://api.github.com/users/sjohnr/followers\",\n" + " \"following_url\": \"https://api.github.com/users/sjohnr/following{/other_user}\",\n" + " \"gists_url\": \"https://api.github.com/users/sjohnr/gists{/gist_id}\",\n" + " \"starred_url\": \"https://api.github.com/users/sjohnr/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\": \"https://api.github.com/users/sjohnr/subscriptions\",\n" + " \"organizations_url\": \"https://api.github.com/users/sjohnr/orgs\",\n" + " \"repos_url\": \"https://api.github.com/users/sjohnr/repos\",\n" + " \"events_url\": \"https://api.github.com/users/sjohnr/events{/privacy}\",\n" + " \"received_events_url\": \"https://api.github.com/users/sjohnr/received_events\",\n" + " \"type\": \"User\",\n" + " \"site_admin\": false\n" + " },\n" + " \"assets\": [\n" + " {\n" + " \"url\": \"https://api.github.com/spring-projects/spring-security/releases/assets/1\",\n" + " \"browser_download_url\": \"https://github.com/spring-projects/spring-security/releases/download/v1.0.0/example.zip\",\n" + " \"id\": 1,\n" + " \"node_id\": \"MDEyOlJlbGVhc2VBc3NldDE=\",\n" + " \"name\": \"example.zip\",\n" + " \"label\": \"short description\",\n" + " \"state\": \"uploaded\",\n" + " \"content_type\": \"application/zip\",\n" + " \"size\": 1024,\n" + " \"download_count\": 42,\n" + " \"created_at\": \"2013-02-27T19:35:32Z\",\n" + " \"updated_at\": \"2013-02-27T19:35:32Z\",\n" + " \"uploader\": {\n" + " \"login\": \"sjohnr\",\n" + " \"id\": 1,\n" + " \"node_id\": \"MDQ6VXNlcjE=\",\n" + " \"avatar_url\": \"https://github.com/images/avatar.gif\",\n" + " \"gravatar_id\": \"\",\n" + " \"url\": \"https://api.github.com/users/sjohnr\",\n" + " \"html_url\": \"https://github.com/sjohnr\",\n" + " \"followers_url\": \"https://api.github.com/users/sjohnr/followers\",\n" + " \"following_url\": \"https://api.github.com/users/sjohnr/following{/other_user}\",\n" + " \"gists_url\": \"https://api.github.com/users/sjohnr/gists{/gist_id}\",\n" + " \"starred_url\": \"https://api.github.com/users/sjohnr/starred{/owner}{/repo}\",\n" + " \"subscriptions_url\": \"https://api.github.com/users/sjohnr/subscriptions\",\n" + " \"organizations_url\": \"https://api.github.com/users/sjohnr/orgs\",\n" + " \"repos_url\": \"https://api.github.com/users/sjohnr/repos\",\n" + " \"events_url\": \"https://api.github.com/users/sjohnr/events{/privacy}\",\n" + " \"received_events_url\": \"https://api.github.com/users/sjohnr/received_events\",\n" + " \"type\": \"User\",\n" + " \"site_admin\": false\n" + " }\n" + " }\n" + " ]\n" + "}"; this.server.enqueue(new MockResponse().setBody(responseJson)); this.gitHubReleaseApi.publishRelease(this.repository, Release.tag("1.0.0").build()); RecordedRequest recordedRequest = this.server.takeRequest(1, TimeUnit.SECONDS); assertThat(recordedRequest.getMethod()).isEqualToIgnoringCase("post"); assertThat(recordedRequest.getRequestUrl().toString()) .isEqualTo(this.baseUrl + "/repos/spring-projects/spring-security/releases"); assertThat(recordedRequest.getBody().readString(Charset.defaultCharset())) .isEqualTo("{\"tag_name\":\"1.0.0\",\"draft\":false,\"prerelease\":false,\"generate_release_notes\":false}"); } @Test public void publishReleaseWhenErrorResponseThenException() throws Exception { this.server.enqueue(new MockResponse().setResponseCode(400)); assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> this.gitHubReleaseApi.publishRelease(this.repository, Release.tag("1.0.0").build())); } }
7,429
46.628205
134
java
null
spring-security-main/buildSrc/src/test/java/org/springframework/gradle/github/release/GitHubActionsApiTests.java
/* * Copyright 2002-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.github.release; import java.nio.charset.Charset; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.gradle.github.RepositoryRef; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Steve Riesenberg */ public class GitHubActionsApiTests { private GitHubActionsApi gitHubActionsApi; private MockWebServer server; private String baseUrl; private RepositoryRef repository; @BeforeEach public void setup() throws Exception { this.server = new MockWebServer(); this.server.start(); this.baseUrl = this.server.url("/api").toString(); this.gitHubActionsApi = new GitHubActionsApi("mock-oauth-token"); this.gitHubActionsApi.setBaseUrl(this.baseUrl); this.repository = new RepositoryRef("spring-projects", "spring-security"); } @AfterEach public void cleanup() throws Exception { this.server.shutdown(); } @Test public void dispatchWorkflowWhenValidParametersThenSuccess() throws Exception { this.server.enqueue(new MockResponse().setResponseCode(204)); Map<String, Object> inputs = new LinkedHashMap<>(); inputs.put("input-1", "value"); inputs.put("input-2", false); WorkflowDispatch workflowDispatch = new WorkflowDispatch("main", inputs); this.gitHubActionsApi.dispatchWorkflow(this.repository, "test-workflow.yml", workflowDispatch); RecordedRequest recordedRequest = this.server.takeRequest(1, TimeUnit.SECONDS); assertThat(recordedRequest.getMethod()).isEqualToIgnoringCase("post"); assertThat(recordedRequest.getRequestUrl().toString()) .isEqualTo(this.baseUrl + "/repos/spring-projects/spring-security/actions/workflows/test-workflow.yml/dispatches"); assertThat(recordedRequest.getBody().readString(Charset.defaultCharset())) .isEqualTo("{\"ref\":\"main\",\"inputs\":{\"input-1\":\"value\",\"input-2\":false}}"); } @Test public void dispatchWorkflowWhenErrorResponseThenException() throws Exception { this.server.enqueue(new MockResponse().setResponseCode(400)); WorkflowDispatch workflowDispatch = new WorkflowDispatch("main", null); assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> this.gitHubActionsApi.dispatchWorkflow(this.repository, "test-workflow.yml", workflowDispatch)); } }
3,256
35.188889
119
java
null
spring-security-main/buildSrc/src/test/java/org/springframework/gradle/antora/AntoraVersionPluginTests.java
package org.springframework.gradle.antora; import org.apache.commons.io.IOUtils; import org.gradle.api.GradleException; import org.gradle.api.Project; import org.gradle.api.Task; import org.gradle.testfixtures.ProjectBuilder; import org.junit.jupiter.api.Test; import java.io.File; import java.io.FileOutputStream; import java.nio.charset.StandardCharsets; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIOException; class AntoraVersionPluginTests { @Test void defaultsPropertiesWhenSnapshot() { String expectedVersion = "1.0.0-SNAPSHOT"; Project project = ProjectBuilder.builder().build(); project.setVersion(expectedVersion); project.getPluginManager().apply(AntoraVersionPlugin.class); Task task = project.getTasks().findByName(AntoraVersionPlugin.ANTORA_CHECK_VERSION_TASK_NAME); assertThat(task).isInstanceOf(CheckAntoraVersionTask.class); CheckAntoraVersionTask checkAntoraVersionTask = (CheckAntoraVersionTask) task; assertThat(checkAntoraVersionTask.getAntoraVersion().get()).isEqualTo("1.0.0"); assertThat(checkAntoraVersionTask.getAntoraPrerelease().get()).isEqualTo("-SNAPSHOT"); assertThat(checkAntoraVersionTask.getAntoraDisplayVersion().isPresent()).isFalse(); assertThat(checkAntoraVersionTask.getAntoraYmlFile().getAsFile().get()).isEqualTo(project.file("antora.yml")); } @Test void defaultsPropertiesWhenMilestone() { String expectedVersion = "1.0.0-M1"; Project project = ProjectBuilder.builder().build(); project.setVersion(expectedVersion); project.getPluginManager().apply(AntoraVersionPlugin.class); Task task = project.getTasks().findByName(AntoraVersionPlugin.ANTORA_CHECK_VERSION_TASK_NAME); assertThat(task).isInstanceOf(CheckAntoraVersionTask.class); CheckAntoraVersionTask checkAntoraVersionTask = (CheckAntoraVersionTask) task; assertThat(checkAntoraVersionTask.getAntoraVersion().get()).isEqualTo("1.0.0-M1"); assertThat(checkAntoraVersionTask.getAntoraPrerelease().get()).isEqualTo("true"); assertThat(checkAntoraVersionTask.getAntoraDisplayVersion().get()).isEqualTo(checkAntoraVersionTask.getAntoraVersion().get()); assertThat(checkAntoraVersionTask.getAntoraYmlFile().getAsFile().get()).isEqualTo(project.file("antora.yml")); } @Test void defaultsPropertiesWhenRc() { String expectedVersion = "1.0.0-RC1"; Project project = ProjectBuilder.builder().build(); project.setVersion(expectedVersion); project.getPluginManager().apply(AntoraVersionPlugin.class); Task task = project.getTasks().findByName(AntoraVersionPlugin.ANTORA_CHECK_VERSION_TASK_NAME); assertThat(task).isInstanceOf(CheckAntoraVersionTask.class); CheckAntoraVersionTask checkAntoraVersionTask = (CheckAntoraVersionTask) task; assertThat(checkAntoraVersionTask.getAntoraVersion().get()).isEqualTo("1.0.0-RC1"); assertThat(checkAntoraVersionTask.getAntoraPrerelease().get()).isEqualTo("true"); assertThat(checkAntoraVersionTask.getAntoraDisplayVersion().get()).isEqualTo(checkAntoraVersionTask.getAntoraVersion().get()); assertThat(checkAntoraVersionTask.getAntoraYmlFile().getAsFile().get()).isEqualTo(project.file("antora.yml")); } @Test void defaultsPropertiesWhenRelease() { String expectedVersion = "1.0.0"; Project project = ProjectBuilder.builder().build(); project.setVersion(expectedVersion); project.getPluginManager().apply(AntoraVersionPlugin.class); Task task = project.getTasks().findByName(AntoraVersionPlugin.ANTORA_CHECK_VERSION_TASK_NAME); assertThat(task).isInstanceOf(CheckAntoraVersionTask.class); CheckAntoraVersionTask checkAntoraVersionTask = (CheckAntoraVersionTask) task; assertThat(checkAntoraVersionTask.getAntoraVersion().get()).isEqualTo("1.0.0"); assertThat(checkAntoraVersionTask.getAntoraPrerelease().isPresent()).isFalse(); assertThat(checkAntoraVersionTask.getAntoraDisplayVersion().isPresent()).isFalse(); assertThat(checkAntoraVersionTask.getAntoraYmlFile().getAsFile().get()).isEqualTo(project.file("antora.yml")); } @Test void explicitProperties() { Project project = ProjectBuilder.builder().build(); project.getPluginManager().apply(AntoraVersionPlugin.class); Task task = project.getTasks().findByName(AntoraVersionPlugin.ANTORA_CHECK_VERSION_TASK_NAME); CheckAntoraVersionTask checkAntoraVersionTask = (CheckAntoraVersionTask) task; checkAntoraVersionTask.getAntoraVersion().set("1.0.0"); checkAntoraVersionTask.getAntoraPrerelease().set("-SNAPSHOT"); assertThat(checkAntoraVersionTask.getAntoraVersion().get()).isEqualTo("1.0.0"); assertThat(checkAntoraVersionTask.getAntoraPrerelease().get()).isEqualTo("-SNAPSHOT"); assertThat(checkAntoraVersionTask.getAntoraDisplayVersion().isPresent()).isFalse(); assertThat(checkAntoraVersionTask.getAntoraYmlFile().getAsFile().get()).isEqualTo(project.file("antora.yml")); } @Test void versionNotDefined() throws Exception { Project project = ProjectBuilder.builder().build(); File rootDir = project.getRootDir(); IOUtils.write("version: '1.0.0'", new FileOutputStream(new File(rootDir, "antora.yml")), StandardCharsets.UTF_8); project.getPluginManager().apply(AntoraVersionPlugin.class); Task task = project.getTasks().findByName(AntoraVersionPlugin.ANTORA_CHECK_VERSION_TASK_NAME); assertThat(task).isInstanceOf(CheckAntoraVersionTask.class); CheckAntoraVersionTask checkAntoraVersionTask = (CheckAntoraVersionTask) task; assertThatExceptionOfType(GradleException.class).isThrownBy(() -> checkAntoraVersionTask.check()); } @Test void antoraFileNotFound() throws Exception { String expectedVersion = "1.0.0-SNAPSHOT"; Project project = ProjectBuilder.builder().build(); project.setVersion(expectedVersion); project.getPluginManager().apply(AntoraVersionPlugin.class); Task task = project.getTasks().findByName(AntoraVersionPlugin.ANTORA_CHECK_VERSION_TASK_NAME); assertThat(task).isInstanceOf(CheckAntoraVersionTask.class); CheckAntoraVersionTask checkAntoraVersionTask = (CheckAntoraVersionTask) task; assertThatIOException().isThrownBy(() -> checkAntoraVersionTask.check()); } @Test void actualAntoraPrereleaseNull() throws Exception { String expectedVersion = "1.0.0-SNAPSHOT"; Project project = ProjectBuilder.builder().build(); File rootDir = project.getRootDir(); IOUtils.write("version: '1.0.0'", new FileOutputStream(new File(rootDir, "antora.yml")), StandardCharsets.UTF_8); project.setVersion(expectedVersion); project.getPluginManager().apply(AntoraVersionPlugin.class); Task task = project.getTasks().findByName(AntoraVersionPlugin.ANTORA_CHECK_VERSION_TASK_NAME); assertThat(task).isInstanceOf(CheckAntoraVersionTask.class); CheckAntoraVersionTask checkAntoraVersionTask = (CheckAntoraVersionTask) task; assertThatExceptionOfType(GradleException.class).isThrownBy(() -> checkAntoraVersionTask.check()); } @Test void matchesWhenSnapshot() throws Exception { String expectedVersion = "1.0.0-SNAPSHOT"; Project project = ProjectBuilder.builder().build(); File rootDir = project.getRootDir(); IOUtils.write("version: '1.0.0'\nprerelease: '-SNAPSHOT'", new FileOutputStream(new File(rootDir, "antora.yml")), StandardCharsets.UTF_8); project.setVersion(expectedVersion); project.getPluginManager().apply(AntoraVersionPlugin.class); Task task = project.getTasks().findByName(AntoraVersionPlugin.ANTORA_CHECK_VERSION_TASK_NAME); assertThat(task).isInstanceOf(CheckAntoraVersionTask.class); CheckAntoraVersionTask checkAntoraVersionTask = (CheckAntoraVersionTask) task; checkAntoraVersionTask.check(); } @Test void matchesWhenMilestone() throws Exception { String expectedVersion = "1.0.0-M1"; Project project = ProjectBuilder.builder().build(); File rootDir = project.getRootDir(); IOUtils.write("version: '1.0.0-M1'\nprerelease: 'true'\ndisplay_version: '1.0.0-M1'", new FileOutputStream(new File(rootDir, "antora.yml")), StandardCharsets.UTF_8); project.setVersion(expectedVersion); project.getPluginManager().apply(AntoraVersionPlugin.class); Task task = project.getTasks().findByName(AntoraVersionPlugin.ANTORA_CHECK_VERSION_TASK_NAME); assertThat(task).isInstanceOf(CheckAntoraVersionTask.class); CheckAntoraVersionTask checkAntoraVersionTask = (CheckAntoraVersionTask) task; checkAntoraVersionTask.check(); } @Test void matchesWhenRc() throws Exception { String expectedVersion = "1.0.0-RC1"; Project project = ProjectBuilder.builder().build(); File rootDir = project.getRootDir(); IOUtils.write("version: '1.0.0-RC1'\nprerelease: 'true'\ndisplay_version: '1.0.0-RC1'", new FileOutputStream(new File(rootDir, "antora.yml")), StandardCharsets.UTF_8); project.setVersion(expectedVersion); project.getPluginManager().apply(AntoraVersionPlugin.class); Task task = project.getTasks().findByName(AntoraVersionPlugin.ANTORA_CHECK_VERSION_TASK_NAME); assertThat(task).isInstanceOf(CheckAntoraVersionTask.class); CheckAntoraVersionTask checkAntoraVersionTask = (CheckAntoraVersionTask) task; checkAntoraVersionTask.check(); } @Test void matchesWhenReleaseAndPrereleaseUndefined() throws Exception { String expectedVersion = "1.0.0"; Project project = ProjectBuilder.builder().build(); File rootDir = project.getRootDir(); IOUtils.write("version: '1.0.0'", new FileOutputStream(new File(rootDir, "antora.yml")), StandardCharsets.UTF_8); project.setVersion(expectedVersion); project.getPluginManager().apply(AntoraVersionPlugin.class); Task task = project.getTasks().findByName(AntoraVersionPlugin.ANTORA_CHECK_VERSION_TASK_NAME); assertThat(task).isInstanceOf(CheckAntoraVersionTask.class); CheckAntoraVersionTask checkAntoraVersionTask = (CheckAntoraVersionTask) task; checkAntoraVersionTask.check(); } @Test void matchesWhenExplicitRelease() throws Exception { Project project = ProjectBuilder.builder().build(); File rootDir = project.getRootDir(); IOUtils.write("version: '1.0.0'", new FileOutputStream(new File(rootDir, "antora.yml")), StandardCharsets.UTF_8); project.getPluginManager().apply(AntoraVersionPlugin.class); Task task = project.getTasks().findByName(AntoraVersionPlugin.ANTORA_CHECK_VERSION_TASK_NAME); assertThat(task).isInstanceOf(CheckAntoraVersionTask.class); CheckAntoraVersionTask checkAntoraVersionTask = (CheckAntoraVersionTask) task; ((CheckAntoraVersionTask) task).getAntoraVersion().set("1.0.0"); checkAntoraVersionTask.check(); } @Test void matchesWhenExplicitPrerelease() throws Exception { Project project = ProjectBuilder.builder().build(); File rootDir = project.getRootDir(); IOUtils.write("version: '1.0.0'\nprerelease: '-SNAPSHOT'", new FileOutputStream(new File(rootDir, "antora.yml")), StandardCharsets.UTF_8); project.getPluginManager().apply(AntoraVersionPlugin.class); Task task = project.getTasks().findByName(AntoraVersionPlugin.ANTORA_CHECK_VERSION_TASK_NAME); assertThat(task).isInstanceOf(CheckAntoraVersionTask.class); CheckAntoraVersionTask checkAntoraVersionTask = (CheckAntoraVersionTask) task; ((CheckAntoraVersionTask) task).getAntoraVersion().set("1.0.0"); ((CheckAntoraVersionTask) task).getAntoraPrerelease().set("-SNAPSHOT"); checkAntoraVersionTask.check(); } @Test void matchesWhenMissingPropertyDefined() throws Exception { Project project = ProjectBuilder.builder().build(); File rootDir = project.getRootDir(); IOUtils.write("name: 'ROOT'\nversion: '1.0.0'", new FileOutputStream(new File(rootDir, "antora.yml")), StandardCharsets.UTF_8); project.getPluginManager().apply(AntoraVersionPlugin.class); Task task = project.getTasks().findByName(AntoraVersionPlugin.ANTORA_CHECK_VERSION_TASK_NAME); assertThat(task).isInstanceOf(CheckAntoraVersionTask.class); CheckAntoraVersionTask checkAntoraVersionTask = (CheckAntoraVersionTask) task; ((CheckAntoraVersionTask) task).getAntoraVersion().set("1.0.0"); checkAntoraVersionTask.check(); } }
12,024
43.372694
169
java
null
spring-security-main/buildSrc/src/test/resources/samples/javadocapi/multimodule/sample/src/main/java/sample/Sample.java
package sample; /** * Testing this * @author Rob Winch * */ public class Sample { /** * This does stuff */ public void doSample() {} }
147
8.866667
26
java
null
spring-security-main/buildSrc/src/test/resources/samples/javadocapi/multimodule/api/src/main/java/sample/Api.java
package sample; /** * Testing this * @author Rob Winch * */ public class Api { /** * This does stuff */ public void doStuff() {} }
143
8.6
25
java
null
spring-security-main/buildSrc/src/test/resources/samples/javadocapi/multimodule/impl/src/main/java/sample/Impl.java
package sample; /** * Testing this * @author Rob Winch * */ public class Impl { /** * This does stuff */ public void otherThings() {} }
148
8.933333
29
java
null
spring-security-main/buildSrc/src/test/resources/samples/showcase/sgbcs-docs/src/main/java/example/StringUtils.java
package example; public class StringUtils { // tag::contains[] public boolean contains(String haystack, String needle) { return haystack.contains(needle); } // end::contains[] }
203
19.4
61
java
null
spring-security-main/buildSrc/src/test/resources/samples/showcase/sgbcs-core/src/test/java/core/HasOptionalTest.java
package core; import org.junit.jupiter.api.Test; public class HasOptionalTest { @Test public void test() { HasOptional.doStuffWithOptionalDependency(); } }
165
11.769231
46
java
null
spring-security-main/buildSrc/src/test/resources/samples/showcase/sgbcs-core/src/test/java/core/CoreClassTest.java
package core; import org.junit.jupiter.api.Test; public class CoreClassTest { @Test public void test() { new CoreClass().run(); } }
141
9.923077
34
java
null
spring-security-main/buildSrc/src/test/resources/samples/showcase/sgbcs-core/src/main/java/core/CoreClass.java
package core; /** * * @author Rob Winch * */ public class CoreClass { public void run() { } }
103
6.428571
24
java
null
spring-security-main/buildSrc/src/test/resources/samples/showcase/sgbcs-core/src/main/java/core/HasOptional.java
package core; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HasOptional { public static void doStuffWithOptionalDependency() { Logger logger = LoggerFactory.getLogger(HasOptional.class); logger.debug("This is optional"); } }
260
16.4
61
java
null
spring-security-main/buildSrc/src/test/resources/samples/showcase/sgbcs-api/src/test/java/api/ApiTest.java
package api; import org.junit.jupiter.api.Test; public class ApiTest { @Test public void api() {} }
105
9.6
34
java
null
spring-security-main/buildSrc/src/test/resources/samples/showcase/sgbcs-api/src/main/java/api/Api.java
package api; /** * * @author Rob Winch * */ public class Api { }
71
5.545455
20
java
null
spring-security-main/buildSrc/src/test/resources/samples/testsconfiguration/core/src/test/java/sample/Dependency.java
package sample; public class Dependency {}
43
13.666667
26
java
null
spring-security-main/buildSrc/src/test/resources/samples/testsconfiguration/web/src/test/java/sample/DependencyTest.java
package sample; import org.junit.*; public class DependencyTest { @Test public void findsDependencyOnClasspath() { new Dependency(); } }
143
13.4
43
java
null
spring-security-main/buildSrc/src/test/resources/samples/jacoco/java/src/test/java/sample/TheClassTest.java
package sample; import static org.junit.Assert.*; import org.junit.Test; public class TheClassTest { TheClass theClass = new TheClass(); @Test public void doStuffWhenTrueThenTrue() { assertTrue(theClass.doStuff(true)); } @Test public void doStuffWhenTrueThenFalse() { assertFalse(theClass.doStuff(false)); } }
325
16.157895
41
java
null
spring-security-main/buildSrc/src/test/resources/samples/jacoco/java/src/main/java/sample/TheClass.java
package sample; public class TheClass { public boolean doStuff(boolean b) { if(b) { return true; } else { return false; } } }
140
11.818182
36
java
null
spring-security-main/buildSrc/src/test/resources/samples/integrationtest/withpropdeps/src/integration-test/java/sample/TheTest.java
package sample; import org.junit.Test; import jakarta.servlet.http.HttpServletRequest; public class TheTest { @Test public void compilesAndRuns() { HttpServletRequest request = null; } }
193
16.636364
47
java
null
spring-security-main/buildSrc/src/test/resources/samples/integrationtest/withjava/src/integration-test/java/sample/TheTest.java
package sample; import org.junit.Test; import org.springframework.core.Ordered; public class TheTest { @Test public void compilesAndRuns() { Ordered ordered = new Ordered() { @Override public int getOrder() { return 0; } }; } }
249
14.625
40
java
null
spring-security-main/buildSrc/src/main/groovy/io/spring/gradle/convention/ManagementConfigurationPlugin.java
/* * 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 org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.artifacts.ConfigurationContainer; import org.gradle.api.plugins.JavaPlugin; import org.gradle.api.plugins.JavaTestFixturesPlugin; import org.gradle.api.plugins.PluginContainer; 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 * will extend from it. * @author Rob Winch */ public class ManagementConfigurationPlugin implements Plugin<Project> { public static final String MANAGEMENT_CONFIGURATION_NAME = "management"; @Override public void apply(Project project) { ConfigurationContainer configurations = project.getConfigurations(); configurations.create(MANAGEMENT_CONFIGURATION_NAME, (management) -> { management.setVisible(false); management.setCanBeConsumed(false); management.setCanBeResolved(false); PluginContainer plugins = project.getPlugins(); plugins.withType(JavaPlugin.class, (javaPlugin) -> { configurations.getByName(JavaPlugin.COMPILE_CLASSPATH_CONFIGURATION_NAME).extendsFrom(management); configurations.getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME).extendsFrom(management); configurations.getByName(JavaPlugin.TEST_COMPILE_CLASSPATH_CONFIGURATION_NAME).extendsFrom(management); configurations.getByName(JavaPlugin.TEST_RUNTIME_CLASSPATH_CONFIGURATION_NAME).extendsFrom(management); }); plugins.withType(JavaTestFixturesPlugin.class, (javaTestFixturesPlugin) -> { configurations.getByName("testFixturesCompileClasspath").extendsFrom(management); configurations.getByName("testFixturesRuntimeClasspath").extendsFrom(management); }); plugins.withType(MavenPublishPlugin.class, (mavenPublish) -> { PublishingExtension publishing = project.getExtensions().getByType(PublishingExtension.class); publishing.getPublications().withType(MavenPublication.class, (mavenPublication -> { mavenPublication.versionMapping((versions) -> versions.allVariants(versionMapping -> versionMapping.fromResolutionResult()) ); })); }); plugins.withType(PropDepsPlugin.class, (propDepsPlugin -> { configurations.getByName("optional").extendsFrom(management); configurations.getByName("provided").extendsFrom(management); })); }); } }
3,314
43.797297
117
java
null
spring-security-main/buildSrc/src/main/java/trang/RncToXsd.java
package trang; import com.thaiopensource.relaxng.translate.Driver; import net.sf.saxon.TransformerFactoryImpl; import org.gradle.api.DefaultTask; import org.gradle.api.tasks.InputDirectory; import org.gradle.api.tasks.InputFile; import org.gradle.api.tasks.OutputDirectory; import org.gradle.api.tasks.TaskAction; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; /** * Converts .rnc files to .xsd files using trang and then applies an xsl file to cleanup the results. */ public class RncToXsd extends DefaultTask { private File rncDir; private File xslFile; private File xsdDir; @InputDirectory public File getRncDir() { return rncDir; } public void setRncDir(File rncDir) { this.rncDir = rncDir; } @InputFile public File getXslFile() { return xslFile; } public void setXslFile(File xslFile) { this.xslFile = xslFile; } @OutputDirectory public File getXsdDir() { return xsdDir; } public void setXsdDir(File xsdDir) { this.xsdDir = xsdDir; } @TaskAction public final void transform() throws IOException, TransformerException { String xslPath = xslFile.getAbsolutePath(); File[] files = rncDir.listFiles((dir, file) -> file.endsWith(".rnc")); if(files != null) { for (File rncFile : files) { File xsdFile = new File(xsdDir, rncFile.getName().replace(".rnc", ".xsd")); String xsdOutputPath = xsdFile.getAbsolutePath(); new Driver().run(new String[]{rncFile.getAbsolutePath(), xsdOutputPath}); TransformerFactory tFactory = new TransformerFactoryImpl(); Transformer transformer = tFactory.newTransformer(new StreamSource(xslPath)); File temp = File.createTempFile("gradle-trang-" + xsdFile.getName(), ".xsd"); Files.copy(xsdFile.toPath(), temp.toPath(), StandardCopyOption.REPLACE_EXISTING); StreamSource xmlSource = new StreamSource(temp); transformer.transform(xmlSource, new StreamResult(xsdFile)); temp.delete(); } } } }
2,229
25.547619
101
java
null
spring-security-main/buildSrc/src/main/java/trang/TrangPlugin.java
package trang; import org.gradle.api.Plugin; import org.gradle.api.Project; /** * Used for converting .rnc files to .xsd files. * @author Rob Winch */ public class TrangPlugin implements Plugin<Project> { @Override public void apply(Project project) { project.getTasks().register("rncToXsd", RncToXsd.class, (rncToXsd) -> { rncToXsd.setDescription("Converts .rnc to .xsd"); rncToXsd.setGroup("Build"); }); } }
428
21.578947
73
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/security/convention/versions/FileUtils.java
/* * Copyright 2019-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.security.convention.versions; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.function.Function; class FileUtils { static void replaceFileText(File file, Function<String, String> replaceText) { String buildFileText = readString(file); String updatedBuildFileText = replaceText.apply(buildFileText); writeString(file, updatedBuildFileText); } static String readString(File file) { try { byte[] bytes = Files.readAllBytes(file.toPath()); return new String(bytes); } catch (IOException e) { throw new RuntimeException(e); } } private static void writeString(File file, String text) { try { Files.write(file.toPath(), text.getBytes()); } catch (IOException e) { throw new RuntimeException(e); } } }
1,439
27.8
79
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/security/convention/versions/UpdateProjectVersionPlugin.java
/* * Copyright 2019-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.security.convention.versions; import org.gradle.api.Action; import org.gradle.api.Plugin; import org.gradle.api.Project; public class UpdateProjectVersionPlugin implements Plugin<Project> { @Override public void apply(Project project) { project.getTasks().register("updateProjectVersion", UpdateProjectVersionTask.class, new Action<UpdateProjectVersionTask>() { @Override public void execute(UpdateProjectVersionTask updateProjectVersionTask) { updateProjectVersionTask.setGroup("Release"); updateProjectVersionTask.setDescription("Updates the project version to the next release in gradle.properties"); updateProjectVersionTask.dependsOn("gitHubNextReleaseMilestone"); updateProjectVersionTask.getNextVersionFile().fileProvider(project.provider(() -> project.file("next-release.yml"))); } }); project.getTasks().register("updateToSnapshotVersion", UpdateToSnapshotVersionTask.class, new Action<UpdateToSnapshotVersionTask>() { @Override public void execute(UpdateToSnapshotVersionTask updateToSnapshotVersionTask) { updateToSnapshotVersionTask.setGroup("Release"); updateToSnapshotVersionTask.setDescription( "Updates the project version to the next snapshot in gradle.properties"); } }); } }
1,906
41.377778
135
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/security/convention/versions/CommandLineUtils.java
/* * Copyright 2019-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.security.convention.versions; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.Scanner; class CommandLineUtils { static void runCommand(File dir, String... args) { try { Process process = new ProcessBuilder() .directory(dir) .command(args) .start(); writeLinesTo(process.getInputStream(), System.out); writeLinesTo(process.getErrorStream(), System.out); if (process.waitFor() != 0) { new RuntimeException("Failed to run " + Arrays.toString(args)); } } catch (IOException | InterruptedException e) { throw new RuntimeException("Failed to run " + Arrays.toString(args), e); } } private static void writeLinesTo(InputStream input, PrintStream out) { Scanner scanner = new Scanner(input); while(scanner.hasNextLine()) { out.println(scanner.nextLine()); } } }
1,563
30.28
75
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/security/convention/versions/UpdateDependenciesPlugin.java
/* * 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 org.springframework.security.convention.versions; import com.github.benmanes.gradle.versions.reporter.result.Dependency; import com.github.benmanes.gradle.versions.reporter.result.DependencyOutdated; import com.github.benmanes.gradle.versions.reporter.result.Result; import com.github.benmanes.gradle.versions.reporter.result.VersionAvailable; import com.github.benmanes.gradle.versions.updates.DependencyUpdatesTask; import com.github.benmanes.gradle.versions.updates.gradle.GradleUpdateResult; import com.github.benmanes.gradle.versions.updates.resolutionstrategy.ComponentSelectionRulesWithCurrent; import com.github.benmanes.gradle.versions.updates.resolutionstrategy.ComponentSelectionWithCurrent; import com.github.benmanes.gradle.versions.updates.resolutionstrategy.ResolutionStrategyWithCurrent; import groovy.lang.Closure; import org.gradle.api.Action; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.artifacts.component.ModuleComponentIdentifier; import reactor.core.publisher.Mono; import java.io.File; import java.time.Duration; import java.util.*; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.springframework.security.convention.versions.TransitiveDependencyLookupUtils.NIMBUS_JOSE_JWT_NAME; import static org.springframework.security.convention.versions.TransitiveDependencyLookupUtils.OIDC_SDK_NAME; public class UpdateDependenciesPlugin implements Plugin<Project> { private GitHubApi gitHubApi; @Override public void apply(Project project) { UpdateDependenciesExtension updateDependenciesSettings = project.getExtensions().create("updateDependenciesSettings", UpdateDependenciesExtension.class, defaultFiles(project)); if (project.hasProperty("updateMode")) { String updateMode = String.valueOf(project.findProperty("updateMode")); updateDependenciesSettings.setUpdateMode(UpdateDependenciesExtension.UpdateMode.valueOf(updateMode)); } if (project.hasProperty("nextVersion")) { String nextVersion = String.valueOf(project.findProperty("nextVersion")); updateDependenciesSettings.getGitHub().setMilestone(nextVersion); } if (project.hasProperty("gitHubAccessToken")) { String gitHubAccessToken = String.valueOf(project.findProperty("gitHubAccessToken")); updateDependenciesSettings.getGitHub().setAccessToken(gitHubAccessToken); } project.getTasks().register("updateDependencies", DependencyUpdatesTask.class, new Action<DependencyUpdatesTask>() { @Override public void execute(DependencyUpdatesTask updateDependencies) { updateDependencies.setDescription("Update the dependencies"); updateDependencies.setCheckConstraints(true); updateDependencies.setOutputFormatter(new Closure<Void>(null) { @Override public Void call(Object argument) { Result result = (Result) argument; if (gitHubApi == null && updateDependenciesSettings.getUpdateMode() != UpdateDependenciesExtension.UpdateMode.COMMIT) { gitHubApi = new GitHubApi(updateDependenciesSettings.getGitHub().getAccessToken()); } updateDependencies(result, project, updateDependenciesSettings); updateGradleVersion(result, project, updateDependenciesSettings); return null; } }); updateDependencies.resolutionStrategy(new Action<ResolutionStrategyWithCurrent>() { @Override public void execute(ResolutionStrategyWithCurrent resolution) { resolution.componentSelection(new Action<ComponentSelectionRulesWithCurrent>() { @Override public void execute(ComponentSelectionRulesWithCurrent components) { updateDependenciesSettings.getExcludes().getActions().forEach((action) -> { components.all(action); }); updateDependenciesSettings.getExcludes().getComponents().forEach((action) -> { action.execute(components); }); components.all((selection) -> { ModuleComponentIdentifier candidate = selection.getCandidate(); if (candidate.getGroup().startsWith("org.apache.directory.") && !candidate.getVersion().equals(selection.getCurrentVersion())) { selection.reject("org.apache.directory.* has breaking changes in newer versions"); } }); String jaxbBetaRegex = ".*?b\\d+.*"; components.withModule("javax.xml.bind:jaxb-api", excludeWithRegex(jaxbBetaRegex, "Reject jaxb-api beta versions")); components.withModule("com.sun.xml.bind:jaxb-impl", excludeWithRegex(jaxbBetaRegex, "Reject jaxb-api beta versions")); components.withModule("commons-collections:commons-collections", excludeWithRegex("^\\d{3,}.*", "Reject commons-collections date based releases")); } }); } }); } }); } private void updateDependencies(Result result, Project project, UpdateDependenciesExtension updateDependenciesSettings) { SortedSet<DependencyOutdated> dependencies = result.getOutdated().getDependencies(); if (dependencies.isEmpty()) { return; } Map<String, List<DependencyOutdated>> groups = new LinkedHashMap<>(); dependencies.forEach(outdated -> { groups.computeIfAbsent(outdated.getGroup(), (key) -> new ArrayList<>()).add(outdated); }); List<DependencyOutdated> nimbusds = groups.getOrDefault("com.nimbusds", new ArrayList<>()); DependencyOutdated oidcSdc = nimbusds.stream().filter(d -> d.getName().equals(OIDC_SDK_NAME)).findFirst().orElseGet(() -> null); if(oidcSdc != null) { String oidcVersion = updatedVersion(oidcSdc); String jwtVersion = TransitiveDependencyLookupUtils.lookupJwtVersion(oidcVersion); Dependency nimbusJoseJwtDependency = result.getCurrent().getDependencies().stream().filter(d -> d.getName().equals(NIMBUS_JOSE_JWT_NAME)).findFirst().get(); DependencyOutdated outdatedJwt = new DependencyOutdated(); outdatedJwt.setVersion(nimbusJoseJwtDependency.getVersion()); outdatedJwt.setGroup(oidcSdc.getGroup()); outdatedJwt.setName(NIMBUS_JOSE_JWT_NAME); VersionAvailable available = new VersionAvailable(); available.setRelease(jwtVersion); outdatedJwt.setAvailable(available); nimbusds.add(outdatedJwt); } File gradlePropertiesFile = project.getRootProject().file(Project.GRADLE_PROPERTIES); Mono<GitHubApi.FindCreateIssueResult> createIssueResult = createIssueResultMono(updateDependenciesSettings); List<File> filesWithDependencies = updateDependenciesSettings.getFiles().get(); groups.forEach((group, outdated) -> { outdated.forEach((dependency) -> { String ga = dependency.getGroup() + ":" + dependency.getName() + ":"; String originalDependency = ga + dependency.getVersion(); String replacementDependency = ga + updatedVersion(dependency); System.out.println("Update " + originalDependency + " to " + replacementDependency); filesWithDependencies.forEach((fileWithDependency) -> { updateDependencyInlineVersion(fileWithDependency, dependency); updateDependencyWithVersionVariable(fileWithDependency, gradlePropertiesFile, dependency); }); }); // commit DependencyOutdated firstDependency = outdated.get(0); String updatedVersion = updatedVersion(firstDependency); String title = outdated.size() == 1 ? "Update " + firstDependency.getName() + " to " + updatedVersion : "Update " + firstDependency.getGroup() + " to " + updatedVersion; afterGroup(updateDependenciesSettings, project.getRootDir(), title, createIssueResult); }); } private void afterGroup(UpdateDependenciesExtension updateDependenciesExtension, File rootDir, String title, Mono<GitHubApi.FindCreateIssueResult> createIssueResultMono) { String commitMessage = title; if (updateDependenciesExtension.getUpdateMode() == UpdateDependenciesExtension.UpdateMode.GITHUB_ISSUE) { GitHubApi.FindCreateIssueResult createIssueResult = createIssueResultMono.block(); Integer issueNumber = gitHubApi.createIssue(createIssueResult.getRepositoryId(), title, createIssueResult.getLabelIds(), createIssueResult.getMilestoneId(), createIssueResult.getAssigneeId()).delayElement(Duration.ofSeconds(1)).block(); commitMessage += "\n\nCloses gh-" + issueNumber; } CommandLineUtils.runCommand(rootDir, "git", "commit", "-am", commitMessage); } private Mono<GitHubApi.FindCreateIssueResult> createIssueResultMono(UpdateDependenciesExtension updateDependenciesExtension) { return Mono.defer(() -> { UpdateDependenciesExtension.GitHub gitHub = updateDependenciesExtension.getGitHub(); return gitHubApi.findCreateIssueInput(gitHub.getOrganization(), gitHub.getRepository(), gitHub.getMilestone()).cache(); }); } private void updateGradleVersion(Result result, Project project, UpdateDependenciesExtension updateDependenciesSettings) { if (!result.getGradle().isEnabled()) { return; } GradleUpdateResult current = result.getGradle().getCurrent(); GradleUpdateResult running = result.getGradle().getRunning(); if (current.compareTo(running) > 0) { String title = "Update Gradle to " + current.getVersion(); System.out.println(title); CommandLineUtils.runCommand(project.getRootDir(), "./gradlew", "wrapper", "--gradle-version", current.getVersion(), "--no-daemon"); afterGroup(updateDependenciesSettings, project.getRootDir(), title, createIssueResultMono(updateDependenciesSettings)); } } private static Supplier<List<File>> defaultFiles(Project project) { return () -> { List<File> result = new ArrayList<>(); result.add(project.getBuildFile()); project.getChildProjects().values().forEach((childProject) -> result.add(childProject.getBuildFile()) ); result.add(project.getRootProject().file("buildSrc/build.gradle")); return result; }; } static Action<ComponentSelectionWithCurrent> excludeWithRegex(String regex, String reason) { Pattern pattern = Pattern.compile(regex); return (selection) -> { String candidateVersion = selection.getCandidate().getVersion(); if (pattern.matcher(candidateVersion).matches()) { selection.reject(candidateVersion + " is not allowed because it is " + reason); } }; } static void updateDependencyInlineVersion(File buildFile, DependencyOutdated dependency){ String ga = dependency.getGroup() + ":" + dependency.getName() + ":"; String originalDependency = ga + dependency.getVersion(); String replacementDependency = ga + updatedVersion(dependency); FileUtils.replaceFileText(buildFile, buildFileText -> buildFileText.replace(originalDependency, replacementDependency)); } static void updateDependencyWithVersionVariable(File scanFile, File gradlePropertiesFile, DependencyOutdated dependency) { if (!gradlePropertiesFile.exists()) { return; } FileUtils.replaceFileText(gradlePropertiesFile, (gradlePropertiesText) -> { String ga = dependency.getGroup() + ":" + dependency.getName() + ":"; Pattern pattern = Pattern.compile("\"" + ga + "\\$\\{?([^'\"]+?)\\}?\""); String buildFileText = FileUtils.readString(scanFile); Matcher matcher = pattern.matcher(buildFileText); while (matcher.find()) { String versionVariable = matcher.group(1); gradlePropertiesText = gradlePropertiesText.replace(versionVariable + "=" + dependency.getVersion(), versionVariable + "=" + updatedVersion(dependency)); } return gradlePropertiesText; }); } private static String updatedVersion(DependencyOutdated dependency) { VersionAvailable available = dependency.getAvailable(); String release = available.getRelease(); if (release != null) { return release; } return available.getMilestone(); } }
12,181
48.722449
239
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/security/convention/versions/UpdateDependenciesExtension.java
package org.springframework.security.convention.versions; import com.github.benmanes.gradle.versions.updates.resolutionstrategy.ComponentSelectionRulesWithCurrent; import com.github.benmanes.gradle.versions.updates.resolutionstrategy.ComponentSelectionWithCurrent; import com.github.benmanes.gradle.versions.updates.resolutionstrategy.ResolutionStrategyWithCurrent; import org.gradle.api.Action; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; import java.util.regex.Pattern; public class UpdateDependenciesExtension { private Supplier<List<File>> files; private UpdateMode updateMode = UpdateMode.COMMIT; private DependencyExcludes dependencyExcludes = new DependencyExcludes(); private GitHub gitHub = new GitHub(); public UpdateDependenciesExtension(Supplier<List<File>> files) { this.files = files; } public void setUpdateMode(UpdateMode updateMode) { this.updateMode = updateMode; } public UpdateMode getUpdateMode() { return updateMode; } GitHub getGitHub() { return this.gitHub; } DependencyExcludes getExcludes() { return dependencyExcludes; } Supplier<List<File>> getFiles() { return files; } public void setFiles(Supplier<List<File>> files) { this.files = files; } public void addFiles(Supplier<List<File>> files) { Supplier<List<File>> original = this.files; setFiles(() -> { List<File> result = new ArrayList<>(original.get()); result.addAll(files.get()); return result; }); } public void dependencyExcludes(Action<DependencyExcludes> excludes) { excludes.execute(this.dependencyExcludes); } public void gitHub(Action<GitHub> gitHub) { gitHub.execute(this.gitHub); } public enum UpdateMode { COMMIT, GITHUB_ISSUE } public class GitHub { private String organization; private String repository; private String accessToken; private String milestone; public String getOrganization() { return organization; } public void setOrganization(String organization) { this.organization = organization; } public String getRepository() { return repository; } public void setRepository(String repository) { this.repository = repository; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public String getMilestone() { return milestone; } public void setMilestone(String milestone) { this.milestone = milestone; } } /** * Consider creating some Predicates instead since they are composible */ public class DependencyExcludes { private List<Action<ComponentSelectionWithCurrent>> actions = new ArrayList<>(); private List<Action<ComponentSelectionRulesWithCurrent>> components = new ArrayList<>(); List<Action<ComponentSelectionWithCurrent>> getActions() { return actions; } public List<Action<ComponentSelectionRulesWithCurrent>> getComponents() { return components; } public DependencyExcludes alphaBetaVersions() { this.actions.add(excludeVersionWithRegex("(?i).*?(alpha|beta).*", "an alpha or beta version")); return this; } public DependencyExcludes majorVersionBump() { this.actions.add((selection) -> { String currentVersion = selection.getCurrentVersion(); int separator = currentVersion.indexOf("."); String major = separator > 0 ? currentVersion.substring(0, separator) : currentVersion; String candidateVersion = selection.getCandidate().getVersion(); Pattern calVerPattern = Pattern.compile("\\d\\d\\d\\d.*"); boolean isCalVer = calVerPattern.matcher(candidateVersion).matches(); if (!isCalVer && !candidateVersion.startsWith(major)) { selection.reject("Cannot upgrade to new Major Version"); } }); return this; } public DependencyExcludes minorVersionBump() { this.actions.add(createExcludeMinorVersionBump()); return this; } public Action<ComponentSelectionWithCurrent> createExcludeMinorVersionBump() { return (selection) -> { String currentVersion = selection.getCurrentVersion(); int majorSeparator = currentVersion.indexOf("."); int separator = currentVersion.indexOf(".", majorSeparator + 1); String majorMinor = separator > 0 ? currentVersion.substring(0, separator) : currentVersion; String candidateVersion = selection.getCandidate().getVersion(); if (!candidateVersion.startsWith(majorMinor)) { selection.reject("Cannot upgrade to new Minor Version"); } }; } public DependencyExcludes releaseCandidatesVersions() { this.actions.add(excludeVersionWithRegex("(?i).*?rc.*", "a release candidate version")); return this; } public DependencyExcludes milestoneVersions() { this.actions.add(excludeVersionWithRegex("(?i).*?m\\d+.*", "a milestone version")); return this; } public DependencyExcludes snapshotVersions() { this.actions.add(excludeVersionWithRegex(".*?-SNAPSHOT.*", "a SNAPSHOT version")); return this; } public DependencyExcludes addRule(Action<ComponentSelectionRulesWithCurrent> rule) { this.components.add(rule); return this; } private Action<ComponentSelectionWithCurrent> excludeVersionWithRegex(String regex, String reason) { Pattern pattern = Pattern.compile(regex); return (selection) -> { String candidateVersion = selection.getCandidate().getVersion(); if (pattern.matcher(candidateVersion).matches()) { selection.reject(candidateVersion + " is not allowed because it is " + reason); } }; } } }
5,557
26.929648
105
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/security/convention/versions/TransitiveDependencyLookupUtils.java
/* * 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 org.springframework.security.convention.versions; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.io.IOException; import java.io.InputStream; class TransitiveDependencyLookupUtils { static String OIDC_SDK_NAME = "oauth2-oidc-sdk"; static String NIMBUS_JOSE_JWT_NAME = "nimbus-jose-jwt"; private static OkHttpClient client = new OkHttpClient(); static String lookupJwtVersion(String oauthSdcVersion) { Request request = new Request.Builder() .get() .url("https://repo.maven.apache.org/maven2/com/nimbusds/" + OIDC_SDK_NAME + "/" + oauthSdcVersion + "/" + OIDC_SDK_NAME + "-" + oauthSdcVersion + ".pom") .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } InputStream inputStream = response.body().byteStream(); return getVersion(inputStream); } catch (Exception e) { throw new RuntimeException(e); } } private static String getVersion(InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(inputStream); doc.getDocumentElement().normalize(); XPath xPath = XPathFactory.newInstance().newXPath(); return xPath.evaluate("/project/dependencies/dependency/version[../artifactId/text() = \"" + NIMBUS_JOSE_JWT_NAME + "\"]", doc); } }
2,594
35.549296
157
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/security/convention/versions/UpdateToSnapshotVersionTask.java
/* * Copyright 2019-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.security.convention.versions; import org.gradle.api.DefaultTask; import org.gradle.api.Project; import org.gradle.api.tasks.TaskAction; import java.io.File; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class UpdateToSnapshotVersionTask extends DefaultTask { private static final String RELEASE_VERSION_PATTERN = "^([0-9]+)\\.([0-9]+)\\.([0-9]+)(-M\\d+|-RC\\d+)?$"; @TaskAction public void updateToSnapshotVersion() { String currentVersion = getProject().getVersion().toString(); File gradlePropertiesFile = getProject().getRootProject().file(Project.GRADLE_PROPERTIES); if (!gradlePropertiesFile.exists()) { return; } String nextVersion = calculateNextSnapshotVersion(currentVersion); System.out.println("Updating the project version in " + Project.GRADLE_PROPERTIES + " from " + currentVersion + " to " + nextVersion); FileUtils.replaceFileText(gradlePropertiesFile, (gradlePropertiesText) -> { gradlePropertiesText = gradlePropertiesText.replace("version=" + currentVersion, "version=" + nextVersion); return gradlePropertiesText; }); } private String calculateNextSnapshotVersion(String currentVersion) { Pattern releaseVersionPattern = Pattern.compile(RELEASE_VERSION_PATTERN); Matcher releaseVersion = releaseVersionPattern.matcher(currentVersion); if (releaseVersion.find()) { String majorSegment = releaseVersion.group(1); String minorSegment = releaseVersion.group(2); String patchSegment = releaseVersion.group(3); String modifier = releaseVersion.group(4); if (modifier == null) { patchSegment = String.valueOf(Integer.parseInt(patchSegment) + 1); } System.out.println("modifier = " + modifier); return String.format("%s.%s.%s-SNAPSHOT", majorSegment, minorSegment, patchSegment); } else { throw new IllegalStateException( "Cannot calculate next snapshot version because the current project version does not conform to the expected format"); } } }
2,635
37.202899
123
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/security/convention/versions/UpdateProjectVersionTask.java
/* * Copyright 2019-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.security.convention.versions; import org.gradle.api.DefaultTask; import org.gradle.api.Project; import org.gradle.api.file.RegularFileProperty; 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 java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import org.springframework.gradle.github.milestones.NextVersionYml; public abstract class UpdateProjectVersionTask extends DefaultTask { @InputFile public abstract RegularFileProperty getNextVersionFile(); @TaskAction public void checkReleaseDueToday() throws FileNotFoundException { File nextVersionFile = getNextVersionFile().getAsFile().get(); Yaml yaml = new Yaml(new Constructor(NextVersionYml.class)); NextVersionYml nextVersionYml = yaml.load(new FileInputStream(nextVersionFile)); String nextVersion = nextVersionYml.getVersion(); if (nextVersion == null) { throw new IllegalArgumentException( "Could not find version property in provided file " + nextVersionFile.getName()); } String currentVersion = getProject().getVersion().toString(); File gradlePropertiesFile = getProject().getRootProject().file(Project.GRADLE_PROPERTIES); if (!gradlePropertiesFile.exists()) { return; } System.out.println("Updating the project version in " + Project.GRADLE_PROPERTIES + " from " + currentVersion + " to " + nextVersion); FileUtils.replaceFileText(gradlePropertiesFile, (gradlePropertiesText) -> { gradlePropertiesText = gradlePropertiesText.replace("version=" + currentVersion, "version=" + nextVersion); return gradlePropertiesText; }); } }
2,423
36.875
111
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/security/convention/versions/GitHubApi.java
package org.springframework.security.convention.versions; import com.apollographql.apollo.ApolloCall; import com.apollographql.apollo.ApolloClient; import com.apollographql.apollo.api.Input; import com.apollographql.apollo.api.Response; import com.apollographql.apollo.exception.ApolloException; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import org.jetbrains.annotations.NotNull; import reactor.core.publisher.Mono; import reactor.util.retry.Retry; import reactor.util.retry.RetrySpec; import java.io.IOException; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class GitHubApi { private final ApolloClient apolloClient; public GitHubApi(String githubToken) { if (githubToken == null) { throw new IllegalArgumentException("githubToken is required. You can set it using -PgitHubAccessToken="); } OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); clientBuilder.addInterceptor(new AuthorizationInterceptor(githubToken)); this.apolloClient = ApolloClient.builder() .serverUrl("https://api.github.com/graphql") .okHttpClient(clientBuilder.build()) .build(); } public Mono<FindCreateIssueResult> findCreateIssueInput(String owner, String name, String milestone) { String label = "\"type: dependency-upgrade\""; FindCreateIssueInputQuery findCreateIssueInputQuery = new FindCreateIssueInputQuery(owner, name, Input.optional(label), Input.optional(milestone)); return Mono.create( sink -> this.apolloClient.query(findCreateIssueInputQuery) .enqueue(new ApolloCall.Callback<FindCreateIssueInputQuery.Data>() { @Override public void onResponse(@NotNull Response<FindCreateIssueInputQuery.Data> response) { if (response.hasErrors()) { sink.error(new RuntimeException(response.getErrors().stream().map(e -> e.getMessage()).collect(Collectors.joining(" ")))); } else { FindCreateIssueInputQuery.Data data = response.getData(); FindCreateIssueInputQuery.Repository repository = data.repository(); List<String> labels = repository.labels().nodes().stream().map(FindCreateIssueInputQuery.Node::id).collect(Collectors.toList()); if (labels.isEmpty()) { sink.error(new IllegalArgumentException("Could not find label for " + label)); return; } Optional<String> firstMilestoneId = repository.milestones().nodes().stream().map(FindCreateIssueInputQuery.Node1::id).findFirst(); if (!firstMilestoneId.isPresent()) { sink.error(new IllegalArgumentException("Could not find OPEN milestone id for " + milestone)); return; } String milestoneId = firstMilestoneId.get(); String repositoryId = repository.id(); String assigneeId = data.viewer().id(); sink.success(new FindCreateIssueResult(repositoryId, labels, milestoneId, assigneeId)); } } @Override public void onFailure(@NotNull ApolloException e) { sink.error(e); } })); } public static class FindCreateIssueResult { private final String repositoryId; private final List<String> labelIds; private final String milestoneId; private final String assigneeId; public FindCreateIssueResult(String repositoryId, List<String> labelIds, String milestoneId, String assigneeId) { this.repositoryId = repositoryId; this.labelIds = labelIds; this.milestoneId = milestoneId; this.assigneeId = assigneeId; } public String getRepositoryId() { return repositoryId; } public List<String> getLabelIds() { return labelIds; } public String getMilestoneId() { return milestoneId; } public String getAssigneeId() { return assigneeId; } } public Mono<RateLimitQuery.RateLimit> findRateLimit() { return Mono.create( sink -> this.apolloClient.query(new RateLimitQuery()) .enqueue(new ApolloCall.Callback<RateLimitQuery.Data>() { @Override public void onResponse(@NotNull Response<RateLimitQuery.Data> response) { if (response.hasErrors()) { sink.error(new RuntimeException(response.getErrors().stream().map(e -> e.getMessage()).collect(Collectors.joining(" ")))); } else { sink.success(response.getData().rateLimit()); } } @Override public void onFailure(@NotNull ApolloException e) { sink.error(e); } })); } public Mono<Integer> createIssue(String repositoryId, String title, List<String> labelIds, String milestoneId, String assigneeId) { CreateIssueInputMutation createIssue = new CreateIssueInputMutation.Builder() .repositoryId(repositoryId) .title(title) .labelIds(labelIds) .milestoneId(milestoneId) .assigneeId(assigneeId) .build(); return Mono.create( sink -> this.apolloClient.mutate(createIssue) .enqueue(new ApolloCall.Callback<CreateIssueInputMutation.Data>() { @Override public void onResponse(@NotNull Response<CreateIssueInputMutation.Data> response) { if (response.hasErrors()) { String message = response.getErrors().stream().map(e -> e.getMessage() + " " + e.getCustomAttributes() + " " + e.getLocations()).collect(Collectors.joining(" ")); if (message.contains("was submitted too quickly")) { sink.error(new SubmittedTooQuick(message)); } else { sink.error(new RuntimeException(message)); } } else { sink.success(response.getData().createIssue().issue().number()); } } @Override public void onFailure(@NotNull ApolloException e) { sink.error(e); } })) .retryWhen( RetrySpec.fixedDelay(3, Duration.ofMinutes(1)) .filter(SubmittedTooQuick.class::isInstance) .doBeforeRetry(r -> System.out.println("Pausing for 1 minute and then retrying due to receiving \"submitted too quickly\" error from GitHub API")) ) .cast(Integer.class); } public static class SubmittedTooQuick extends RuntimeException { public SubmittedTooQuick(String message) { super(message); } } private static class AuthorizationInterceptor implements Interceptor { private final String token; public AuthorizationInterceptor(String token) { this.token = token; } @Override public okhttp3.Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("Authorization", "Bearer " + this.token).build(); return chain.proceed(request); } } }
6,491
35.066667
169
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/CopyPropertiesPlugin.java
package org.springframework.gradle; import org.gradle.api.Plugin; import org.gradle.api.Project; public class CopyPropertiesPlugin implements Plugin<Project> { @Override public void apply(Project project) { copyPropertyFromRootProjectTo("group", project); copyPropertyFromRootProjectTo("version", project); copyPropertyFromRootProjectTo("description", project); } private void copyPropertyFromRootProjectTo(String propertyName, Project project) { Project rootProject = project.getRootProject(); Object property = rootProject.findProperty(propertyName); if(property != null) { project.setProperty(propertyName, property); } } }
653
27.434783
83
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/sagan/Release.java
/* * 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 org.springframework.gradle.sagan; import java.util.regex.Pattern; /** * Domain object for creating a new release version. */ public class Release { private String version; private ReleaseStatus status; private boolean current; private String referenceDocUrl; private String apiDocUrl; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public ReleaseStatus getStatus() { return status; } public void setStatus(ReleaseStatus status) { this.status = status; } public boolean isCurrent() { return current; } public void setCurrent(boolean current) { this.current = current; } public String getReferenceDocUrl() { return referenceDocUrl; } public void setReferenceDocUrl(String referenceDocUrl) { this.referenceDocUrl = referenceDocUrl; } public String getApiDocUrl() { return apiDocUrl; } public void setApiDocUrl(String apiDocUrl) { this.apiDocUrl = apiDocUrl; } @Override public String toString() { return "Release{" + "version='" + version + '\'' + ", status=" + status + ", current=" + current + ", referenceDocUrl='" + referenceDocUrl + '\'' + ", apiDocUrl='" + apiDocUrl + '\'' + '}'; } public enum ReleaseStatus { /** * Unstable version with limited support */ SNAPSHOT, /** * Pre-Release version meant to be tested by the community */ PRERELEASE, /** * Release Generally Available on public artifact repositories and enjoying full support from maintainers */ GENERAL_AVAILABILITY; private static final Pattern PRERELEASE_PATTERN = Pattern.compile("[A-Za-z0-9\\.\\-]+?(M|RC)\\d+"); private static final String SNAPSHOT_SUFFIX = "SNAPSHOT"; /** * Parse the ReleaseStatus from a String * @param version a project version * @return the release status for this version */ public static ReleaseStatus parse(String version) { if (version == null) { throw new IllegalArgumentException("version cannot be null"); } if (version.endsWith(SNAPSHOT_SUFFIX)) { return SNAPSHOT; } if (PRERELEASE_PATTERN.matcher(version).matches()) { return PRERELEASE; } return GENERAL_AVAILABILITY; } } }
2,859
22.064516
107
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/sagan/SaganCreateReleaseTask.java
/* * 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 org.springframework.gradle.sagan; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.core.runtime.Assert; import org.gradle.api.DefaultTask; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.TaskAction; import org.springframework.gradle.github.user.GitHubUserApi; import org.springframework.gradle.github.user.User; public class SaganCreateReleaseTask extends DefaultTask { private static final Pattern VERSION_PATTERN = Pattern.compile("^([0-9]+)\\.([0-9]+)\\.([0-9]+)(-.+)?$"); @Input private String gitHubAccessToken; @Input private String version; @Input private String apiDocUrl; @Input private String referenceDocUrl; @Input private String projectName; @TaskAction public void saganCreateRelease() { GitHubUserApi github = new GitHubUserApi(this.gitHubAccessToken); User user = github.getUser(); // Antora reference docs URLs for snapshots do not contain -SNAPSHOT String referenceDocUrl = this.referenceDocUrl; if (this.version.endsWith("-SNAPSHOT")) { Matcher versionMatcher = VERSION_PATTERN.matcher(this.version); Assert.isTrue(versionMatcher.matches(), "Version " + this.version + " does not match expected pattern"); String majorVersion = versionMatcher.group(1); String minorVersion = versionMatcher.group(2); String majorMinorVersion = String.format("%s.%s-SNAPSHOT", majorVersion, minorVersion); referenceDocUrl = this.referenceDocUrl.replace("{version}", majorMinorVersion); } SaganApi sagan = new SaganApi(user.getLogin(), this.gitHubAccessToken); Release release = new Release(); release.setVersion(this.version); release.setApiDocUrl(this.apiDocUrl); release.setReferenceDocUrl(referenceDocUrl); sagan.createReleaseForProject(release, this.projectName); } public String getGitHubAccessToken() { return gitHubAccessToken; } public void setGitHubAccessToken(String gitHubAccessToken) { this.gitHubAccessToken = gitHubAccessToken; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getApiDocUrl() { return apiDocUrl; } public void setApiDocUrl(String apiDocUrl) { this.apiDocUrl = apiDocUrl; } public String getReferenceDocUrl() { return referenceDocUrl; } public void setReferenceDocUrl(String referenceDocUrl) { this.referenceDocUrl = referenceDocUrl; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } }
3,183
27.945455
107
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/sagan/SaganDeleteReleaseTask.java
/* * 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 org.springframework.gradle.sagan; import org.gradle.api.DefaultTask; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.TaskAction; import org.springframework.gradle.github.user.GitHubUserApi; import org.springframework.gradle.github.user.User; public class SaganDeleteReleaseTask extends DefaultTask { @Input private String gitHubAccessToken; @Input private String version; @Input private String projectName; @TaskAction public void saganCreateRelease() { GitHubUserApi github = new GitHubUserApi(this.gitHubAccessToken); User user = github.getUser(); SaganApi sagan = new SaganApi(user.getLogin(), this.gitHubAccessToken); sagan.deleteReleaseForProject(this.version, this.projectName); } public String getGitHubAccessToken() { return gitHubAccessToken; } public void setGitHubAccessToken(String gitHubAccessToken) { this.gitHubAccessToken = gitHubAccessToken; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } }
1,815
25.318841
75
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/sagan/SaganApi.java
/* * 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 org.springframework.gradle.sagan; import com.google.gson.Gson; import okhttp3.*; import java.io.IOException; import java.util.Base64; /** * Implements necessary calls to the Sagan API See https://spring.io/restdocs/index.html */ public class SaganApi { private String baseUrl = "https://api.spring.io"; private OkHttpClient client; private Gson gson = new Gson(); public SaganApi(String username, String gitHubToken) { this.client = new OkHttpClient.Builder() .addInterceptor(new BasicInterceptor(username, gitHubToken)) .build(); } public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } public void createReleaseForProject(Release release, String projectName) { String url = this.baseUrl + "/projects/" + projectName + "/releases"; String releaseJsonString = gson.toJson(release); RequestBody body = RequestBody.create(MediaType.parse("application/json"), releaseJsonString); Request request = new Request.Builder() .url(url) .post(body) .build(); try { Response response = this.client.newCall(request).execute(); if (!response.isSuccessful()) { throw new RuntimeException("Could not create release " + release + ". Got response " + response); } } catch (IOException fail) { throw new RuntimeException("Could not create release " + release, fail); } } public void deleteReleaseForProject(String release, String projectName) { String url = this.baseUrl + "/projects/" + projectName + "/releases/" + release; Request request = new Request.Builder() .url(url) .delete() .build(); try { Response response = this.client.newCall(request).execute(); if (!response.isSuccessful()) { throw new RuntimeException("Could not delete release " + release + ". Got response " + response); } } catch (IOException fail) { throw new RuntimeException("Could not delete release " + release, fail); } } private static class BasicInterceptor implements Interceptor { private final String token; public BasicInterceptor(String username, String token) { this.token = Base64.getEncoder().encodeToString((username + ":" + token).getBytes()); } @Override public okhttp3.Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("Authorization", "Basic " + this.token).build(); return chain.proceed(request); } } }
3,025
31.191489
101
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/sagan/SaganPlugin.java
/* * 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 org.springframework.gradle.sagan; import io.spring.gradle.convention.Utils; import org.gradle.api.*; public class SaganPlugin implements Plugin<Project> { @Override public void apply(Project project) { project.getTasks().register("saganCreateRelease", SaganCreateReleaseTask.class, new Action<SaganCreateReleaseTask>() { @Override public void execute(SaganCreateReleaseTask saganCreateVersion) { saganCreateVersion.setGroup("Release"); saganCreateVersion.setDescription("Creates a new version for the specified project on spring.io"); saganCreateVersion.setVersion((String) project.findProperty("nextVersion")); saganCreateVersion.setProjectName(Utils.getProjectName(project)); saganCreateVersion.setGitHubAccessToken((String) project.findProperty("gitHubAccessToken")); } }); project.getTasks().register("saganDeleteRelease", SaganDeleteReleaseTask.class, new Action<SaganDeleteReleaseTask>() { @Override public void execute(SaganDeleteReleaseTask saganDeleteVersion) { saganDeleteVersion.setGroup("Release"); saganDeleteVersion.setDescription("Delete a version for the specified project on spring.io"); saganDeleteVersion.setVersion((String) project.findProperty("previousVersion")); saganDeleteVersion.setProjectName(Utils.getProjectName(project)); saganDeleteVersion.setGitHubAccessToken((String) project.findProperty("gitHubAccessToken")); } }); } }
2,058
41.895833
120
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/RepositoryRef.java
package org.springframework.gradle.github; import java.io.Serializable; public class RepositoryRef implements Serializable { private static final long serialVersionUID = 7151218536746822797L; private String owner; private String name; public RepositoryRef() { } public RepositoryRef(String owner, String name) { this.owner = owner; this.name = name; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "RepositoryRef{" + "owner='" + owner + '\'' + ", name='" + name + '\'' + '}'; } public static RepositoryRefBuilder owner(String owner) { return new RepositoryRefBuilder().owner(owner); } public static final class RepositoryRefBuilder { private String owner; private String repository; private RepositoryRefBuilder() { } private RepositoryRefBuilder owner(String owner) { this.owner = owner; return this; } public RepositoryRefBuilder repository(String repository) { this.repository = repository; return this; } public RepositoryRef build() { return new RepositoryRef(owner, repository); } } }
1,290
17.183099
67
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/changelog/GitHubChangelogPlugin.java
/* * 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 org.springframework.gradle.github.changelog; import java.io.File; import java.nio.file.Paths; import org.gradle.api.Action; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.Task; import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.DependencySet; import org.gradle.api.artifacts.repositories.ExclusiveContentRepository; import org.gradle.api.artifacts.repositories.IvyArtifactRepository; import org.gradle.api.artifacts.repositories.IvyPatternRepositoryLayout; import org.gradle.api.tasks.JavaExec; public class GitHubChangelogPlugin implements Plugin<Project> { public static final String CHANGELOG_GENERATOR_CONFIGURATION_NAME = "changelogGenerator"; public static final String RELEASE_NOTES_PATH = "changelog/release-notes.md"; @Override public void apply(Project project) { createRepository(project); createChangelogGeneratorConfiguration(project); project.getTasks().register("generateChangelog", JavaExec.class, new Action<JavaExec>() { @Override public void execute(JavaExec generateChangelog) { File outputFile = project.file(Paths.get(project.getBuildDir().getPath(), RELEASE_NOTES_PATH)); outputFile.getParentFile().mkdirs(); generateChangelog.setGroup("Release"); generateChangelog.setDescription("Generates the changelog"); generateChangelog.setWorkingDir(project.getRootDir()); generateChangelog.classpath(project.getConfigurations().getAt(CHANGELOG_GENERATOR_CONFIGURATION_NAME)); generateChangelog.doFirst(new Action<Task>() { @Override public void execute(Task task) { generateChangelog.args("--spring.config.location=scripts/release/release-notes-sections.yml", project.property("nextVersion"), outputFile.toString()); } }); } }); } private void createChangelogGeneratorConfiguration(Project project) { project.getConfigurations().create(CHANGELOG_GENERATOR_CONFIGURATION_NAME, new Action<Configuration>() { @Override public void execute(Configuration configuration) { configuration.defaultDependencies(new Action<DependencySet>() { @Override public void execute(DependencySet dependencies) { dependencies.add(project.getDependencies().create("spring-io:github-changelog-generator:0.0.6")); } }); } }); } private void createRepository(Project project) { IvyArtifactRepository repository = project.getRepositories().ivy(new Action<IvyArtifactRepository>() { @Override public void execute(IvyArtifactRepository repository) { repository.setUrl("https://github.com/"); repository.patternLayout(new Action<IvyPatternRepositoryLayout>() { @Override public void execute(IvyPatternRepositoryLayout layout) { layout.artifact("[organization]/[artifact]/releases/download/v[revision]/[artifact].[ext]"); } }); repository.getMetadataSources().artifact(); } }); project.getRepositories().exclusiveContent(new Action<ExclusiveContentRepository>() { @Override public void execute(ExclusiveContentRepository exclusiveContentRepository) { exclusiveContentRepository.forRepositories(repository); exclusiveContentRepository.filter(descriptor -> descriptor.includeGroup("spring-io")); } }); } }
3,882
38.622449
156
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/user/GitHubUserApi.java
/* * Copyright 2020-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.gradle.github.user; import java.io.IOException; import com.google.gson.Gson; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * @author Steve Riesenberg */ public class GitHubUserApi { private String baseUrl = "https://api.github.com"; private final OkHttpClient httpClient; private Gson gson = new Gson(); public GitHubUserApi(String gitHubAccessToken) { this.httpClient = new OkHttpClient.Builder() .addInterceptor(new AuthorizationInterceptor(gitHubAccessToken)) .build(); } public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } /** * Retrieve a GitHub user by the personal access token. * * @return The GitHub user */ public User getUser() { String url = this.baseUrl + "/user"; Request request = new Request.Builder().url(url).get().build(); try (Response response = this.httpClient.newCall(request).execute()) { if (!response.isSuccessful()) { throw new RuntimeException( String.format("Unable to retrieve GitHub user." + " Please check the personal access token and try again." + " Got response %s", response)); } return this.gson.fromJson(response.body().charStream(), User.class); } catch (IOException ex) { throw new RuntimeException("Unable to retrieve GitHub user.", ex); } } private static class AuthorizationInterceptor implements Interceptor { private final String token; public AuthorizationInterceptor(String token) { this.token = token; } @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("Authorization", "Bearer " + this.token) .build(); return chain.proceed(request); } } }
2,421
28.180723
75
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/user/User.java
package org.springframework.gradle.github.user; /** * @author Steve Riesenberg */ public class User { private Long id; private String login; private String name; private String url; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getLogin() { return this.login; } public void setLogin(String login) { this.login = login; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getUrl() { return this.url; } public void setUrl(String url) { this.url = url; } @Override public String toString() { return "User{" + "id=" + id + ", login='" + login + '\'' + ", name='" + name + '\'' + ", url='" + url + '\'' + '}'; } }
799
14.09434
47
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/milestones/LocalDateTimeAdapter.java
package org.springframework.gradle.github.milestones; import java.io.IOException; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; /** * @author Steve Riesenberg */ class LocalDateTimeAdapter extends TypeAdapter<LocalDateTime> { @Override public void write(JsonWriter jsonWriter, LocalDateTime localDateTime) throws IOException { jsonWriter.value(localDateTime.atOffset(ZoneOffset.UTC).format(DateTimeFormatter.ISO_ZONED_DATE_TIME)); } @Override public LocalDateTime read(JsonReader jsonReader) throws IOException { return LocalDateTime.parse(jsonReader.nextString(), DateTimeFormatter.ISO_ZONED_DATE_TIME); } }
803
29.923077
105
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestonePlugin.java
/* * Copyright 2019-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.github.milestones; import org.gradle.api.Action; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.tasks.TaskProvider; import org.springframework.gradle.github.RepositoryRef; public class GitHubMilestonePlugin implements Plugin<Project> { @Override public void apply(Project project) { TaskProvider<GitHubMilestoneNextReleaseTask> nextReleaseMilestoneTask = project.getTasks().register("gitHubNextReleaseMilestone", GitHubMilestoneNextReleaseTask.class, (gitHubMilestoneNextReleaseTask) -> { gitHubMilestoneNextReleaseTask.doNotTrackState("API call to GitHub needs to check for new milestones every time"); gitHubMilestoneNextReleaseTask.setGroup("Release"); gitHubMilestoneNextReleaseTask.setDescription("Calculates the next release version based on the current version and outputs it to a yaml file"); gitHubMilestoneNextReleaseTask.getNextReleaseFile() .fileProvider(project.provider(() -> project.file("next-release.yml"))); if (project.hasProperty("gitHubAccessToken")) { gitHubMilestoneNextReleaseTask .setGitHubAccessToken((String) project.findProperty("gitHubAccessToken")); } }); project.getTasks().register("gitHubCheckMilestoneHasNoOpenIssues", GitHubMilestoneHasNoOpenIssuesTask.class, (githubCheckMilestoneHasNoOpenIssues) -> { githubCheckMilestoneHasNoOpenIssues.setGroup("Release"); githubCheckMilestoneHasNoOpenIssues.setDescription("Checks if there are any open issues for the specified repository and milestone"); githubCheckMilestoneHasNoOpenIssues.getIsOpenIssuesFile().value(project.getLayout().getBuildDirectory().file("github/milestones/is-open-issues")); githubCheckMilestoneHasNoOpenIssues.setMilestoneTitle((String) project.findProperty("nextVersion")); if (!project.hasProperty("nextVersion")) { githubCheckMilestoneHasNoOpenIssues.getNextVersionFile().convention( nextReleaseMilestoneTask.flatMap(GitHubMilestoneNextReleaseTask::getNextReleaseFile)); } if (project.hasProperty("gitHubAccessToken")) { githubCheckMilestoneHasNoOpenIssues.setGitHubAccessToken((String) project.findProperty("gitHubAccessToken")); } }); project.getTasks().register("gitHubCheckNextVersionDueToday", GitHubMilestoneNextVersionDueTodayTask.class, (gitHubMilestoneNextVersionDueTodayTask) -> { gitHubMilestoneNextVersionDueTodayTask.setGroup("Release"); gitHubMilestoneNextVersionDueTodayTask.setDescription("Checks if the next release version is due today or past due, will fail if the next version is not due yet"); gitHubMilestoneNextVersionDueTodayTask.getIsDueTodayFile().value(project.getLayout().getBuildDirectory().file("github/milestones/is-due-today")); gitHubMilestoneNextVersionDueTodayTask.getNextVersionFile().convention( nextReleaseMilestoneTask.flatMap(GitHubMilestoneNextReleaseTask::getNextReleaseFile)); if (project.hasProperty("gitHubAccessToken")) { gitHubMilestoneNextVersionDueTodayTask .setGitHubAccessToken((String) project.findProperty("gitHubAccessToken")); } }); project.getTasks().register("scheduleNextRelease", ScheduleNextReleaseTask.class, (scheduleNextRelease) -> { scheduleNextRelease.doNotTrackState("API call to GitHub needs to check for new milestones every time"); scheduleNextRelease.setGroup("Release"); scheduleNextRelease.setDescription("Schedule the next release (even months only) or release train (series of milestones starting in January or July) based on the current version"); scheduleNextRelease.setVersion((String) project.findProperty("nextVersion")); scheduleNextRelease.setGitHubAccessToken((String) project.findProperty("gitHubAccessToken")); }); } }
4,344
57.716216
207
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestoneNextVersionDueTodayTask.java
/* * Copyright 2019-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.github.milestones; import org.gradle.api.Action; import org.gradle.api.DefaultTask; import org.gradle.api.file.RegularFileProperty; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.InputFile; import org.gradle.api.tasks.Optional; import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.TaskAction; import org.gradle.work.DisableCachingByDefault; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.springframework.gradle.github.RepositoryRef; @DisableCachingByDefault(because = "the due date needs to be checked every time in case it changes") public abstract class GitHubMilestoneNextVersionDueTodayTask extends DefaultTask { @Input private RepositoryRef repository = new RepositoryRef(); @Input @Optional private String gitHubAccessToken; @InputFile public abstract RegularFileProperty getNextVersionFile(); @OutputFile public abstract RegularFileProperty getIsDueTodayFile(); private GitHubMilestoneApi milestones = new GitHubMilestoneApi(); @TaskAction public void checkReleaseDueToday() throws IOException { File nextVersionFile = getNextVersionFile().getAsFile().get(); Yaml yaml = new Yaml(new Constructor(NextVersionYml.class)); NextVersionYml nextVersionYml = yaml.load(new FileInputStream(nextVersionFile)); String nextVersion = nextVersionYml.getVersion(); if (nextVersion == null) { throw new IllegalArgumentException( "Could not find version property in provided file " + nextVersionFile.getName()); } boolean milestoneDueToday = this.milestones.isMilestoneDueToday(this.repository, nextVersion); Path isDueTodayPath = getIsDueTodayFile().getAsFile().get().toPath(); Files.writeString(isDueTodayPath, String.valueOf(milestoneDueToday)); if (milestoneDueToday) { System.out.println("The milestone with the title " + nextVersion + " in the repository " + this.repository + " is due today"); } else { System.out.println("The milestone with the title " + nextVersion + " in the repository " + this.repository + " is not due yet"); } } public RepositoryRef getRepository() { return repository; } public void repository(Action<RepositoryRef> repository) { repository.execute(this.repository); } public void setRepository(RepositoryRef repository) { this.repository = repository; } public String getGitHubAccessToken() { return gitHubAccessToken; } public void setGitHubAccessToken(String gitHubAccessToken) { this.gitHubAccessToken = gitHubAccessToken; this.milestones = new GitHubMilestoneApi(gitHubAccessToken); } }
3,389
31.912621
109
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/milestones/SpringReleaseTrain.java
/* * Copyright 2002-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.github.milestones; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.Month; import java.time.Year; import java.time.temporal.TemporalAdjuster; import java.time.temporal.TemporalAdjusters; import java.util.LinkedHashMap; import java.util.Map; /** * Spring release train generator based on rules contained in a specification. * <p> * The rules are: * <ol> * <li>Train 1 (January-May) or 2 (July-November)</li> * <li>Version number (e.g. 0.1.2, 1.0.0, etc.)</li> * <li>Week of month (1st, 2nd, 3rd, 4th)</li> * <li>Day of week (Monday-Friday)</li> * <li>Year (e.g. 2020, 2021, etc.)</li> * </ol> * * The release train generated will contain M1, M2, M3, RC1 and GA versions * mapped to their respective dates in the train. * * @author Steve Riesenberg */ public final class SpringReleaseTrain { private final SpringReleaseTrainSpec releaseTrainSpec; public SpringReleaseTrain(SpringReleaseTrainSpec releaseTrainSpec) { this.releaseTrainSpec = releaseTrainSpec; } /** * Calculate release train dates based on the release train specification. * * @return A mapping of release milestones to scheduled release dates */ public Map<String, LocalDate> getTrainDates() { Map<String, LocalDate> releaseDates = new LinkedHashMap<>(); switch (this.releaseTrainSpec.getTrain()) { case ONE: addTrainDate(releaseDates, "M1", Month.JANUARY); addTrainDate(releaseDates, "M2", Month.FEBRUARY); addTrainDate(releaseDates, "M3", Month.MARCH); addTrainDate(releaseDates, "RC1", Month.APRIL); addTrainDate(releaseDates, null, Month.MAY); break; case TWO: addTrainDate(releaseDates, "M1", Month.JULY); addTrainDate(releaseDates, "M2", Month.AUGUST); addTrainDate(releaseDates, "M3", Month.SEPTEMBER); addTrainDate(releaseDates, "RC1", Month.OCTOBER); addTrainDate(releaseDates, null, Month.NOVEMBER); break; } return releaseDates; } /** * Determine if a given date matches the due date of given version. * * @param version The version number (e.g. 5.6.0-M1, 5.6.0, etc.) * @param expectedDate The expected date * @return true if the given date matches the due date of the given version, false otherwise */ public boolean isTrainDate(String version, LocalDate expectedDate) { return expectedDate.isEqual(getTrainDates().get(version)); } /** * Calculate the next release date following the given date. * <p> * The next release date is always on an even month so that a patch release * is the month after the GA version of a release train. This method does * not consider the year of the release train, only the given start date. * * @param startDate The start date * @return The next release date following the given date */ public LocalDate getNextReleaseDate(LocalDate startDate) { LocalDate trainDate; LocalDate currentDate = startDate; do { trainDate = calculateReleaseDate( Year.of(currentDate.getYear()), currentDate.getMonth(), this.releaseTrainSpec.getDayOfWeek().getDayOfWeek(), this.releaseTrainSpec.getWeekOfMonth().getDayOffset() ); currentDate = currentDate.plusMonths(1); } while (!trainDate.isAfter(startDate) || trainDate.getMonthValue() % 2 != 0); return trainDate; } private void addTrainDate(Map<String, LocalDate> releaseDates, String milestone, Month month) { LocalDate releaseDate = calculateReleaseDate( this.releaseTrainSpec.getYear(), month, this.releaseTrainSpec.getDayOfWeek().getDayOfWeek(), this.releaseTrainSpec.getWeekOfMonth().getDayOffset() ); String suffix = (milestone == null) ? "" : "-" + milestone; releaseDates.put(this.releaseTrainSpec.getVersion() + suffix, releaseDate); } private static LocalDate calculateReleaseDate(Year year, Month month, DayOfWeek dayOfWeek, int dayOffset) { TemporalAdjuster nextMonday = TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY); TemporalAdjuster nextDayOfWeek = TemporalAdjusters.nextOrSame(dayOfWeek); LocalDate firstDayOfMonth = year.atMonth(month).atDay(1); LocalDate firstMondayOfMonth = firstDayOfMonth.with(nextMonday); return firstMondayOfMonth.with(nextDayOfWeek).plusDays(dayOffset); } }
4,863
34.50365
108
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/milestones/LocalDateAdapter.java
package org.springframework.gradle.github.milestones; import java.io.IOException; import java.time.LocalDate; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; /** * @author Steve Riesenberg */ class LocalDateAdapter extends TypeAdapter<LocalDate> { @Override public void write(JsonWriter jsonWriter, LocalDate localDate) throws IOException { jsonWriter.value(localDate.toString()); } @Override public LocalDate read(JsonReader jsonReader) throws IOException { return LocalDate.parse(jsonReader.nextString()); } }
600
24.041667
83
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/milestones/Milestone.java
/* * Copyright 2019-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.github.milestones; import com.google.gson.annotations.SerializedName; import java.time.LocalDateTime; import java.util.Date; /** * @author Steve Riesenberg */ public class Milestone { private String title; private Long number; @SerializedName("due_on") private LocalDateTime dueOn; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Long getNumber() { return number; } public void setNumber(Long number) { this.number = number; } public LocalDateTime getDueOn() { return dueOn; } public void setDueOn(LocalDateTime dueOn) { this.dueOn = dueOn; } @Override public String toString() { return "Milestone{" + "title='" + title + '\'' + ", number='" + number + '\'' + ", dueOn='" + dueOn + '\'' + '}'; } }
1,480
20.779412
75
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/milestones/SpringReleaseTrainSpec.java
/* * Copyright 2002-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.github.milestones; import java.time.LocalDate; import java.time.Month; import java.time.Year; import org.springframework.util.Assert; /** * A specification for a release train. * * @author Steve Riesenberg * @see SpringReleaseTrain */ public final class SpringReleaseTrainSpec { private final Train train; private final String version; private final WeekOfMonth weekOfMonth; private final DayOfWeek dayOfWeek; private final Year year; public SpringReleaseTrainSpec(Train train, String version, WeekOfMonth weekOfMonth, DayOfWeek dayOfWeek, Year year) { this.train = train; this.version = version; this.weekOfMonth = weekOfMonth; this.dayOfWeek = dayOfWeek; this.year = year; } public Train getTrain() { return train; } public String getVersion() { return version; } public WeekOfMonth getWeekOfMonth() { return weekOfMonth; } public DayOfWeek getDayOfWeek() { return dayOfWeek; } public Year getYear() { return year; } public static Builder builder() { return new Builder(); } public enum WeekOfMonth { FIRST(0), SECOND(7), THIRD(14), FOURTH(21); private final int dayOffset; WeekOfMonth(int dayOffset) { this.dayOffset = dayOffset; } public int getDayOffset() { return dayOffset; } } public enum DayOfWeek { MONDAY(java.time.DayOfWeek.MONDAY), TUESDAY(java.time.DayOfWeek.TUESDAY), WEDNESDAY(java.time.DayOfWeek.WEDNESDAY), THURSDAY(java.time.DayOfWeek.THURSDAY), FRIDAY(java.time.DayOfWeek.FRIDAY); private final java.time.DayOfWeek dayOfWeek; DayOfWeek(java.time.DayOfWeek dayOfWeek) { this.dayOfWeek = dayOfWeek; } public java.time.DayOfWeek getDayOfWeek() { return dayOfWeek; } } public enum Train { ONE, TWO } public static class Builder { private Train train; private String version; private WeekOfMonth weekOfMonth; private DayOfWeek dayOfWeek; private Year year; private Builder() { } public Builder train(int train) { this.train = switch (train) { case 1 -> Train.ONE; case 2 -> Train.TWO; default -> throw new IllegalArgumentException("Invalid train: " + train); }; return this; } public Builder train(Train train) { this.train = train; return this; } public Builder nextTrain() { // Search for next train starting with this month return nextTrain(LocalDate.now().withDayOfMonth(1)); } public Builder nextTrain(LocalDate startDate) { Train nextTrain = null; // Search for next train from a given start date LocalDate currentDate = startDate; while (nextTrain == null) { if (currentDate.getMonth() == Month.JANUARY) { nextTrain = Train.ONE; } else if (currentDate.getMonth() == Month.JULY) { nextTrain = Train.TWO; } currentDate = currentDate.plusMonths(1); } return train(nextTrain).year(currentDate.getYear()); } public Builder version(String version) { this.version = version; return this; } public Builder weekOfMonth(int weekOfMonth) { this.weekOfMonth = switch (weekOfMonth) { case 1 -> WeekOfMonth.FIRST; case 2 -> WeekOfMonth.SECOND; case 3 -> WeekOfMonth.THIRD; case 4 -> WeekOfMonth.FOURTH; default -> throw new IllegalArgumentException("Invalid weekOfMonth: " + weekOfMonth); }; return this; } public Builder weekOfMonth(WeekOfMonth weekOfMonth) { this.weekOfMonth = weekOfMonth; return this; } public Builder dayOfWeek(int dayOfWeek) { this.dayOfWeek = switch (dayOfWeek) { case 1 -> DayOfWeek.MONDAY; case 2 -> DayOfWeek.TUESDAY; case 3 -> DayOfWeek.WEDNESDAY; case 4 -> DayOfWeek.THURSDAY; case 5 -> DayOfWeek.FRIDAY; default -> throw new IllegalArgumentException("Invalid dayOfWeek: " + dayOfWeek); }; return this; } public Builder dayOfWeek(DayOfWeek dayOfWeek) { this.dayOfWeek = dayOfWeek; return this; } public Builder year(int year) { this.year = Year.of(year); return this; } public SpringReleaseTrainSpec build() { Assert.notNull(train, "train cannot be null"); Assert.notNull(version, "version cannot be null"); Assert.notNull(weekOfMonth, "weekOfMonth cannot be null"); Assert.notNull(dayOfWeek, "dayOfWeek cannot be null"); Assert.notNull(year, "year cannot be null"); return new SpringReleaseTrainSpec(train, version, weekOfMonth, dayOfWeek, year); } } }
5,023
23.38835
118
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestoneHasNoOpenIssuesTask.java
/* * Copyright 2019-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.github.milestones; import org.gradle.api.Action; import org.gradle.api.DefaultTask; import org.gradle.api.file.RegularFileProperty; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.InputFile; import org.gradle.api.tasks.Optional; import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.TaskAction; import org.gradle.work.DisableCachingByDefault; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.springframework.gradle.github.RepositoryRef; @DisableCachingByDefault(because = "the due date needs to be checked every time in case it changes") public abstract class GitHubMilestoneHasNoOpenIssuesTask extends DefaultTask { @Input private RepositoryRef repository = new RepositoryRef(); @Input @Optional private String milestoneTitle; @InputFile @Optional public abstract RegularFileProperty getNextVersionFile(); @Input @Optional private String gitHubAccessToken; @OutputFile public abstract RegularFileProperty getIsOpenIssuesFile(); private GitHubMilestoneApi milestones = new GitHubMilestoneApi(); @TaskAction public void checkHasNoOpenIssues() throws IOException { if (this.milestoneTitle == null) { File nextVersionFile = getNextVersionFile().getAsFile().get(); Yaml yaml = new Yaml(new Constructor(NextVersionYml.class)); NextVersionYml nextVersionYml = yaml.load(new FileInputStream(nextVersionFile)); String nextVersion = nextVersionYml.getVersion(); if (nextVersion == null) { throw new IllegalArgumentException( "Could not find version property in provided file " + nextVersionFile.getName()); } this.milestoneTitle = nextVersion; } long milestoneNumber = this.milestones.findMilestoneNumberByTitle(this.repository, this.milestoneTitle); boolean isOpenIssues = this.milestones.isOpenIssuesForMilestoneNumber(this.repository, milestoneNumber); Path isOpenIssuesPath = getIsOpenIssuesFile().getAsFile().get().toPath(); Files.writeString(isOpenIssuesPath, String.valueOf(isOpenIssues)); if (isOpenIssues) { System.out.println("The repository " + this.repository + " has open issues for milestone with the title " + this.milestoneTitle + " and number " + milestoneNumber); } else { System.out.println("The repository " + this.repository + " has no open issues for milestone with the title " + this.milestoneTitle + " and number " + milestoneNumber); } } public RepositoryRef getRepository() { return repository; } public void repository(Action<RepositoryRef> repository) { repository.execute(this.repository); } public void setRepository(RepositoryRef repository) { this.repository = repository; } public String getMilestoneTitle() { return milestoneTitle; } public void setMilestoneTitle(String milestoneTitle) { this.milestoneTitle = milestoneTitle; } public String getGitHubAccessToken() { return gitHubAccessToken; } public void setGitHubAccessToken(String gitHubAccessToken) { this.gitHubAccessToken = gitHubAccessToken; this.milestones = new GitHubMilestoneApi(gitHubAccessToken); } }
3,876
33.927928
170
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/milestones/NextVersionYml.java
/* * Copyright 2019-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.github.milestones; public class NextVersionYml { private String version; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } }
859
27.666667
75
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/milestones/ScheduleNextReleaseTask.java
/* * Copyright 2002-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.github.milestones; import java.time.LocalDate; import java.time.LocalTime; import org.gradle.api.Action; import org.gradle.api.DefaultTask; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.TaskAction; import org.springframework.gradle.github.RepositoryRef; /** * @author Steve Riesenberg */ public class ScheduleNextReleaseTask extends DefaultTask { @Input private RepositoryRef repository = new RepositoryRef(); @Input private String gitHubAccessToken; @Input private String version; @Input private Integer weekOfMonth; @Input private Integer dayOfWeek; @TaskAction public void scheduleNextRelease() { GitHubMilestoneApi gitHubMilestoneApi = new GitHubMilestoneApi(this.gitHubAccessToken); String nextReleaseMilestone = gitHubMilestoneApi.getNextReleaseMilestone(this.repository, this.version); // If the next release contains a dash (e.g. 5.6.0-RC1), it is already scheduled if (nextReleaseMilestone.contains("-")) { return; } // Check to see if a scheduled GA version already exists boolean hasExistingMilestone = gitHubMilestoneApi.getMilestones(this.repository).stream() .anyMatch(milestone -> nextReleaseMilestone.equals(milestone.getTitle())); if (hasExistingMilestone) { return; } // Next milestone is either a patch version or minor version // Note: Major versions will be handled like minor and get a release // train which can be manually updated to match the desired schedule. if (nextReleaseMilestone.endsWith(".0")) { // Create M1, M2, M3, RC1 and GA milestones for release train getReleaseTrain(nextReleaseMilestone).getTrainDates().forEach((milestoneTitle, dueOn) -> { Milestone milestone = new Milestone(); milestone.setTitle(milestoneTitle); // Note: GitHub seems to store full date/time as UTC then displays // as a date (no time) in your timezone, which means the date will // not always be the same date as we intend. // Using 12pm/noon UTC allows GitHub to schedule and display the // correct date. milestone.setDueOn(dueOn.atTime(LocalTime.NOON)); gitHubMilestoneApi.createMilestone(this.repository, milestone); }); } else { // Create GA milestone for patch release on the next even month LocalDate startDate = LocalDate.now(); LocalDate dueOn = getReleaseTrain(nextReleaseMilestone).getNextReleaseDate(startDate); Milestone milestone = new Milestone(); milestone.setTitle(nextReleaseMilestone); milestone.setDueOn(dueOn.atTime(LocalTime.NOON)); gitHubMilestoneApi.createMilestone(this.repository, milestone); } } private SpringReleaseTrain getReleaseTrain(String nextReleaseMilestone) { SpringReleaseTrainSpec releaseTrainSpec = SpringReleaseTrainSpec.builder() .nextTrain() .version(nextReleaseMilestone) .weekOfMonth(this.weekOfMonth) .dayOfWeek(this.dayOfWeek) .build(); return new SpringReleaseTrain(releaseTrainSpec); } public RepositoryRef getRepository() { return this.repository; } public void repository(Action<RepositoryRef> repository) { repository.execute(this.repository); } public void setRepository(RepositoryRef repository) { this.repository = repository; } public String getGitHubAccessToken() { return this.gitHubAccessToken; } public void setGitHubAccessToken(String gitHubAccessToken) { this.gitHubAccessToken = gitHubAccessToken; } public String getVersion() { return this.version; } public void setVersion(String version) { this.version = version; } public Integer getWeekOfMonth() { return weekOfMonth; } public void setWeekOfMonth(Integer weekOfMonth) { this.weekOfMonth = weekOfMonth; } public Integer getDayOfWeek() { return dayOfWeek; } public void setDayOfWeek(Integer dayOfWeek) { this.dayOfWeek = dayOfWeek; } }
4,468
29.195946
106
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestoneNextReleaseTask.java
/* * Copyright 2019-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.github.milestones; import org.gradle.api.Action; import org.gradle.api.DefaultTask; import org.gradle.api.file.RegularFileProperty; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.Optional; import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.TaskAction; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Representer; import java.io.File; import java.io.FileWriter; import java.io.IOException; import org.springframework.gradle.github.RepositoryRef; public abstract class GitHubMilestoneNextReleaseTask extends DefaultTask { @Input private RepositoryRef repository = new RepositoryRef(); @Input @Optional private String gitHubAccessToken; private GitHubMilestoneApi milestones = new GitHubMilestoneApi(); @TaskAction public void calculateNextReleaseMilestone() throws IOException { String currentVersion = getProject().getVersion().toString(); String nextPreRelease = this.milestones.getNextReleaseMilestone(this.repository, currentVersion); System.out.println("The next release milestone is: " + nextPreRelease); NextVersionYml nextVersionYml = new NextVersionYml(); nextVersionYml.setVersion(nextPreRelease); File outputFile = getNextReleaseFile().get().getAsFile(); FileWriter outputWriter = new FileWriter(outputFile); Yaml yaml = getYaml(); yaml.dump(nextVersionYml, outputWriter); } @OutputFile public abstract RegularFileProperty getNextReleaseFile(); public RepositoryRef getRepository() { return repository; } public void repository(Action<RepositoryRef> repository) { repository.execute(this.repository); } public void setRepository(RepositoryRef repository) { this.repository = repository; } public String getGitHubAccessToken() { return gitHubAccessToken; } public void setGitHubAccessToken(String gitHubAccessToken) { this.gitHubAccessToken = gitHubAccessToken; this.milestones = new GitHubMilestoneApi(gitHubAccessToken); } private Yaml getYaml() { Representer representer = new Representer(); representer.addClassTag(NextVersionYml.class, Tag.MAP); DumperOptions ymlOptions = new DumperOptions(); ymlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); return new Yaml(representer, ymlOptions); } }
2,986
30.776596
99
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestoneApi.java
/* * Copyright 2019-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.github.milestones; import java.io.IOException; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.util.List; import java.util.Optional; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import org.springframework.gradle.github.RepositoryRef; public class GitHubMilestoneApi { private String baseUrl = "https://api.github.com"; private OkHttpClient client; private final Gson gson = new GsonBuilder() .registerTypeAdapter(LocalDate.class, new LocalDateAdapter().nullSafe()) .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter().nullSafe()) .create(); public GitHubMilestoneApi() { this.client = new OkHttpClient.Builder().build(); } public GitHubMilestoneApi(String gitHubToken) { this.client = new OkHttpClient.Builder() .addInterceptor(new AuthorizationInterceptor(gitHubToken)) .build(); } public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } public long findMilestoneNumberByTitle(RepositoryRef repositoryRef, String milestoneTitle) { List<Milestone> milestones = this.getMilestones(repositoryRef); for (Milestone milestone : milestones) { if (milestoneTitle.equals(milestone.getTitle())) { return milestone.getNumber(); } } if (milestones.size() <= 100) { throw new RuntimeException("Could not find open milestone with title " + milestoneTitle + " for repository " + repositoryRef + " Got " + milestones); } throw new RuntimeException("It is possible there are too many open milestones (only 100 are supported). Could not find open milestone with title " + milestoneTitle + " for repository " + repositoryRef + " Got " + milestones); } public List<Milestone> getMilestones(RepositoryRef repositoryRef) { String url = this.baseUrl + "/repos/" + repositoryRef.getOwner() + "/" + repositoryRef.getName() + "/milestones?per_page=100"; Request request = new Request.Builder().get().url(url) .build(); try { Response response = this.client.newCall(request).execute(); if (!response.isSuccessful()) { throw new RuntimeException("Could not retrieve milestones for repository " + repositoryRef + ". Response " + response); } return this.gson.fromJson(response.body().charStream(), new TypeToken<List<Milestone>>(){}.getType()); } catch (IOException e) { throw new RuntimeException("Could not retrieve milestones for repository " + repositoryRef, e); } } public boolean isOpenIssuesForMilestoneNumber(RepositoryRef repositoryRef, long milestoneNumber) { String url = this.baseUrl + "/repos/" + repositoryRef.getOwner() + "/" + repositoryRef.getName() + "/issues?per_page=1&milestone=" + milestoneNumber; Request request = new Request.Builder().get().url(url) .build(); try { Response response = this.client.newCall(request).execute(); if (!response.isSuccessful()) { throw new RuntimeException("Could not find issues for milestone number " + milestoneNumber + " for repository " + repositoryRef + ". Response " + response); } List<Object> issues = this.gson.fromJson(response.body().charStream(), new TypeToken<List<Object>>(){}.getType()); return !issues.isEmpty(); } catch (IOException e) { throw new RuntimeException("Could not find issues for milestone number " + milestoneNumber + " for repository " + repositoryRef, e); } } /** * Check if the given milestone is due today or past due. * * @param repositoryRef The repository owner/name * @param milestoneTitle The title of the milestone whose due date should be checked * @return true if the given milestone is due today or past due, false otherwise */ public boolean isMilestoneDueToday(RepositoryRef repositoryRef, String milestoneTitle) { String url = this.baseUrl + "/repos/" + repositoryRef.getOwner() + "/" + repositoryRef.getName() + "/milestones?per_page=100"; Request request = new Request.Builder().get().url(url).build(); try { Response response = this.client.newCall(request).execute(); if (!response.isSuccessful()) { throw new RuntimeException("Could not find milestone with title " + milestoneTitle + " for repository " + repositoryRef + ". Response " + response); } List<Milestone> milestones = this.gson.fromJson(response.body().charStream(), new TypeToken<List<Milestone>>() { }.getType()); for (Milestone milestone : milestones) { if (milestoneTitle.equals(milestone.getTitle())) { LocalDate today = LocalDate.now(); return milestone.getDueOn() != null && today.compareTo(milestone.getDueOn().toLocalDate()) >= 0; } } if (milestones.size() <= 100) { throw new RuntimeException("Could not find open milestone with title " + milestoneTitle + " for repository " + repositoryRef + " Got " + milestones); } throw new RuntimeException( "It is possible there are too many open milestones open (only 100 are supported). Could not find open milestone with title " + milestoneTitle + " for repository " + repositoryRef + " Got " + milestones); } catch (IOException e) { throw new RuntimeException( "Could not find open milestone with title " + milestoneTitle + " for repository " + repositoryRef, e); } } /** * Calculate the next release version based on the current version. * * The current version must conform to the pattern MAJOR.MINOR.PATCH-SNAPSHOT. If the * current version is a snapshot of a patch release, then the patch release will be * returned. For example, if the current version is 5.6.1-SNAPSHOT, then 5.6.1 will be * returned. If the current version is a snapshot of a version that is not GA (i.e the * PATCH segment is 0), then GitHub will be queried to find the next milestone or * release candidate. If no pre-release versions are found, then the next version will * be assumed to be the GA. * @param repositoryRef The repository owner/name * @param currentVersion The current project version * @return the next matching milestone/release candidate or null if none exist */ public String getNextReleaseMilestone(RepositoryRef repositoryRef, String currentVersion) { Pattern snapshotPattern = Pattern.compile("^([0-9]+)\\.([0-9]+)\\.([0-9]+)-SNAPSHOT$"); Matcher snapshotVersion = snapshotPattern.matcher(currentVersion); if (snapshotVersion.find()) { String patchSegment = snapshotVersion.group(3); String currentVersionNoIdentifier = currentVersion.replace("-SNAPSHOT", ""); if (patchSegment.equals("0")) { String nextPreRelease = getNextPreRelease(repositoryRef, currentVersionNoIdentifier); return nextPreRelease != null ? nextPreRelease : currentVersionNoIdentifier; } else { return currentVersionNoIdentifier; } } else { throw new IllegalStateException( "Cannot calculate next release version because the current project version does not conform to the expected format"); } } /** * Calculate the next pre-release version (milestone or release candidate) based on * the current version. * * The current version must conform to the pattern MAJOR.MINOR.PATCH. If no matching * milestone or release candidate is found in GitHub then it will return null. * @param repositoryRef The repository owner/name * @param currentVersionNoIdentifier The current project version without any * identifier * @return the next matching milestone/release candidate or null if none exist */ private String getNextPreRelease(RepositoryRef repositoryRef, String currentVersionNoIdentifier) { String url = this.baseUrl + "/repos/" + repositoryRef.getOwner() + "/" + repositoryRef.getName() + "/milestones?per_page=100"; Request request = new Request.Builder().get().url(url).build(); try { Response response = this.client.newCall(request).execute(); if (!response.isSuccessful()) { throw new RuntimeException( "Could not get milestones for repository " + repositoryRef + ". Response " + response); } List<Milestone> milestones = this.gson.fromJson(response.body().charStream(), new TypeToken<List<Milestone>>() { }.getType()); Optional<String> nextPreRelease = milestones.stream().map(Milestone::getTitle) .filter(m -> m.startsWith(currentVersionNoIdentifier + "-")) .min((m1, m2) -> { Pattern preReleasePattern = Pattern.compile("^.*-([A-Z]+)([0-9]+)$"); Matcher matcher1 = preReleasePattern.matcher(m1); Matcher matcher2 = preReleasePattern.matcher(m2); matcher1.find(); matcher2.find(); if (!matcher1.group(1).equals(matcher2.group(1))) { return m1.compareTo(m2); } else { return Integer.valueOf(matcher1.group(2)).compareTo(Integer.valueOf(matcher2.group(2))); } }); return nextPreRelease.orElse(null); } catch (IOException e) { throw new RuntimeException("Could not find open milestones with for repository " + repositoryRef, e); } } /** * Create a milestone. * * @param repository The repository owner/name * @param milestone The milestone containing a title and due date */ public void createMilestone(RepositoryRef repository, Milestone milestone) { String url = this.baseUrl + "/repos/" + repository.getOwner() + "/" + repository.getName() + "/milestones"; String json = this.gson.toJson(milestone); RequestBody body = RequestBody.create(MediaType.parse("application/json"), json); Request request = new Request.Builder().url(url).post(body).build(); try { Response response = this.client.newCall(request).execute(); if (!response.isSuccessful()) { throw new RuntimeException(String.format("Could not create milestone %s for repository %s/%s. Got response %s", milestone.getTitle(), repository.getOwner(), repository.getName(), response)); } } catch (IOException ex) { throw new RuntimeException(String.format("Could not create release %s for repository %s/%s", milestone.getTitle(), repository.getOwner(), repository.getName()), ex); } } private static class AuthorizationInterceptor implements Interceptor { private final String token; public AuthorizationInterceptor(String token) { this.token = token; } @Override public okhttp3.Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("Authorization", "Bearer " + this.token).build(); return chain.proceed(request); } } }
11,405
40.933824
227
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/release/GitHubActionsApi.java
/* * Copyright 2002-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.github.release; import java.io.IOException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import org.springframework.gradle.github.RepositoryRef; /** * Manage GitHub Actions. * * @author Steve Riesenberg */ public class GitHubActionsApi { private String baseUrl = "https://api.github.com"; private final OkHttpClient client; private final Gson gson = new GsonBuilder().create(); public GitHubActionsApi() { this.client = new OkHttpClient.Builder().build(); } public GitHubActionsApi(String gitHubToken) { this.client = new OkHttpClient.Builder() .addInterceptor(new AuthorizationInterceptor(gitHubToken)) .build(); } public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } /** * Create a workflow dispatch event. * * @param repository The repository owner/name * @param workflowId The ID of the workflow or the name of the workflow file name * @param workflowDispatch The workflow dispatch containing a ref (branch) and optional inputs */ public void dispatchWorkflow(RepositoryRef repository, String workflowId, WorkflowDispatch workflowDispatch) { String url = this.baseUrl + "/repos/" + repository.getOwner() + "/" + repository.getName() + "/actions/workflows/" + workflowId + "/dispatches"; String json = this.gson.toJson(workflowDispatch); RequestBody body = RequestBody.create(MediaType.parse("application/json"), json); Request request = new Request.Builder().url(url).post(body).build(); try { Response response = this.client.newCall(request).execute(); if (!response.isSuccessful()) { throw new RuntimeException(String.format("Could not create workflow dispatch %s for repository %s/%s. Got response %s", workflowId, repository.getOwner(), repository.getName(), response)); } } catch (IOException ex) { throw new RuntimeException(String.format("Could not create workflow dispatch %s for repository %s/%s", workflowId, repository.getOwner(), repository.getName()), ex); } } private static class AuthorizationInterceptor implements Interceptor { private final String token; public AuthorizationInterceptor(String token) { this.token = token; } @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("Authorization", "Bearer " + this.token) .build(); return chain.proceed(request); } } }
3,245
31.787879
146
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/release/WorkflowDispatch.java
/* * Copyright 2002-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.github.release; import java.util.Map; /** * @author Steve Riesenberg */ public class WorkflowDispatch { private String ref; private Map<String, Object> inputs; public WorkflowDispatch() { } public WorkflowDispatch(String ref, Map<String, Object> inputs) { this.ref = ref; this.inputs = inputs; } public String getRef() { return ref; } public void setRef(String ref) { this.ref = ref; } public Map<String, Object> getInputs() { return inputs; } public void setInputs(Map<String, Object> inputs) { this.inputs = inputs; } }
1,216
22.403846
75
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/release/DispatchGitHubWorkflowTask.java
/* * Copyright 2002-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.github.release; import org.gradle.api.Action; import org.gradle.api.DefaultTask; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.TaskAction; import org.springframework.gradle.github.RepositoryRef; /** * @author Steve Riesenberg */ public class DispatchGitHubWorkflowTask extends DefaultTask { @Input private RepositoryRef repository = new RepositoryRef(); @Input private String gitHubAccessToken; @Input private String branch; @Input private String workflowId; @TaskAction public void dispatchGitHubWorkflow() { GitHubActionsApi gitHubActionsApi = new GitHubActionsApi(this.gitHubAccessToken); WorkflowDispatch workflowDispatch = new WorkflowDispatch(this.branch, null); gitHubActionsApi.dispatchWorkflow(this.repository, this.workflowId, workflowDispatch); } public RepositoryRef getRepository() { return repository; } public void repository(Action<RepositoryRef> repository) { repository.execute(this.repository); } public void setRepository(RepositoryRef repository) { this.repository = repository; } public String getGitHubAccessToken() { return gitHubAccessToken; } public void setGitHubAccessToken(String gitHubAccessToken) { this.gitHubAccessToken = gitHubAccessToken; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public String getWorkflowId() { return workflowId; } public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } }
2,164
24.470588
88
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/release/Release.java
/* * 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.github.release; import com.google.gson.annotations.SerializedName; /** * @author Steve Riesenberg */ public class Release { @SerializedName("tag_name") private final String tag; @SerializedName("target_commitish") private final String commit; @SerializedName("name") private final String name; @SerializedName("body") private final String body; @SerializedName("draft") private final boolean draft; @SerializedName("prerelease") private final boolean preRelease; @SerializedName("generate_release_notes") private final boolean generateReleaseNotes; private Release(String tag, String commit, String name, String body, boolean draft, boolean preRelease, boolean generateReleaseNotes) { this.tag = tag; this.commit = commit; this.name = name; this.body = body; this.draft = draft; this.preRelease = preRelease; this.generateReleaseNotes = generateReleaseNotes; } public String getTag() { return tag; } public String getCommit() { return commit; } public String getName() { return name; } public String getBody() { return body; } public boolean isDraft() { return draft; } public boolean isPreRelease() { return preRelease; } public boolean isGenerateReleaseNotes() { return generateReleaseNotes; } @Override public String toString() { return "Release{" + "tag='" + tag + '\'' + ", commit='" + commit + '\'' + ", name='" + name + '\'' + ", body='" + body + '\'' + ", draft=" + draft + ", preRelease=" + preRelease + ", generateReleaseNotes=" + generateReleaseNotes + '}'; } public static Builder tag(String tag) { return new Builder().tag(tag); } public static Builder commit(String commit) { return new Builder().commit(commit); } public static final class Builder { private String tag; private String commit; private String name; private String body; private boolean draft; private boolean preRelease; private boolean generateReleaseNotes; private Builder() { } public Builder tag(String tag) { this.tag = tag; return this; } public Builder commit(String commit) { this.commit = commit; return this; } public Builder name(String name) { this.name = name; return this; } public Builder body(String body) { this.body = body; return this; } public Builder draft(boolean draft) { this.draft = draft; return this; } public Builder preRelease(boolean preRelease) { this.preRelease = preRelease; return this; } public Builder generateReleaseNotes(boolean generateReleaseNotes) { this.generateReleaseNotes = generateReleaseNotes; return this; } public Release build() { return new Release(tag, commit, name, body, draft, preRelease, generateReleaseNotes); } } }
3,442
20.929936
136
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/release/GitHubReleaseApi.java
/* * 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.github.release; import java.io.IOException; import com.google.gson.Gson; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import org.springframework.gradle.github.RepositoryRef; /** * Manage GitHub releases. * * @author Steve Riesenberg */ public class GitHubReleaseApi { private String baseUrl = "https://api.github.com"; private final OkHttpClient httpClient; private Gson gson = new Gson(); public GitHubReleaseApi(String gitHubAccessToken) { this.httpClient = new OkHttpClient.Builder() .addInterceptor(new AuthorizationInterceptor(gitHubAccessToken)) .build(); } public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } /** * Publish a release with no binary attachments. * * @param repository The repository owner/name * @param release The contents of the release */ public void publishRelease(RepositoryRef repository, Release release) { String url = this.baseUrl + "/repos/" + repository.getOwner() + "/" + repository.getName() + "/releases"; String json = this.gson.toJson(release); RequestBody body = RequestBody.create(MediaType.parse("application/json"), json); Request request = new Request.Builder().url(url).post(body).build(); try { Response response = this.httpClient.newCall(request).execute(); if (!response.isSuccessful()) { throw new RuntimeException(String.format("Could not create release %s for repository %s/%s. Got response %s", release.getName(), repository.getOwner(), repository.getName(), response)); } } catch (IOException ex) { throw new RuntimeException(String.format("Could not create release %s for repository %s/%s", release.getName(), repository.getOwner(), repository.getName()), ex); } } private static class AuthorizationInterceptor implements Interceptor { private final String token; public AuthorizationInterceptor(String token) { this.token = token; } @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("Authorization", "Bearer " + this.token) .build(); return chain.proceed(request); } } }
2,913
30.673913
113
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/release/CreateGitHubReleaseTask.java
/* * 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.github.release; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import org.gradle.api.Action; import org.gradle.api.DefaultTask; import org.gradle.api.Project; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.Optional; import org.gradle.api.tasks.TaskAction; import org.springframework.gradle.github.RepositoryRef; import org.springframework.gradle.github.changelog.GitHubChangelogPlugin; /** * @author Steve Riesenberg */ public class CreateGitHubReleaseTask extends DefaultTask { @Input private RepositoryRef repository = new RepositoryRef(); @Input @Optional private String gitHubAccessToken; @Input private String version; @Input @Optional private String branch = "main"; @Input private boolean createRelease = false; @TaskAction public void createGitHubRelease() { String body = readReleaseNotes(); Release release = Release.tag(this.version) .commit(this.branch) .name(this.version) .body(body) .preRelease(this.version.contains("-")) .build(); System.out.printf("%sCreating GitHub release for %s/%s@%s\n", this.createRelease ? "" : "[DRY RUN] ", this.repository.getOwner(), this.repository.getName(), this.version ); System.out.printf(" Release Notes:\n\n----\n%s\n----\n\n", body.trim()); if (this.createRelease) { GitHubReleaseApi github = new GitHubReleaseApi(this.gitHubAccessToken); github.publishRelease(this.repository, release); } } private String readReleaseNotes() { Project project = getProject(); File inputFile = project.file(Paths.get(project.getBuildDir().getPath(), GitHubChangelogPlugin.RELEASE_NOTES_PATH)); try { return Files.readString(inputFile.toPath()); } catch (IOException ex) { throw new RuntimeException("Unable to read release notes from " + inputFile, ex); } } public RepositoryRef getRepository() { return repository; } public void repository(Action<RepositoryRef> repository) { repository.execute(this.repository); } public void setRepository(RepositoryRef repository) { this.repository = repository; } public String getGitHubAccessToken() { return gitHubAccessToken; } public void setGitHubAccessToken(String gitHubAccessToken) { this.gitHubAccessToken = gitHubAccessToken; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public boolean isCreateRelease() { return createRelease; } public void setCreateRelease(boolean createRelease) { this.createRelease = createRelease; } }
3,376
24.778626
118
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/github/release/GitHubReleasePlugin.java
/* * 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.github.release; import groovy.lang.MissingPropertyException; import org.gradle.api.Plugin; import org.gradle.api.Project; /** * @author Steve Riesenberg */ public class GitHubReleasePlugin implements Plugin<Project> { @Override public void apply(Project project) { project.getTasks().register("createGitHubRelease", CreateGitHubReleaseTask.class, (createGitHubRelease) -> { createGitHubRelease.setGroup("Release"); createGitHubRelease.setDescription("Create a github release"); createGitHubRelease.dependsOn("generateChangelog"); createGitHubRelease.setCreateRelease("true".equals(project.findProperty("createRelease"))); createGitHubRelease.setVersion((String) project.findProperty("nextVersion")); if (project.hasProperty("branch")) { createGitHubRelease.setBranch((String) project.findProperty("branch")); } createGitHubRelease.setGitHubAccessToken((String) project.findProperty("gitHubAccessToken")); if (createGitHubRelease.isCreateRelease() && createGitHubRelease.getGitHubAccessToken() == null) { throw new MissingPropertyException("Please provide an access token with -PgitHubAccessToken=..."); } }); project.getTasks().register("dispatchGitHubWorkflow", DispatchGitHubWorkflowTask.class, (dispatchGitHubWorkflow) -> { dispatchGitHubWorkflow.setGroup("Release"); dispatchGitHubWorkflow.setDescription("Create a workflow_dispatch event on a given branch"); dispatchGitHubWorkflow.setBranch((String) project.findProperty("branch")); dispatchGitHubWorkflow.setWorkflowId((String) project.findProperty("workflowId")); dispatchGitHubWorkflow.setGitHubAccessToken((String) project.findProperty("gitHubAccessToken")); }); } }
2,356
41.854545
119
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/classpath/CheckClasspathForProhibitedDependenciesPlugin.java
/* * 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)); } }
2,992
44.348485
185
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/classpath/CheckProhibitedDependenciesLifecyclePlugin.java
/* * 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,592
38.825
172
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/classpath/CheckClasspathForProhibitedDependencies.java
/* * 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; } }
3,037
29.38
130
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/maven/SpringNexusPublishPlugin.java
package org.springframework.gradle.maven; import io.github.gradlenexus.publishplugin.NexusPublishExtension; import io.github.gradlenexus.publishplugin.NexusPublishPlugin; import io.github.gradlenexus.publishplugin.NexusRepository; import org.gradle.api.Action; import org.gradle.api.Plugin; import org.gradle.api.Project; import java.net.URI; import java.time.Duration; public class SpringNexusPublishPlugin implements Plugin<Project> { @Override public void apply(Project project) { project.getPlugins().apply(NexusPublishPlugin.class); NexusPublishExtension nexusPublishing = project.getExtensions().findByType(NexusPublishExtension.class); nexusPublishing.getRepositories().create("ossrh", new Action<NexusRepository>() { @Override public void execute(NexusRepository nexusRepository) { nexusRepository.getNexusUrl().set(URI.create("https://s01.oss.sonatype.org/service/local/")); nexusRepository.getSnapshotRepositoryUrl().set(URI.create("https://s01.oss.sonatype.org/content/repositories/snapshots/")); } }); nexusPublishing.getConnectTimeout().set(Duration.ofMinutes(3)); nexusPublishing.getClientTimeout().set(Duration.ofMinutes(3)); } }
1,186
39.931034
129
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/maven/PublishAllJavaComponentsPlugin.java
package org.springframework.gradle.maven; import org.gradle.api.Action; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.plugins.JavaPlatformPlugin; import org.gradle.api.plugins.JavaPlugin; import org.gradle.api.publish.PublishingExtension; import org.gradle.api.publish.VariantVersionMappingStrategy; import org.gradle.api.publish.VersionMappingStrategy; import org.gradle.api.publish.maven.MavenPublication; import org.gradle.api.publish.maven.plugins.MavenPublishPlugin; public class PublishAllJavaComponentsPlugin implements Plugin<Project> { @Override public void apply(Project project) { project.getPlugins().withType(MavenPublishPlugin.class).all((mavenPublish) -> { PublishingExtension publishing = project.getExtensions().getByType(PublishingExtension.class); publishing.getPublications().create("mavenJava", MavenPublication.class, new Action<MavenPublication>() { @Override public void execute(MavenPublication maven) { project.getPlugins().withType(JavaPlugin.class, (plugin) -> { maven.from(project.getComponents().getByName("java")); }); project.getPlugins().withType(JavaPlatformPlugin.class, (plugin) -> { maven.from(project.getComponents().getByName("javaPlatform")); }); } }); }); } }
1,301
37.294118
108
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/maven/SpringMavenPlugin.java
package org.springframework.gradle.maven; import io.spring.gradle.convention.ArtifactoryPlugin; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.plugins.PluginManager; import org.gradle.api.publish.maven.plugins.MavenPublishPlugin; public class SpringMavenPlugin implements Plugin<Project> { @Override public void apply(Project project) { PluginManager pluginManager = project.getPluginManager(); pluginManager.apply(MavenPublishPlugin.class); pluginManager.apply(SpringSigningPlugin.class); pluginManager.apply(MavenPublishingConventionsPlugin.class); pluginManager.apply(PublishAllJavaComponentsPlugin.class); pluginManager.apply(PublishLocalPlugin.class); pluginManager.apply(PublishArtifactsPlugin.class); pluginManager.apply(ArtifactoryPlugin.class); } }
815
36.090909
63
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/maven/MavenPublishingConventionsPlugin.java
package org.springframework.gradle.maven; import org.gradle.api.Action; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.plugins.JavaPlugin; import org.gradle.api.plugins.JavaPluginExtension; import org.gradle.api.publish.PublishingExtension; import org.gradle.api.publish.maven.MavenPom; import org.gradle.api.publish.maven.MavenPomDeveloperSpec; import org.gradle.api.publish.maven.MavenPomIssueManagement; import org.gradle.api.publish.maven.MavenPomLicenseSpec; import org.gradle.api.publish.maven.MavenPomOrganization; import org.gradle.api.publish.maven.MavenPomScm; import org.gradle.api.publish.maven.MavenPublication; import org.gradle.api.publish.maven.plugins.MavenPublishPlugin; public class MavenPublishingConventionsPlugin implements Plugin<Project> { @Override public void apply(Project project) { project.getPlugins().withType(MavenPublishPlugin.class).all(new Action<MavenPublishPlugin>() { @Override public void execute(MavenPublishPlugin mavenPublish) { PublishingExtension publishing = project.getExtensions().getByType(PublishingExtension.class); publishing.getPublications().withType(MavenPublication.class) .all((mavenPublication) -> MavenPublishingConventionsPlugin.this.customizePom(mavenPublication.getPom(), project)); MavenPublishingConventionsPlugin.this.customizeJavaPlugin(project); } }); } private void customizePom(MavenPom pom, Project project) { pom.getUrl().set("https://spring.io/projects/spring-security"); pom.getName().set(project.provider(project::getName)); pom.getDescription().set(project.provider(project::getDescription)); pom.organization(this::customizeOrganization); pom.licenses(this::customizeLicences); pom.developers(this::customizeDevelopers); pom.scm(this::customizeScm); pom.issueManagement(this::customizeIssueManagement); } private void customizeOrganization(MavenPomOrganization organization) { organization.getName().set("Pivotal Software, Inc."); organization.getUrl().set("https://spring.io"); } private void customizeLicences(MavenPomLicenseSpec licences) { licences.license((licence) -> { licence.getName().set("Apache License, Version 2.0"); licence.getUrl().set("https://www.apache.org/licenses/LICENSE-2.0"); }); } private void customizeDevelopers(MavenPomDeveloperSpec developers) { developers.developer((developer) -> { developer.getName().set("Pivotal"); developer.getEmail().set("info@pivotal.io"); developer.getOrganization().set("Pivotal Software, Inc."); developer.getOrganizationUrl().set("https://www.spring.io"); }); } private void customizeScm(MavenPomScm scm) { scm.getConnection().set("scm:git:git://github.com/spring-projects/spring-security.git"); scm.getDeveloperConnection().set("scm:git:ssh://git@github.com/spring-projects/spring-security.git"); scm.getUrl().set("https://github.com/spring-projects/spring-security"); } private void customizeIssueManagement(MavenPomIssueManagement issueManagement) { issueManagement.getSystem().set("GitHub"); issueManagement.getUrl().set("https://github.com/spring-projects/spring-security/issues"); } private void customizeJavaPlugin(Project project) { project.getPlugins().withType(JavaPlugin.class).all((javaPlugin) -> { JavaPluginExtension extension = project.getExtensions().getByType(JavaPluginExtension.class); extension.withJavadocJar(); extension.withSourcesJar(); }); } }
3,463
40.73494
121
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/maven/PublishLocalPlugin.java
package org.springframework.gradle.maven; import org.gradle.api.Action; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.artifacts.repositories.MavenArtifactRepository; import org.gradle.api.publish.PublishingExtension; import org.gradle.api.publish.maven.plugins.MavenPublishPlugin; import java.io.File; public class PublishLocalPlugin implements Plugin<Project> { @Override public void apply(Project project) { project.getPlugins().withType(MavenPublishPlugin.class).all(new Action<MavenPublishPlugin>() { @Override public void execute(MavenPublishPlugin mavenPublish) { PublishingExtension publishing = project.getExtensions().getByType(PublishingExtension.class); publishing.getRepositories().maven(new Action<MavenArtifactRepository>() { @Override public void execute(MavenArtifactRepository maven) { maven.setName("local"); maven.setUrl(new File(project.getRootProject().getBuildDir(), "publications/repos")); } }); } }); } }
1,024
33.166667
98
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/maven/SpringSigningPlugin.java
/* * Copyright 2016-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.springframework.gradle.maven; import org.gradle.api.Action; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.publish.Publication; import org.gradle.api.publish.PublishingExtension; import org.gradle.plugins.signing.SigningExtension; import org.gradle.plugins.signing.SigningPlugin; import java.util.concurrent.Callable; public class SpringSigningPlugin implements Plugin<Project> { @Override public void apply(Project project) { project.getPluginManager().apply(SigningPlugin.class); project.getPlugins().withType(SigningPlugin.class).all(new Action<SigningPlugin>() { @Override public void execute(SigningPlugin signingPlugin) { boolean hasSigningKey = project.hasProperty("signing.keyId") || project.hasProperty("signingKey"); if (hasSigningKey) { sign(project); } } }); } private void sign(Project project) { SigningExtension signing = project.getExtensions().findByType(SigningExtension.class); signing.setRequired((Callable<Boolean>) () -> project.getGradle().getTaskGraph().hasTask("publishArtifacts")); String signingKeyId = (String) project.findProperty("signingKeyId"); String signingKey = (String) project.findProperty("signingKey"); String signingPassword = (String) project.findProperty("signingPassword"); if (signingKeyId != null) { signing.useInMemoryPgpKeys(signingKeyId, signingKey, signingPassword); } else { signing.useInMemoryPgpKeys(signingKey, signingPassword); } project.getPlugins().withType(PublishAllJavaComponentsPlugin.class).all(new Action<PublishAllJavaComponentsPlugin>() { @Override public void execute(PublishAllJavaComponentsPlugin publishingPlugin) { PublishingExtension publishing = project.getExtensions().findByType(PublishingExtension.class); Publication maven = publishing.getPublications().getByName("mavenJava"); signing.sign(maven); } }); } }
2,538
38.061538
120
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/maven/PublishArtifactsPlugin.java
package org.springframework.gradle.maven; import io.spring.gradle.convention.Utils; import org.gradle.api.Action; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.Task; public class PublishArtifactsPlugin implements Plugin<Project> { @Override public void apply(Project project) { project.getTasks().register("publishArtifacts", new Action<Task>() { @Override public void execute(Task publishArtifacts) { publishArtifacts.setGroup("Publishing"); publishArtifacts.setDescription("Publish the artifacts to either Artifactory or Maven Central based on the version"); if (Utils.isRelease(project)) { publishArtifacts.dependsOn("publishToOssrh"); } else { publishArtifacts.dependsOn("artifactoryPublish"); } } }); } }
799
28.62963
121
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/antora/AntoraVersionPlugin.java
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.tasks.TaskProvider; import org.gradle.language.base.plugins.LifecycleBasePlugin; public class AntoraVersionPlugin 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(check -> check.dependsOn(antoraCheckVersion)); } }); project.getTasks().register("antoraUpdateVersion", UpdateAntoraVersionTask.class, new Action<UpdateAntoraVersionTask>() { @Override public void execute(UpdateAntoraVersionTask antoraUpdateVersion) { antoraUpdateVersion.setGroup("Release"); antoraUpdateVersion.setDescription("Updates the antora.yml version properties to match the Gradle version"); antoraUpdateVersion.getAntoraYmlFile().fileProvider(project.provider(() -> project.file("antora.yml"))); } }); } private static String getDefaultAntoraVersion(Project project) { String projectVersion = getProjectVersion(project); return AntoraVersionUtils.getDefaultAntoraVersion(projectVersion); } private static String getDefaultAntoraPrerelease(Project project) { String projectVersion = getProjectVersion(project); return AntoraVersionUtils.getDefaultAntoraPrerelease(projectVersion); } private static String getDefaultAntoraDisplayVersion(Project project) { String projectVersion = getProjectVersion(project); return AntoraVersionUtils.getDefaultAntoraDisplayVersion(projectVersion); } 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); } }
3,172
46.358209
188
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/antora/AntoraVersionUtils.java
/* * Copyright 2019-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.antora; public class AntoraVersionUtils { public static String getDefaultAntoraVersion(String projectVersion) { int preReleaseIndex = getSnapshotIndex(projectVersion); return isSnapshot(projectVersion) ? projectVersion.substring(0, preReleaseIndex) : projectVersion; } public static String getDefaultAntoraPrerelease(String projectVersion) { if (isSnapshot(projectVersion)) { int preReleaseIndex = getSnapshotIndex(projectVersion); return projectVersion.substring(preReleaseIndex); } if (isPreRelease(projectVersion)) { return Boolean.TRUE.toString(); } return null; } public static String getDefaultAntoraDisplayVersion(String projectVersion) { if (!isSnapshot(projectVersion) && isPreRelease(projectVersion)) { return getDefaultAntoraVersion(projectVersion); } return null; } 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,821
31.535714
100
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/antora/CheckAntoraVersionTask.java
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; } } }
3,306
33.092784
133
java
null
spring-security-main/buildSrc/src/main/java/org/springframework/gradle/antora/UpdateAntoraVersionTask.java
/* * Copyright 2019-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.antora; import org.gradle.api.DefaultTask; import org.gradle.api.GradleException; import org.gradle.api.Project; 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.OutputFile; import org.gradle.api.tasks.TaskAction; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.nodes.NodeTuple; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Representer; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import org.springframework.gradle.github.milestones.NextVersionYml; public abstract class UpdateAntoraVersionTask extends DefaultTask { @TaskAction public void update() throws IOException { String projectVersion = getProject().getVersion().toString(); File antoraYmlFile = getAntoraYmlFile().getAsFile().get(); String updatedAntoraVersion = AntoraVersionUtils.getDefaultAntoraVersion(projectVersion); String updatedAntoraPrerelease = AntoraVersionUtils.getDefaultAntoraPrerelease(projectVersion); String updatedAntoraDisplayVersion = AntoraVersionUtils.getDefaultAntoraDisplayVersion(projectVersion); Representer representer = new Representer(); representer.getPropertyUtils().setSkipMissingProperties(true); Yaml yaml = new Yaml(new Constructor(AntoraYml.class), representer); AntoraYml antoraYml = yaml.load(new FileInputStream(antoraYmlFile)); System.out.println("Updating the version parameters in " + antoraYmlFile.getName() + " to version: " + updatedAntoraVersion + ", prerelease: " + updatedAntoraPrerelease + ", display_version: " + updatedAntoraDisplayVersion); antoraYml.setVersion(updatedAntoraVersion); antoraYml.setPrerelease(updatedAntoraPrerelease); antoraYml.setDisplay_version(updatedAntoraDisplayVersion); FileWriter outputWriter = new FileWriter(antoraYmlFile); getYaml().dump(antoraYml, outputWriter); } @InputFile public abstract RegularFileProperty getAntoraYmlFile(); public static class AntoraYml { private String name; private String version; private String prerelease; private String display_version; public String getName() { return name; } public void setName(String name) { this.name = name; } 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; } } private Yaml getYaml() { Representer representer = new Representer() { @Override protected NodeTuple representJavaBeanProperty(Object javaBean, org.yaml.snakeyaml.introspector.Property property, Object propertyValue, Tag customTag) { // Don't write out null values if (propertyValue == null) { return null; } else { return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); } } }; representer.addClassTag(AntoraYml.class, Tag.MAP); DumperOptions ymlOptions = new DumperOptions(); ymlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); ymlOptions.setDefaultScalarStyle(DumperOptions.ScalarStyle.SINGLE_QUOTED); return new Yaml(representer, ymlOptions); } }
4,336
30.201439
105
java
null
spring-security-main/buildSrc/src/main/java/s101/S101Install.java
/* * 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); } }
1,231
33.222222
100
java
null
spring-security-main/buildSrc/src/main/java/s101/S101Configure.java
/* * 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,211
32.666667
100
java
null
spring-security-main/buildSrc/src/main/java/s101/S101Plugin.java
/* * 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); } } }
6,327
38.061728
142
java
null
spring-security-main/buildSrc/src/main/java/s101/S101PluginExtension.java
/* * 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")); } } }
2,508
29.228916
75
java
null
spring-security-main/buildSrc/src/main/java/s101/S101Configurer.java
/* * 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); Matcher matcher = null; for (HtmlAnchor anchor : page.getAnchors()) { Matcher candidate = Pattern.compile("(structure101-build-java-all-)(.*).zip").matcher(anchor.getHrefAttribute()); if (candidate.find()) { matcher = candidate; } } if (matcher == null) { return null; } copyZipToFilesystem(source, installationDirectory, matcher.group(1) + matcher.group(2)); return matcher.group(2); } 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; } }
10,883
33.884615
132
java
null
spring-security-main/buildSrc/src/main/java/lock/GlobalLockPlugin.java
package lock; import org.gradle.api.Plugin; import org.gradle.api.Project; /** * @author Rob Winch */ public class GlobalLockPlugin implements Plugin<Project> { @Override public void apply(Project project) { project.getTasks().register("writeLocks", GlobalLockTask.class, (writeAll) -> { writeAll.setDescription("Writes the locks for all projects"); }); } }
372
20.941176
81
java
null
spring-security-main/buildSrc/src/main/java/lock/GlobalLockTask.java
package lock; import org.gradle.api.Action; import org.gradle.api.DefaultTask; import org.gradle.api.Project; import org.gradle.api.artifacts.Configuration; import org.gradle.api.tasks.TaskAction; import java.util.function.Consumer; /** * @author Rob Winch */ public class GlobalLockTask extends DefaultTask { @TaskAction public void lock() { Project taskProject = getProject(); if (!taskProject.getGradle().getStartParameter().isWriteDependencyLocks()) { throw new IllegalStateException("You just specify --write-locks argument"); } writeLocksFor(taskProject); taskProject.getSubprojects().forEach(new Consumer<Project>() { @Override public void accept(Project subproject) { writeLocksFor(subproject); } }); } private void writeLocksFor(Project project) { project.getConfigurations().configureEach(new Action<Configuration>() { @Override public void execute(Configuration configuration) { if (configuration.isCanBeResolved()) { configuration.resolve(); } } }); } }
1,031
24.170732
78
java
null
spring-security-main/ldap/src/test/java/org/apache/directory/server/core/avltree/ArrayMarshaller.java
/* * 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.apache.directory.server.core.avltree; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Comparator; import org.apache.directory.shared.ldap.util.StringTools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class to serialize the Array data. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$, $Date$ */ @SuppressWarnings("unchecked") public class ArrayMarshaller<E> implements Marshaller<ArrayTree<E>> { /** static logger */ private static final Logger LOG = LoggerFactory.getLogger(ArrayMarshaller.class); /** used for serialized form of an empty AvlTree */ private static final byte[] EMPTY_TREE = new byte[1]; /** marshaller to be used for marshalling the keys */ private Marshaller<E> keyMarshaller; /** key Comparator for the AvlTree */ private Comparator<E> comparator; /** * Creates a new instance of AvlTreeMarshaller with a custom key Marshaller. * @param comparator Comparator to be used for key comparision * @param keyMarshaller marshaller for keys */ public ArrayMarshaller(Comparator<E> comparator, Marshaller<E> keyMarshaller) { this.comparator = comparator; this.keyMarshaller = keyMarshaller; } /** * Creates a new instance of AvlTreeMarshaller with the default key Marshaller which * uses Java Serialization. * @param comparator Comparator to be used for key comparision */ public ArrayMarshaller(Comparator<E> comparator) { this.comparator = comparator; this.keyMarshaller = DefaultMarshaller.INSTANCE; } /** * Marshals the given tree to bytes * @param tree the tree to be marshalled */ public byte[] serialize(ArrayTree<E> tree) { if ((tree == null) || (tree.size() == 0)) { return EMPTY_TREE; } ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(byteStream); byte[] data = null; try { out.writeByte(0); // represents the start of an Array byte stream out.writeInt(tree.size()); for (int position = 0; position < tree.size(); position++) { E value = tree.get(position); byte[] bytes = this.keyMarshaller.serialize(value); // Write the key length out.writeInt(bytes.length); // Write the key if its length is not null if (bytes.length != 0) { out.write(bytes); } } out.flush(); data = byteStream.toByteArray(); // Try to deserialize, just to see try { deserialize(data); } catch (NullPointerException npe) { System.out.println("Bad serialization, tree : [" + StringTools.dumpBytes(data) + "]"); throw npe; } out.close(); } catch (IOException ex) { ex.printStackTrace(); } return data; } /** * Creates an Array from given bytes of data. * @param data byte array to be converted into an array */ public ArrayTree<E> deserialize(byte[] data) throws IOException { try { if ((data == null) || (data.length == 0)) { throw new IOException("Null or empty data array is invalid."); } if ((data.length == 1) && (data[0] == 0)) { E[] array = (E[]) new Object[] {}; ArrayTree<E> tree = new ArrayTree<E>(this.comparator, array); return tree; } ByteArrayInputStream bin = new ByteArrayInputStream(data); DataInputStream din = new DataInputStream(bin); byte startByte = din.readByte(); if (startByte != 0) { throw new IOException("wrong array serialized data format"); } int size = din.readInt(); E[] nodes = (E[]) new Object[size]; for (int i = 0; i < size; i++) { // Read the object's size int dataSize = din.readInt(); if (dataSize != 0) { byte[] bytes = new byte[dataSize]; din.read(bytes); E key = this.keyMarshaller.deserialize(bytes); nodes[i] = key; } } ArrayTree<E> arrayTree = new ArrayTree<E>(this.comparator, nodes); return arrayTree; } catch (NullPointerException npe) { System.out.println("Bad tree : [" + StringTools.dumpBytes(data) + "]"); throw npe; } } }
4,782
26.488506
90
java
null
spring-security-main/ldap/src/test/java/org/springframework/security/ldap/SpringSecurityAuthenticationSourceTests.java
/* * Copyright 2002-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.security.ldap; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.ldap.core.AuthenticationSource; import org.springframework.ldap.core.DistinguishedName; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.ldap.authentication.SpringSecurityAuthenticationSource; import org.springframework.security.ldap.userdetails.LdapUserDetailsImpl; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * @author Luke Taylor */ public class SpringSecurityAuthenticationSourceTests { @BeforeEach @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } @Test public void principalAndCredentialsAreEmptyWithNoAuthentication() { AuthenticationSource source = new SpringSecurityAuthenticationSource(); assertThat(source.getPrincipal()).isEqualTo(""); assertThat(source.getCredentials()).isEqualTo(""); } @Test public void principalIsEmptyForAnonymousUser() { AuthenticationSource source = new SpringSecurityAuthenticationSource(); SecurityContextHolder.getContext().setAuthentication( new AnonymousAuthenticationToken("key", "anonUser", AuthorityUtils.createAuthorityList("ignored"))); assertThat(source.getPrincipal()).isEqualTo(""); } @Test public void getPrincipalRejectsNonLdapUserDetailsObject() { AuthenticationSource source = new SpringSecurityAuthenticationSource(); SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(new Object(), "password")); assertThatIllegalArgumentException().isThrownBy(source::getPrincipal); } @Test public void expectedCredentialsAreReturned() { AuthenticationSource source = new SpringSecurityAuthenticationSource(); SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(new Object(), "password")); assertThat(source.getCredentials()).isEqualTo("password"); } @Test public void expectedPrincipalIsReturned() { LdapUserDetailsImpl.Essence user = new LdapUserDetailsImpl.Essence(); user.setUsername("joe"); user.setDn(new DistinguishedName("uid=joe,ou=users")); AuthenticationSource source = new SpringSecurityAuthenticationSource(); SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken(user.createUserDetails(), null)); assertThat(source.getPrincipal()).isEqualTo("uid=joe,ou=users"); } @Test public void getPrincipalWhenCustomSecurityContextHolderStrategyThenExpectedPrincipalIsReturned() { LdapUserDetailsImpl.Essence user = new LdapUserDetailsImpl.Essence(); user.setUsername("joe"); user.setDn(new DistinguishedName("uid=joe,ou=users")); SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class); given(strategy.getContext()) .willReturn(new SecurityContextImpl(new TestingAuthenticationToken(user.createUserDetails(), null))); SpringSecurityAuthenticationSource source = new SpringSecurityAuthenticationSource(); source.setSecurityContextHolderStrategy(strategy); assertThat(source.getPrincipal()).isEqualTo("uid=joe,ou=users"); verify(strategy).getContext(); } }
4,425
40.754717
113
java
null
spring-security-main/ldap/src/test/java/org/springframework/security/ldap/LdapUtilsTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.security.ldap; import javax.naming.NamingException; import javax.naming.directory.DirContext; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; /** * Tests {@link LdapUtils} * * @author Luke Taylor */ public class LdapUtilsTests { @Test public void testCloseContextSwallowsNamingException() throws Exception { final DirContext dirCtx = mock(DirContext.class); willThrow(new NamingException()).given(dirCtx).close(); LdapUtils.closeContext(dirCtx); } @Test public void testGetRelativeNameReturnsEmptyStringForDnEqualToBaseName() throws Exception { final DirContext mockCtx = mock(DirContext.class); given(mockCtx.getNameInNamespace()).willReturn("dc=springframework,dc=org"); assertThat(LdapUtils.getRelativeName("dc=springframework,dc=org", mockCtx)).isEqualTo(""); } @Test public void testGetRelativeNameReturnsFullDnWithEmptyBaseName() throws Exception { final DirContext mockCtx = mock(DirContext.class); given(mockCtx.getNameInNamespace()).willReturn(""); assertThat(LdapUtils.getRelativeName("cn=jane,dc=springframework,dc=org", mockCtx)) .isEqualTo("cn=jane,dc=springframework,dc=org"); } @Test public void testGetRelativeNameWorksWithArbitrarySpaces() throws Exception { final DirContext mockCtx = mock(DirContext.class); given(mockCtx.getNameInNamespace()).willReturn("dc=springsecurity,dc = org"); assertThat(LdapUtils.getRelativeName("cn=jane smith, dc = springsecurity , dc=org", mockCtx)) .isEqualTo("cn=jane smith"); } @Test public void testRootDnsAreParsedFromUrlsCorrectly() { assertThat(LdapUtils.parseRootDnFromUrl("ldap://monkeymachine")).isEqualTo(""); assertThat(LdapUtils.parseRootDnFromUrl("ldap://monkeymachine:11389")).isEqualTo(""); assertThat(LdapUtils.parseRootDnFromUrl("ldap://monkeymachine/")).isEqualTo(""); assertThat(LdapUtils.parseRootDnFromUrl("ldap://monkeymachine.co.uk/")).isEqualTo(""); assertThat(LdapUtils.parseRootDnFromUrl("ldaps://monkeymachine.co.uk/dc=springframework,dc=org")) .isEqualTo("dc=springframework,dc=org"); assertThat(LdapUtils.parseRootDnFromUrl("ldap:///dc=springframework,dc=org")) .isEqualTo("dc=springframework,dc=org"); assertThat(LdapUtils.parseRootDnFromUrl("ldap://monkeymachine/dc=springframework,dc=org")) .isEqualTo("dc=springframework,dc=org"); assertThat(LdapUtils.parseRootDnFromUrl("ldap://monkeymachine.co.uk/dc=springframework,dc=org/ou=blah")) .isEqualTo("dc=springframework,dc=org/ou=blah"); assertThat(LdapUtils.parseRootDnFromUrl("ldap://monkeymachine.co.uk:389/dc=springframework,dc=org/ou=blah")) .isEqualTo("dc=springframework,dc=org/ou=blah"); } }
3,461
39.729412
110
java
null
spring-security-main/ldap/src/test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateTests.java
/* * Copyright 2002-2013 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.security.ldap; import javax.naming.NamingEnumeration; import javax.naming.directory.DirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.ldap.core.DirContextAdapter; import org.springframework.ldap.core.DistinguishedName; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @ExtendWith(MockitoExtension.class) public class SpringSecurityLdapTemplateTests { @Mock private DirContext ctx; @Captor private ArgumentCaptor<SearchControls> searchControls; @Mock private NamingEnumeration<SearchResult> resultsEnum; @Mock private SearchResult searchResult; // SEC-2405 @Test public void searchForSingleEntryInternalAllowsReferrals() throws Exception { String base = ""; String filter = ""; String searchResultName = "ldap://example.com/dc=springframework,dc=org"; Object[] params = new Object[] {}; DirContextAdapter searchResultObject = mock(DirContextAdapter.class); given(this.ctx.search(any(DistinguishedName.class), eq(filter), eq(params), this.searchControls.capture())) .willReturn(this.resultsEnum); given(this.resultsEnum.hasMore()).willReturn(true, false); given(this.resultsEnum.next()).willReturn(this.searchResult); given(this.searchResult.getObject()).willReturn(searchResultObject); SpringSecurityLdapTemplate.searchForSingleEntryInternal(this.ctx, mock(SearchControls.class), base, filter, params); assertThat(this.searchControls.getValue().getReturningObjFlag()).isTrue(); } }
2,576
33.824324
109
java
null
spring-security-main/ldap/src/test/java/org/springframework/security/ldap/userdetails/UserDetailsServiceLdapAuthoritiesPopulatorTests.java
/* * Copyright 2002-2016 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.security.ldap.userdetails; import java.util.Collection; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.ldap.core.DirContextAdapter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.ldap.authentication.UserDetailsServiceLdapAuthoritiesPopulator; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * @author Luke Taylor */ public class UserDetailsServiceLdapAuthoritiesPopulatorTests { @Test public void delegationToUserDetailsServiceReturnsCorrectRoles() { UserDetailsService uds = mock(UserDetailsService.class); UserDetails user = mock(UserDetails.class); given(uds.loadUserByUsername("joe")).willReturn(user); List authorities = AuthorityUtils.createAuthorityList("ROLE_USER"); given(user.getAuthorities()).willReturn(authorities); UserDetailsServiceLdapAuthoritiesPopulator populator = new UserDetailsServiceLdapAuthoritiesPopulator(uds); Collection<? extends GrantedAuthority> auths = populator.getGrantedAuthorities(new DirContextAdapter(), "joe"); assertThat(auths).hasSize(1); assertThat(AuthorityUtils.authorityListToSet(auths).contains("ROLE_USER")).isTrue(); } }
2,139
38.62963
113
java
null
spring-security-main/ldap/src/test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsServiceTests.java
/* * Copyright 2002-2016 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.security.ldap.userdetails; import java.util.Collection; import java.util.Set; import org.junit.jupiter.api.Test; import org.springframework.ldap.core.DirContextAdapter; import org.springframework.ldap.core.DirContextOperations; import org.springframework.ldap.core.DistinguishedName; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.ldap.authentication.MockUserSearch; import org.springframework.security.ldap.authentication.NullLdapAuthoritiesPopulator; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link LdapUserDetailsService} * * @author Luke Taylor */ public class LdapUserDetailsServiceTests { @Test public void rejectsNullSearchObject() { assertThatIllegalArgumentException() .isThrownBy(() -> new LdapUserDetailsService(null, new NullLdapAuthoritiesPopulator())); } @Test public void rejectsNullAuthoritiesPopulator() { assertThatIllegalArgumentException().isThrownBy(() -> new LdapUserDetailsService(new MockUserSearch(), null)); } @Test public void correctAuthoritiesAreReturned() { DirContextAdapter userData = new DirContextAdapter(new DistinguishedName("uid=joe")); LdapUserDetailsService service = new LdapUserDetailsService(new MockUserSearch(userData), new MockAuthoritiesPopulator()); service.setUserDetailsMapper(new LdapUserDetailsMapper()); UserDetails user = service.loadUserByUsername("doesntmatterwegetjoeanyway"); Set<String> authorities = AuthorityUtils.authorityListToSet(user.getAuthorities()); assertThat(authorities).hasSize(1); assertThat(authorities.contains("ROLE_FROM_POPULATOR")).isTrue(); } @Test public void nullPopulatorConstructorReturnsEmptyAuthoritiesList() { DirContextAdapter userData = new DirContextAdapter(new DistinguishedName("uid=joe")); LdapUserDetailsService service = new LdapUserDetailsService(new MockUserSearch(userData)); UserDetails user = service.loadUserByUsername("doesntmatterwegetjoeanyway"); assertThat(user.getAuthorities()).isEmpty(); } class MockAuthoritiesPopulator implements LdapAuthoritiesPopulator { @Override public Collection<GrantedAuthority> getGrantedAuthorities(DirContextOperations userCtx, String username) { return AuthorityUtils.createAuthorityList("ROLE_FROM_POPULATOR"); } } }
3,175
36.809524
112
java
null
spring-security-main/ldap/src/test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsImplTests.java
/* * Copyright 2012-2016 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.security.ldap.userdetails; import org.junit.jupiter.api.Test; import org.springframework.security.core.CredentialsContainer; import static org.assertj.core.api.Assertions.assertThat; /** * Tests {@link LdapUserDetailsImpl} * * @author Joe Grandja */ public class LdapUserDetailsImplTests { @Test public void credentialsAreCleared() { LdapUserDetailsImpl.Essence mutableLdapUserDetails = new LdapUserDetailsImpl.Essence(); mutableLdapUserDetails.setDn("uid=username1,ou=people,dc=example,dc=com"); mutableLdapUserDetails.setUsername("username1"); mutableLdapUserDetails.setPassword("password"); LdapUserDetails ldapUserDetails = mutableLdapUserDetails.createUserDetails(); assertThat(ldapUserDetails).isInstanceOf(CredentialsContainer.class); ldapUserDetails.eraseCredentials(); assertThat(ldapUserDetails.getPassword()).isNull(); } }
1,514
32.666667
89
java
null
spring-security-main/ldap/src/test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsMapperTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.security.ldap.userdetails; import javax.naming.directory.BasicAttribute; import javax.naming.directory.BasicAttributes; import org.junit.jupiter.api.Test; import org.springframework.ldap.core.DirContextAdapter; import org.springframework.ldap.core.DistinguishedName; import org.springframework.security.core.authority.AuthorityUtils; import static org.assertj.core.api.Assertions.assertThat; /** * Tests {@link LdapUserDetailsMapper}. * * @author Luke Taylor * @author Eddú Meléndez */ public class LdapUserDetailsMapperTests { @Test public void testMultipleRoleAttributeValuesAreMappedToAuthorities() { LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); mapper.setConvertToUpperCase(false); mapper.setRolePrefix(""); mapper.setRoleAttributes(new String[] { "userRole" }); DirContextAdapter ctx = new DirContextAdapter(); ctx.setAttributeValues("userRole", new String[] { "X", "Y", "Z" }); ctx.setAttributeValue("uid", "ani"); LdapUserDetailsImpl user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani", AuthorityUtils.NO_AUTHORITIES); assertThat(user.getAuthorities()).hasSize(3); } /** * SEC-303. Non-retrieved role attribute causes NullPointerException */ @Test public void testNonRetrievedRoleAttributeIsIgnored() { LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); mapper.setRoleAttributes(new String[] { "userRole", "nonRetrievedAttribute" }); BasicAttributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("userRole", "x")); DirContextAdapter ctx = new DirContextAdapter(attrs, new DistinguishedName("cn=someName")); ctx.setAttributeValue("uid", "ani"); LdapUserDetailsImpl user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani", AuthorityUtils.NO_AUTHORITIES); assertThat(user.getAuthorities()).hasSize(1); assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())).contains("ROLE_X"); } @Test public void testPasswordAttributeIsMappedCorrectly() { LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); mapper.setPasswordAttributeName("myappsPassword"); BasicAttributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("myappsPassword", "mypassword".getBytes())); DirContextAdapter ctx = new DirContextAdapter(attrs, new DistinguishedName("cn=someName")); ctx.setAttributeValue("uid", "ani"); LdapUserDetails user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani", AuthorityUtils.NO_AUTHORITIES); assertThat(user.getPassword()).isEqualTo("mypassword"); } }
3,203
37.60241
93
java
null
spring-security-main/ldap/src/test/java/org/springframework/security/ldap/userdetails/LdapAuthorityTests.java
/* * Copyright 2002-2016 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.security.ldap.userdetails; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.security.ldap.SpringSecurityLdapTemplate; import static org.assertj.core.api.Assertions.assertThat; /** * @author Filip Hanik */ public class LdapAuthorityTests { public static final String DN = "cn=filip,ou=Users,dc=test,dc=com"; LdapAuthority authority; @BeforeEach public void setUp() { Map<String, List<String>> attributes = new HashMap<>(); attributes.put(SpringSecurityLdapTemplate.DN_KEY, Arrays.asList(DN)); attributes.put("mail", Arrays.asList("filip@ldap.test.org", "filip@ldap.test2.org")); this.authority = new LdapAuthority("testRole", DN, attributes); } @Test public void testGetDn() { assertThat(this.authority.getDn()).isEqualTo(DN); assertThat(this.authority.getAttributeValues(SpringSecurityLdapTemplate.DN_KEY)).isNotNull(); assertThat(this.authority.getAttributeValues(SpringSecurityLdapTemplate.DN_KEY)).hasSize(1); assertThat(this.authority.getFirstAttributeValue(SpringSecurityLdapTemplate.DN_KEY)).isEqualTo(DN); } @Test public void testGetAttributes() { assertThat(this.authority.getAttributes()).isNotNull(); assertThat(this.authority.getAttributeValues("mail")).isNotNull(); assertThat(this.authority.getAttributeValues("mail")).hasSize(2); assertThat(this.authority.getFirstAttributeValue("mail")).isEqualTo("filip@ldap.test.org"); assertThat(this.authority.getAttributeValues("mail").get(0)).isEqualTo("filip@ldap.test.org"); assertThat(this.authority.getAttributeValues("mail").get(1)).isEqualTo("filip@ldap.test2.org"); } @Test public void testGetAuthority() { assertThat(this.authority.getAuthority()).isNotNull(); assertThat(this.authority.getAuthority()).isEqualTo("testRole"); } }
2,553
33.986301
101
java
null
spring-security-main/ldap/src/test/java/org/springframework/security/ldap/userdetails/InetOrgPersonTests.java
/* * Copyright 2002-2016 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.security.ldap.userdetails; import java.util.HashSet; import java.util.Set; import org.junit.jupiter.api.Test; import org.springframework.ldap.core.DirContextAdapter; import org.springframework.ldap.core.DistinguishedName; import static org.assertj.core.api.Assertions.assertThat; /** * @author Luke Taylor */ public class InetOrgPersonTests { @Test public void testUsernameIsMappedFromContextUidIfNotSet() { InetOrgPerson.Essence essence = new InetOrgPerson.Essence(createUserContext()); InetOrgPerson p = (InetOrgPerson) essence.createUserDetails(); assertThat(p.getUsername()).isEqualTo("ghengis"); } @Test public void hashLookupViaEqualObjectRetrievesOriginal() { InetOrgPerson.Essence essence = new InetOrgPerson.Essence(createUserContext()); InetOrgPerson p = (InetOrgPerson) essence.createUserDetails(); essence = new InetOrgPerson.Essence(createUserContext()); InetOrgPerson p2 = (InetOrgPerson) essence.createUserDetails(); Set<InetOrgPerson> set = new HashSet<>(); set.add(p); assertThat(set.contains(p2)).isTrue(); } @Test public void usernameIsDifferentFromContextUidIfSet() { InetOrgPerson.Essence essence = new InetOrgPerson.Essence(createUserContext()); essence.setUsername("joe"); InetOrgPerson p = (InetOrgPerson) essence.createUserDetails(); assertThat(p.getUsername()).isEqualTo("joe"); assertThat(p.getUid()).isEqualTo("ghengis"); } @Test public void attributesMapCorrectlyFromContext() { InetOrgPerson.Essence essence = new InetOrgPerson.Essence(createUserContext()); InetOrgPerson p = (InetOrgPerson) essence.createUserDetails(); assertThat(p.getCarLicense()).isEqualTo("HORS1"); assertThat(p.getMail()).isEqualTo("ghengis@mongolia"); assertThat(p.getGivenName()).isEqualTo("Ghengis"); assertThat(p.getSn()).isEqualTo("Khan"); assertThat(p.getCn()[0]).isEqualTo("Ghengis Khan"); assertThat(p.getEmployeeNumber()).isEqualTo("00001"); assertThat(p.getTelephoneNumber()).isEqualTo("+442075436521"); assertThat(p.getHomePostalAddress()).isEqualTo("Steppes"); assertThat(p.getHomePhone()).isEqualTo("+467575436521"); assertThat(p.getO()).isEqualTo("Hordes"); assertThat(p.getOu()).isEqualTo("Horde1"); assertThat(p.getPostalAddress()).isEqualTo("On the Move"); assertThat(p.getPostalCode()).isEqualTo("Changes Frequently"); assertThat(p.getRoomNumber()).isEqualTo("Yurt 1"); assertThat(p.getStreet()).isEqualTo("Westward Avenue"); assertThat(p.getDescription()).isEqualTo("Scary"); assertThat(p.getDisplayName()).isEqualTo("Ghengis McCann"); assertThat(p.getInitials()).isEqualTo("G"); } @Test public void testPasswordIsSetFromContextUserPassword() { InetOrgPerson.Essence essence = new InetOrgPerson.Essence(createUserContext()); InetOrgPerson p = (InetOrgPerson) essence.createUserDetails(); assertThat(p.getPassword()).isEqualTo("pillage"); } @Test public void mappingBackToContextMatchesOriginalData() { DirContextAdapter ctx1 = createUserContext(); DirContextAdapter ctx2 = new DirContextAdapter(); ctx1.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" }); ctx2.setDn(new DistinguishedName("ignored=ignored")); InetOrgPerson p = (InetOrgPerson) (new InetOrgPerson.Essence(ctx1)).createUserDetails(); p.populateContext(ctx2); assertThat(ctx2).isEqualTo(ctx1); } @Test public void copyMatchesOriginalData() { DirContextAdapter ctx1 = createUserContext(); DirContextAdapter ctx2 = new DirContextAdapter(); ctx2.setDn(new DistinguishedName("ignored=ignored")); ctx1.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" }); InetOrgPerson p = (InetOrgPerson) (new InetOrgPerson.Essence(ctx1)).createUserDetails(); InetOrgPerson p2 = (InetOrgPerson) new InetOrgPerson.Essence(p).createUserDetails(); p2.populateContext(ctx2); assertThat(ctx2).isEqualTo(ctx1); } private DirContextAdapter createUserContext() { DirContextAdapter ctx = new DirContextAdapter(); ctx.setDn(new DistinguishedName("ignored=ignored")); ctx.setAttributeValue("uid", "ghengis"); ctx.setAttributeValue("userPassword", "pillage"); ctx.setAttributeValue("carLicense", "HORS1"); ctx.setAttributeValue("cn", "Ghengis Khan"); ctx.setAttributeValue("description", "Scary"); ctx.setAttributeValue("destinationIndicator", "West"); ctx.setAttributeValue("displayName", "Ghengis McCann"); ctx.setAttributeValue("givenName", "Ghengis"); ctx.setAttributeValue("homePhone", "+467575436521"); ctx.setAttributeValue("initials", "G"); ctx.setAttributeValue("employeeNumber", "00001"); ctx.setAttributeValue("homePostalAddress", "Steppes"); ctx.setAttributeValue("mail", "ghengis@mongolia"); ctx.setAttributeValue("mobile", "always"); ctx.setAttributeValue("o", "Hordes"); ctx.setAttributeValue("ou", "Horde1"); ctx.setAttributeValue("postalAddress", "On the Move"); ctx.setAttributeValue("postalCode", "Changes Frequently"); ctx.setAttributeValue("roomNumber", "Yurt 1"); ctx.setAttributeValue("roomNumber", "Yurt 1"); ctx.setAttributeValue("sn", "Khan"); ctx.setAttributeValue("street", "Westward Avenue"); ctx.setAttributeValue("telephoneNumber", "+442075436521"); return ctx; } }
5,920
39.278912
90
java
null
spring-security-main/ldap/src/test/java/org/springframework/security/ldap/aot/hint/LdapSecurityRuntimeHintsTests.java
/* * Copyright 2002-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.security.ldap.aot.hint; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.aot.hint.RuntimeHints; import org.springframework.aot.hint.RuntimeHintsRegistrar; import org.springframework.aot.hint.TypeReference; import org.springframework.aot.hint.predicate.RuntimeHintsPredicates; import org.springframework.core.io.support.SpringFactoriesLoader; import org.springframework.util.ClassUtils; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link LdapSecurityRuntimeHints} * * @author Marcus Da Coregio */ class LdapSecurityRuntimeHintsTests { private final RuntimeHints hints = new RuntimeHints(); @BeforeEach void setup() { SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories").load(RuntimeHintsRegistrar.class) .forEach((registrar) -> registrar.registerHints(this.hints, ClassUtils.getDefaultClassLoader())); } @Test void ldifResourcesHasHints() { assertThat(RuntimeHintsPredicates.resource().forResource("users.ldif")).accepts(this.hints); } @Test void ldapCtxFactoryHasHints() { assertThat(RuntimeHintsPredicates.reflection().onType(TypeReference.of("com.sun.jndi.ldap.LdapCtxFactory"))) .accepts(this.hints); } }
1,902
31.810345
110
java
null
spring-security-main/ldap/src/test/java/org/springframework/security/ldap/jackson2/PersonMixinTests.java
/* * 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.security.ldap.jackson2; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.json.JSONException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.ldap.core.DirContextAdapter; import org.springframework.ldap.core.DistinguishedName; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.ldap.userdetails.Person; import org.springframework.security.ldap.userdetails.PersonContextMapper; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link PersonMixin}. */ public class PersonMixinTests { private static final String USER_PASSWORD = "Password1234"; private static final String AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.Collections$UnmodifiableRandomAccessList\", []]"; // @formatter:off private static final String PERSON_JSON = "{" + "\"@class\": \"org.springframework.security.ldap.userdetails.Person\", " + "\"dn\": \"ignored=ignored\"," + "\"username\": \"ghengis\"," + "\"password\": \"" + USER_PASSWORD + "\"," + "\"givenName\": \"Ghengis\"," + "\"sn\": \"Khan\"," + "\"cn\": [\"java.util.Arrays$ArrayList\",[\"Ghengis Khan\"]]," + "\"description\": \"Scary\"," + "\"telephoneNumber\": \"+442075436521\"," + "\"accountNonExpired\": true, " + "\"accountNonLocked\": true, " + "\"credentialsNonExpired\": true, " + "\"enabled\": true, " + "\"authorities\": " + AUTHORITIES_ARRAYLIST_JSON + "," + "\"graceLoginsRemaining\": " + Integer.MAX_VALUE + "," + "\"timeBeforeExpiration\": " + Integer.MAX_VALUE + "}"; // @formatter:on private ObjectMapper mapper; @BeforeEach public void setup() { ClassLoader loader = getClass().getClassLoader(); this.mapper = new ObjectMapper(); this.mapper.registerModules(SecurityJackson2Modules.getModules(loader)); } @Test public void serializeWhenMixinRegisteredThenSerializes() throws Exception { PersonContextMapper mapper = new PersonContextMapper(); Person p = (Person) mapper.mapUserFromContext(createUserContext(), "ghengis", AuthorityUtils.NO_AUTHORITIES); String json = this.mapper.writeValueAsString(p); JSONAssert.assertEquals(PERSON_JSON, json, true); } @Test public void serializeWhenEraseCredentialInvokedThenUserPasswordIsNull() throws JsonProcessingException, JSONException { PersonContextMapper mapper = new PersonContextMapper(); Person p = (Person) mapper.mapUserFromContext(createUserContext(), "ghengis", AuthorityUtils.NO_AUTHORITIES); p.eraseCredentials(); String actualJson = this.mapper.writeValueAsString(p); JSONAssert.assertEquals(PERSON_JSON.replaceAll("\"" + USER_PASSWORD + "\"", "null"), actualJson, true); } @Test public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() { assertThatExceptionOfType(JsonProcessingException.class) .isThrownBy(() -> new ObjectMapper().readValue(PERSON_JSON, Person.class)); } @Test public void deserializeWhenMixinRegisteredThenDeserializes() throws Exception { PersonContextMapper mapper = new PersonContextMapper(); Person expectedAuthentication = (Person) mapper.mapUserFromContext(createUserContext(), "ghengis", AuthorityUtils.NO_AUTHORITIES); Person authentication = this.mapper.readValue(PERSON_JSON, Person.class); assertThat(authentication.getAuthorities()).containsExactlyElementsOf(expectedAuthentication.getAuthorities()); assertThat(authentication.getDn()).isEqualTo(expectedAuthentication.getDn()); assertThat(authentication.getDescription()).isEqualTo(expectedAuthentication.getDescription()); assertThat(authentication.getUsername()).isEqualTo(expectedAuthentication.getUsername()); assertThat(authentication.getPassword()).isEqualTo(expectedAuthentication.getPassword()); assertThat(authentication.getSn()).isEqualTo(expectedAuthentication.getSn()); assertThat(authentication.getGivenName()).isEqualTo(expectedAuthentication.getGivenName()); assertThat(authentication.getTelephoneNumber()).isEqualTo(expectedAuthentication.getTelephoneNumber()); assertThat(authentication.getGraceLoginsRemaining()) .isEqualTo(expectedAuthentication.getGraceLoginsRemaining()); assertThat(authentication.getTimeBeforeExpiration()) .isEqualTo(expectedAuthentication.getTimeBeforeExpiration()); assertThat(authentication.isAccountNonExpired()).isEqualTo(expectedAuthentication.isAccountNonExpired()); assertThat(authentication.isAccountNonLocked()).isEqualTo(expectedAuthentication.isAccountNonLocked()); assertThat(authentication.isEnabled()).isEqualTo(expectedAuthentication.isEnabled()); assertThat(authentication.isCredentialsNonExpired()) .isEqualTo(expectedAuthentication.isCredentialsNonExpired()); } private DirContextAdapter createUserContext() { DirContextAdapter ctx = new DirContextAdapter(); ctx.setDn(new DistinguishedName("ignored=ignored")); ctx.setAttributeValue("userPassword", USER_PASSWORD); ctx.setAttributeValue("cn", "Ghengis Khan"); ctx.setAttributeValue("description", "Scary"); ctx.setAttributeValue("givenName", "Ghengis"); ctx.setAttributeValue("sn", "Khan"); ctx.setAttributeValue("telephoneNumber", "+442075436521"); return ctx; } }
6,116
43.007194
121
java
null
spring-security-main/ldap/src/test/java/org/springframework/security/ldap/jackson2/InetOrgPersonMixinTests.java
/* * 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.security.ldap.jackson2; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.json.JSONException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.ldap.core.DirContextAdapter; import org.springframework.ldap.core.DistinguishedName; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.ldap.userdetails.InetOrgPerson; import org.springframework.security.ldap.userdetails.InetOrgPersonContextMapper; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link InetOrgPersonMixin}. */ public class InetOrgPersonMixinTests { private static final String USER_PASSWORD = "Password1234"; private static final String AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.Collections$UnmodifiableRandomAccessList\", []]"; // @formatter:off private static final String INET_ORG_PERSON_JSON = "{\n" + "\"@class\": \"org.springframework.security.ldap.userdetails.InetOrgPerson\"," + "\"dn\": \"ignored=ignored\"," + "\"uid\": \"ghengis\"," + "\"username\": \"ghengis\"," + "\"password\": \"" + USER_PASSWORD + "\"," + "\"carLicense\": \"HORS1\"," + "\"givenName\": \"Ghengis\"," + "\"destinationIndicator\": \"West\"," + "\"displayName\": \"Ghengis McCann\"," + "\"givenName\": \"Ghengis\"," + "\"homePhone\": \"+467575436521\"," + "\"initials\": \"G\"," + "\"employeeNumber\": \"00001\"," + "\"homePostalAddress\": \"Steppes\"," + "\"mail\": \"ghengis@mongolia\"," + "\"mobile\": \"always\"," + "\"o\": \"Hordes\"," + "\"ou\": \"Horde1\"," + "\"postalAddress\": \"On the Move\"," + "\"postalCode\": \"Changes Frequently\"," + "\"roomNumber\": \"Yurt 1\"," + "\"sn\": \"Khan\"," + "\"street\": \"Westward Avenue\"," + "\"telephoneNumber\": \"+442075436521\"," + "\"departmentNumber\": \"5679\"," + "\"title\": \"T\"," + "\"cn\": [\"java.util.Arrays$ArrayList\",[\"Ghengis Khan\"]]," + "\"description\": \"Scary\"," + "\"accountNonExpired\": true, " + "\"accountNonLocked\": true, " + "\"credentialsNonExpired\": true, " + "\"enabled\": true, " + "\"authorities\": " + AUTHORITIES_ARRAYLIST_JSON + "," + "\"graceLoginsRemaining\": " + Integer.MAX_VALUE + "," + "\"timeBeforeExpiration\": " + Integer.MAX_VALUE + "}"; // @formatter:on private ObjectMapper mapper; @BeforeEach public void setup() { ClassLoader loader = getClass().getClassLoader(); this.mapper = new ObjectMapper(); this.mapper.registerModules(SecurityJackson2Modules.getModules(loader)); } @Test public void serializeWhenMixinRegisteredThenSerializes() throws Exception { InetOrgPersonContextMapper mapper = new InetOrgPersonContextMapper(); InetOrgPerson p = (InetOrgPerson) mapper.mapUserFromContext(createUserContext(), "ghengis", AuthorityUtils.NO_AUTHORITIES); String json = this.mapper.writeValueAsString(p); JSONAssert.assertEquals(INET_ORG_PERSON_JSON, json, true); } @Test public void serializeWhenEraseCredentialInvokedThenUserPasswordIsNull() throws JsonProcessingException, JSONException { InetOrgPersonContextMapper mapper = new InetOrgPersonContextMapper(); InetOrgPerson p = (InetOrgPerson) mapper.mapUserFromContext(createUserContext(), "ghengis", AuthorityUtils.NO_AUTHORITIES); p.eraseCredentials(); String actualJson = this.mapper.writeValueAsString(p); JSONAssert.assertEquals(INET_ORG_PERSON_JSON.replaceAll("\"" + USER_PASSWORD + "\"", "null"), actualJson, true); } @Test public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() { assertThatExceptionOfType(JsonProcessingException.class) .isThrownBy(() -> new ObjectMapper().readValue(INET_ORG_PERSON_JSON, InetOrgPerson.class)); } @Test public void deserializeWhenMixinRegisteredThenDeserializes() throws Exception { InetOrgPersonContextMapper mapper = new InetOrgPersonContextMapper(); InetOrgPerson expectedAuthentication = (InetOrgPerson) mapper.mapUserFromContext(createUserContext(), "ghengis", AuthorityUtils.NO_AUTHORITIES); InetOrgPerson authentication = this.mapper.readValue(INET_ORG_PERSON_JSON, InetOrgPerson.class); assertThat(authentication.getAuthorities()).containsExactlyElementsOf(expectedAuthentication.getAuthorities()); assertThat(authentication.getCarLicense()).isEqualTo(expectedAuthentication.getCarLicense()); assertThat(authentication.getDepartmentNumber()).isEqualTo(expectedAuthentication.getDepartmentNumber()); assertThat(authentication.getDestinationIndicator()) .isEqualTo(expectedAuthentication.getDestinationIndicator()); assertThat(authentication.getDn()).isEqualTo(expectedAuthentication.getDn()); assertThat(authentication.getDescription()).isEqualTo(expectedAuthentication.getDescription()); assertThat(authentication.getDisplayName()).isEqualTo(expectedAuthentication.getDisplayName()); assertThat(authentication.getUid()).isEqualTo(expectedAuthentication.getUid()); assertThat(authentication.getUsername()).isEqualTo(expectedAuthentication.getUsername()); assertThat(authentication.getPassword()).isEqualTo(expectedAuthentication.getPassword()); assertThat(authentication.getHomePhone()).isEqualTo(expectedAuthentication.getHomePhone()); assertThat(authentication.getEmployeeNumber()).isEqualTo(expectedAuthentication.getEmployeeNumber()); assertThat(authentication.getHomePostalAddress()).isEqualTo(expectedAuthentication.getHomePostalAddress()); assertThat(authentication.getInitials()).isEqualTo(expectedAuthentication.getInitials()); assertThat(authentication.getMail()).isEqualTo(expectedAuthentication.getMail()); assertThat(authentication.getMobile()).isEqualTo(expectedAuthentication.getMobile()); assertThat(authentication.getO()).isEqualTo(expectedAuthentication.getO()); assertThat(authentication.getOu()).isEqualTo(expectedAuthentication.getOu()); assertThat(authentication.getPostalAddress()).isEqualTo(expectedAuthentication.getPostalAddress()); assertThat(authentication.getPostalCode()).isEqualTo(expectedAuthentication.getPostalCode()); assertThat(authentication.getRoomNumber()).isEqualTo(expectedAuthentication.getRoomNumber()); assertThat(authentication.getStreet()).isEqualTo(expectedAuthentication.getStreet()); assertThat(authentication.getSn()).isEqualTo(expectedAuthentication.getSn()); assertThat(authentication.getTitle()).isEqualTo(expectedAuthentication.getTitle()); assertThat(authentication.getGivenName()).isEqualTo(expectedAuthentication.getGivenName()); assertThat(authentication.getTelephoneNumber()).isEqualTo(expectedAuthentication.getTelephoneNumber()); assertThat(authentication.getGraceLoginsRemaining()) .isEqualTo(expectedAuthentication.getGraceLoginsRemaining()); assertThat(authentication.getTimeBeforeExpiration()) .isEqualTo(expectedAuthentication.getTimeBeforeExpiration()); assertThat(authentication.isAccountNonExpired()).isEqualTo(expectedAuthentication.isAccountNonExpired()); assertThat(authentication.isAccountNonLocked()).isEqualTo(expectedAuthentication.isAccountNonLocked()); assertThat(authentication.isEnabled()).isEqualTo(expectedAuthentication.isEnabled()); assertThat(authentication.isCredentialsNonExpired()) .isEqualTo(expectedAuthentication.isCredentialsNonExpired()); } private DirContextAdapter createUserContext() { DirContextAdapter ctx = new DirContextAdapter(); ctx.setDn(new DistinguishedName("ignored=ignored")); ctx.setAttributeValue("uid", "ghengis"); ctx.setAttributeValue("userPassword", USER_PASSWORD); ctx.setAttributeValue("carLicense", "HORS1"); ctx.setAttributeValue("cn", "Ghengis Khan"); ctx.setAttributeValue("description", "Scary"); ctx.setAttributeValue("destinationIndicator", "West"); ctx.setAttributeValue("displayName", "Ghengis McCann"); ctx.setAttributeValue("givenName", "Ghengis"); ctx.setAttributeValue("homePhone", "+467575436521"); ctx.setAttributeValue("initials", "G"); ctx.setAttributeValue("employeeNumber", "00001"); ctx.setAttributeValue("homePostalAddress", "Steppes"); ctx.setAttributeValue("mail", "ghengis@mongolia"); ctx.setAttributeValue("mobile", "always"); ctx.setAttributeValue("o", "Hordes"); ctx.setAttributeValue("ou", "Horde1"); ctx.setAttributeValue("postalAddress", "On the Move"); ctx.setAttributeValue("postalCode", "Changes Frequently"); ctx.setAttributeValue("roomNumber", "Yurt 1"); ctx.setAttributeValue("sn", "Khan"); ctx.setAttributeValue("street", "Westward Avenue"); ctx.setAttributeValue("telephoneNumber", "+442075436521"); ctx.setAttributeValue("departmentNumber", "5679"); ctx.setAttributeValue("title", "T"); return ctx; } }
9,604
47.756345
121
java
null
spring-security-main/ldap/src/test/java/org/springframework/security/ldap/jackson2/LdapUserDetailsImplMixinTests.java
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.ldap.jackson2; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.json.JSONException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.ldap.core.DirContextAdapter; import org.springframework.ldap.core.DistinguishedName; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.ldap.userdetails.LdapUserDetailsImpl; import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link LdapUserDetailsImplMixin}. */ public class LdapUserDetailsImplMixinTests { private static final String USER_PASSWORD = "Password1234"; private static final String AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.Collections$UnmodifiableRandomAccessList\", []]"; // @formatter:off private static final String USER_JSON = "{" + "\"@class\": \"org.springframework.security.ldap.userdetails.LdapUserDetailsImpl\", " + "\"dn\": \"ignored=ignored\"," + "\"username\": \"ghengis\"," + "\"password\": \"" + USER_PASSWORD + "\"," + "\"accountNonExpired\": true, " + "\"accountNonLocked\": true, " + "\"credentialsNonExpired\": true, " + "\"enabled\": true, " + "\"authorities\": " + AUTHORITIES_ARRAYLIST_JSON + "," + "\"graceLoginsRemaining\": " + Integer.MAX_VALUE + "," + "\"timeBeforeExpiration\": " + Integer.MAX_VALUE + "}"; // @formatter:on private ObjectMapper mapper; @BeforeEach public void setup() { ClassLoader loader = getClass().getClassLoader(); this.mapper = new ObjectMapper(); this.mapper.registerModules(SecurityJackson2Modules.getModules(loader)); } @Test public void serializeWhenMixinRegisteredThenSerializes() throws Exception { LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); LdapUserDetailsImpl p = (LdapUserDetailsImpl) mapper.mapUserFromContext(createUserContext(), "ghengis", AuthorityUtils.NO_AUTHORITIES); String json = this.mapper.writeValueAsString(p); JSONAssert.assertEquals(USER_JSON, json, true); } @Test public void serializeWhenEraseCredentialInvokedThenUserPasswordIsNull() throws JsonProcessingException, JSONException { LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); LdapUserDetailsImpl p = (LdapUserDetailsImpl) mapper.mapUserFromContext(createUserContext(), "ghengis", AuthorityUtils.NO_AUTHORITIES); p.eraseCredentials(); String actualJson = this.mapper.writeValueAsString(p); JSONAssert.assertEquals(USER_JSON.replaceAll("\"" + USER_PASSWORD + "\"", "null"), actualJson, true); } @Test public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() { assertThatExceptionOfType(JsonProcessingException.class) .isThrownBy(() -> new ObjectMapper().readValue(USER_JSON, LdapUserDetailsImpl.class)); } @Test public void deserializeWhenMixinRegisteredThenDeserializes() throws Exception { LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); LdapUserDetailsImpl expectedAuthentication = (LdapUserDetailsImpl) mapper .mapUserFromContext(createUserContext(), "ghengis", AuthorityUtils.NO_AUTHORITIES); LdapUserDetailsImpl authentication = this.mapper.readValue(USER_JSON, LdapUserDetailsImpl.class); assertThat(authentication.getAuthorities()).containsExactlyElementsOf(expectedAuthentication.getAuthorities()); assertThat(authentication.getDn()).isEqualTo(expectedAuthentication.getDn()); assertThat(authentication.getUsername()).isEqualTo(expectedAuthentication.getUsername()); assertThat(authentication.getPassword()).isEqualTo(expectedAuthentication.getPassword()); assertThat(authentication.getGraceLoginsRemaining()) .isEqualTo(expectedAuthentication.getGraceLoginsRemaining()); assertThat(authentication.getTimeBeforeExpiration()) .isEqualTo(expectedAuthentication.getTimeBeforeExpiration()); assertThat(authentication.isAccountNonExpired()).isEqualTo(expectedAuthentication.isAccountNonExpired()); assertThat(authentication.isAccountNonLocked()).isEqualTo(expectedAuthentication.isAccountNonLocked()); assertThat(authentication.isEnabled()).isEqualTo(expectedAuthentication.isEnabled()); assertThat(authentication.isCredentialsNonExpired()) .isEqualTo(expectedAuthentication.isCredentialsNonExpired()); } private DirContextAdapter createUserContext() { DirContextAdapter ctx = new DirContextAdapter(); ctx.setDn(new DistinguishedName("ignored=ignored")); ctx.setAttributeValue("userPassword", USER_PASSWORD); return ctx; } }
5,465
42.03937
121
java