Skip to content

Commit

Permalink
Polishing
Browse files Browse the repository at this point in the history
1. fix deprecations
2. fix generics
3. use lambda instead of anonymous class
4. mark some fields as final
  • Loading branch information
quaff authored and marcusdacoregio committed Oct 3, 2023
1 parent 831d65a commit 11ce4b4
Show file tree
Hide file tree
Showing 18 changed files with 96 additions and 98 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
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;

Expand All @@ -12,18 +10,12 @@
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"));
}
});
}
project.getPlugins().withType(MavenPublishPlugin.class).all(mavenPublish -> {
PublishingExtension publishing = project.getExtensions().getByType(PublishingExtension.class);
publishing.getRepositories().maven(maven -> {
maven.setName("local");
maven.setUrl(new File(project.getRootProject().getBuildDir(), "publications/repos"));
});
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.junit.jupiter.api.io.TempDir;

import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Path;

import static org.assertj.core.api.Assertions.assertThat;
Expand All @@ -30,7 +31,7 @@ public void multiModuleApi() throws Exception {
File allClasses = new File(testKit.getRootDir(), "build/api/allclasses-noframe.html");
File index = new File(testKit.getRootDir(), "build/api/allclasses-index.html");
File listing = allClasses.exists() ? allClasses : index;
String listingText = FileUtils.readFileToString(listing);
String listingText = FileUtils.readFileToString(listing, Charset.defaultCharset());
assertThat(listingText).contains("sample/Api.html");
assertThat(listingText).contains("sample/Impl.html");
assertThat(listingText).doesNotContain("sample/Sample.html");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.junit.jupiter.api.io.TempDir;

import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
Expand Down Expand Up @@ -56,6 +57,6 @@ public void signArchivesWhenInMemory() throws Exception {
}

public String getSigningKey() throws Exception {
return IOUtils.toString(getClass().getResource("/test-private.pgp"));
return IOUtils.toString(getClass().getResource("/test-private.pgp"), Charset.defaultCharset());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.quality.Strictness;

import org.springframework.security.core.AuthenticatedPrincipal;
import org.springframework.security.core.Authentication;
Expand Down Expand Up @@ -154,7 +155,7 @@ void expireNow() {
private Session createSession(String sessionId, String userName, Instant lastAccessed) {
MapSession session = new MapSession(sessionId);
session.setLastAccessedTime(lastAccessed);
Authentication authentication = mock(Authentication.class, withSettings().lenient());
Authentication authentication = mock(Authentication.class, withSettings().strictness(Strictness.LENIENT));
given(authentication.getName()).willReturn(userName);
SecurityContextImpl securityContext = new SecurityContextImpl();
securityContext.setAuthentication(authentication);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class OnCommittedResponseWrapperTests {

private static final String NL = "\r\n";

@Mock(lenient = true)
@Mock(strictness = Mock.Strictness.LENIENT)
HttpServletResponse delegate;

@Mock
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
@ExtendWith(MockitoExtension.class)
class SpringSessionWebSessionStoreTests<S extends Session> {

@Mock(lenient = true)
@Mock(strictness = Mock.Strictness.LENIENT)
private ReactiveSessionRepository<S> sessionRepository;

@Mock
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,13 @@
@ExtendWith(MockitoExtension.class)
class WebSocketRegistryListenerTests {

@Mock(lenient = true)
@Mock(strictness = Mock.Strictness.LENIENT)
private WebSocketSession wsSession;

@Mock(lenient = true)
@Mock(strictness = Mock.Strictness.LENIENT)
private WebSocketSession wsSession2;

@Mock(lenient = true)
@Mock(strictness = Mock.Strictness.LENIENT)
private Message<byte[]> message;

@Mock
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
@ExtendWith(MockitoExtension.class)
class SessionRepositoryMessageInterceptorTests {

@Mock(lenient = true)
@Mock(strictness = Mock.Strictness.LENIENT)
SessionRepository<Session> sessionRepository;

@Mock
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
Expand Down Expand Up @@ -72,57 +73,62 @@ void setUp() {
void logoutShouldDeleteOldSessionFromMongoDB() {

// 1. Login and capture the SESSION cookie value.

// @formatter:off
FluxExchangeResult<String> loginResult = this.client.post().uri("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED) //
.body(BodyInserters //
.fromFormData("username", "admin") //
.with("password", "password")) //
.exchange() //
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(BodyInserters
.fromFormData("username", "admin")
.with("password", "password"))
.exchange()
.returnResult(String.class);
// @formatter:on

AssertionsForClassTypes.assertThat(loginResult.getResponseHeaders().getLocation()).isEqualTo(URI.create("/"));

String originalSessionId = loginResult.getResponseCookies().getFirst("SESSION").getValue();

// 2. Fetch a protected resource using the SESSION cookie.

this.client.get().uri("/hello") //
.cookie("SESSION", originalSessionId) //
.exchange() //
.expectStatus().isOk() //
.returnResult(String.class).getResponseBody() //
.as(StepVerifier::create) //
.expectNext("HelloWorld") //
// @formatter:off
this.client.get().uri("/hello")
.cookie("SESSION", originalSessionId)
.exchange()
.expectStatus().isOk()
.returnResult(String.class).getResponseBody()
.as(StepVerifier::create)
.expectNext("HelloWorld")
.verifyComplete();
// @formatter:on

// 3. Logout using the SESSION cookie, and capture the new SESSION cookie.

String newSessionId = this.client.post().uri("/logout") //
.cookie("SESSION", originalSessionId) //
.exchange() //
.expectStatus().isFound() //
// @formatter:off
String newSessionId = this.client.post().uri("/logout")
.cookie("SESSION", originalSessionId)
.exchange()
.expectStatus().isFound()
.returnResult(String.class).getResponseCookies().getFirst("SESSION").getValue();
// @formatter:on

AssertionsForClassTypes.assertThat(newSessionId).isNotEqualTo(originalSessionId);

// 4. Verify the new SESSION cookie is not yet authorized.

this.client.get().uri("/hello") //
.cookie("SESSION", newSessionId) //
.exchange() //
.expectStatus().isFound() //
// @formatter:off
this.client.get().uri("/hello")
.cookie("SESSION", newSessionId)
.exchange()
.expectStatus().isFound()
.expectHeader()
.value(HttpHeaders.LOCATION, (value) -> AssertionsForClassTypes.assertThat(value).isEqualTo("/login"));
// @formatter:on

// 5. Verify the original SESSION cookie no longer works.

this.client.get().uri("/hello") //
.cookie("SESSION", originalSessionId) //
.exchange() //
.expectStatus().isFound() //
// @formatter:off
this.client.get().uri("/hello")
.cookie("SESSION", originalSessionId)
.exchange()
.expectStatus().isFound()
.expectHeader()
.value(HttpHeaders.LOCATION, (value) -> AssertionsForClassTypes.assertThat(value).isEqualTo("/login"));
// @formatter:on
}

@RestController
Expand All @@ -141,24 +147,24 @@ static class SecurityConfig {

@Bean
SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http //
.logout()//
/**/.and() //
.formLogin() //
/**/.and() //
.csrf().disable() //
.authorizeExchange() //
.anyExchange().authenticated() //
/**/.and() //
// @formatter:off
return http
.logout(Customizer.withDefaults())
.formLogin(Customizer.withDefaults())
.csrf((csrf) -> csrf.disable())
.authorizeExchange((ae) -> ae.anyExchange().authenticated())
.build();
// @formatter:on
}

@Bean
MapReactiveUserDetailsService userDetailsService() {
return new MapReactiveUserDetailsService(User.withUsername("admin") //
.password("{noop}password") //
.roles("USER,ADMIN") //
// @formatter:off
return new MapReactiveUserDetailsService(User.withUsername("admin")
.password("{noop}password")
.roles("USER,ADMIN")
.build());
// @formatter:on
}

@Bean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
Expand Down Expand Up @@ -141,26 +142,24 @@ static class SecurityConfig {

@Bean
SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {

return http //
.logout()//
/**/.and() //
.formLogin() //
/**/.and() //
.csrf().disable() //
.authorizeExchange() //
.anyExchange().authenticated() //
/**/.and() //
// @formatter:off
return http
.logout(Customizer.withDefaults())
.formLogin(Customizer.withDefaults())
.csrf((csrf) -> csrf.disable())
.authorizeExchange((ae) -> ae.anyExchange().authenticated())
.build();
// @formatter:on
}

@Bean
MapReactiveUserDetailsService userDetailsService() {

return new MapReactiveUserDetailsService(User.withUsername("admin") //
.password("{noop}password") //
.roles("USER,ADMIN") //
// @formatter:off
return new MapReactiveUserDetailsService(User.withUsername("admin")
.password("{noop}password")
.roles("USER,ADMIN")
.build());
// @formatter:on
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,14 @@ class MongoSession implements Session {
* NOTE: This was originally stored in unicode format. Delomboking the code caused it
* to get converted to another encoding, which isn't supported on all systems, so we
* migrated back to unicode. The same character is being represented ensuring binary
* compatibility.
*
* See https://www.compart.com/en/unicode/U+F607
* compatibility. See <a href=
* "https://www.compart.com/en/unicode/U+F607">https://www.compart.com/en/unicode/U+F607</a>
*/
private static final char DOT_COVER_CHAR = '\uF607';

private String id;

private String originalSessionId;
private final String originalSessionId;

private long createdMillis = System.currentTimeMillis();

Expand All @@ -66,7 +65,7 @@ class MongoSession implements Session {

private Date expireAt;

private Map<String, Object> attrs = new HashMap<>();
private final Map<String, Object> attrs = new HashMap<>();

private transient SessionIdGenerator sessionIdGenerator = UuidSessionIdGenerator.getInstance();

Expand Down Expand Up @@ -135,6 +134,7 @@ public String changeSessionId() {

@Override
@Nullable
@SuppressWarnings("unchecked")
public <T> T getAttribute(String attributeName) {
return (T) this.attrs.get(coverDot(attributeName));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class RedisSessionExpirationPolicyTests {
// Wed Apr 15 10:27:32 CDT 2015
private static final Long ONE_MINUTE_AGO = 1429111652346L;

@Mock(lenient = true)
@Mock(strictness = Mock.Strictness.LENIENT)
RedisOperations<String, Object> sessionRedisOperations;

@Mock
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ class RedisSessionRepositoryTests {

private static final String TEST_SESSION_KEY = getSessionKey(TEST_SESSION_ID);

@Mock(lenient = true)
@Mock(strictness = Mock.Strictness.LENIENT)
private RedisOperations<String, Object> sessionRedisOperations;

@Mock
Expand Down Expand Up @@ -311,7 +311,6 @@ void save_SessionNotExists_ShouldThrowException() {
}

@Test
@SuppressWarnings("unchecked")
void findById_SessionExists_ShouldReturnSession() {
Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS);
given(this.sessionHashOperations.entries(eq(TEST_SESSION_KEY)))
Expand All @@ -334,7 +333,6 @@ void findById_SessionExists_ShouldReturnSession() {
}

@Test
@SuppressWarnings("unchecked")
void findById_SessionExistsAndIsExpired_ShouldReturnNull() {
given(this.sessionHashOperations.entries(eq(TEST_SESSION_KEY)))
.willReturn(mapOf(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(),
Expand Down Expand Up @@ -410,7 +408,7 @@ private static Instant getExpiry(RedisSession session) {
.plusSeconds(session.getMaxInactiveInterval().getSeconds());
}

private static Map mapOf(Object... objects) {
private static Map<String, Object> mapOf(Object... objects) {
Map<String, Object> result = new HashMap<>();
if (objects != null) {
for (int i = 0; i < objects.length; i += 2) {
Expand Down
Loading

0 comments on commit 11ce4b4

Please sign in to comment.