Skip to content

Commit 9b603b9

Browse files
krzykjzheaux
authored andcommitted
Using modern Java features
1 parent 7e01ebd commit 9b603b9

File tree

72 files changed

+208
-404
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

72 files changed

+208
-404
lines changed

acl/src/main/java/org/springframework/security/acls/AclPermissionEvaluator.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,7 @@ List<Permission> resolvePermission(Object permission) {
118118
if (permission instanceof Permission[]) {
119119
return Arrays.asList((Permission[]) permission);
120120
}
121-
if (permission instanceof String) {
122-
String permString = (String) permission;
121+
if (permission instanceof String permString) {
123122
Permission p = buildPermission(permString);
124123
if (p != null) {
125124
return Arrays.asList(p);

acl/src/main/java/org/springframework/security/acls/domain/AbstractPermission.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,9 @@ public final boolean equals(Object obj) {
5656
if (obj == null) {
5757
return false;
5858
}
59-
if (!(obj instanceof Permission)) {
59+
if (!(obj instanceof Permission other)) {
6060
return false;
6161
}
62-
Permission other = (Permission) obj;
6362
return (this.mask == other.getMask());
6463
}
6564

acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTests.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -454,7 +454,7 @@ public void testProcessingCustomSid() {
454454
CustomSid customSid = new CustomSid("Custom sid");
455455
given(customJdbcMutableAclService.createOrRetrieveSidPrimaryKey("Custom sid", false, false)).willReturn(1L);
456456
Long result = customJdbcMutableAclService.createOrRetrieveSidPrimaryKey(customSid, false);
457-
assertThat(new Long(1L)).isEqualTo(result);
457+
assertThat(Long.valueOf(1L)).isEqualTo(result);
458458
}
459459

460460
protected Authentication getAuth() {

buildSrc/src/main/java/org/springframework/gradle/antora/AntoraVersionPlugin.java

+2-7
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import org.gradle.api.GradleException;
55
import org.gradle.api.Plugin;
66
import org.gradle.api.Project;
7-
import org.gradle.api.Task;
87
import org.gradle.api.tasks.TaskProvider;
98
import org.gradle.language.base.plugins.LifecycleBasePlugin;
109

@@ -27,12 +26,8 @@ public void execute(CheckAntoraVersionTask antoraCheckVersion) {
2726
project.getPlugins().withType(LifecycleBasePlugin.class, new Action<LifecycleBasePlugin>() {
2827
@Override
2928
public void execute(LifecycleBasePlugin lifecycleBasePlugin) {
30-
project.getTasks().named(LifecycleBasePlugin.CHECK_TASK_NAME).configure(new Action<Task>() {
31-
@Override
32-
public void execute(Task check) {
33-
check.dependsOn(antoraCheckVersion);
34-
}
35-
});
29+
project.getTasks().named(LifecycleBasePlugin.CHECK_TASK_NAME)
30+
.configure(check -> check.dependsOn(antoraCheckVersion));
3631
}
3732
});
3833
project.getTasks().register("antoraUpdateVersion", UpdateAntoraVersionTask.class, new Action<UpdateAntoraVersionTask>() {

buildSrc/src/main/java/org/springframework/gradle/classpath/CheckClasspathForProhibitedDependenciesPlugin.java

+1-3
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,7 @@ public class CheckClasspathForProhibitedDependenciesPlugin implements Plugin<Pro
3535
@Override
3636
public void apply(Project project) {
3737
project.getPlugins().apply(CheckProhibitedDependenciesLifecyclePlugin.class);
38-
project.getPlugins().withType(JavaBasePlugin.class, javaBasePlugin -> {
39-
configureProhibitedDependencyChecks(project);
40-
});
38+
project.getPlugins().withType(JavaBasePlugin.class, javaBasePlugin -> configureProhibitedDependencyChecks(project));
4139
}
4240

4341
private void configureProhibitedDependencyChecks(Project project) {

buildSrc/src/main/java/org/springframework/gradle/classpath/CheckProhibitedDependenciesLifecyclePlugin.java

+1-3
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,6 @@ public void apply(Project project) {
3434
task.setGroup(JavaBasePlugin.VERIFICATION_GROUP);
3535
task.setDescription("Checks both the compile/runtime classpath of every SourceSet for prohibited dependencies");
3636
});
37-
project.getTasks().named(JavaBasePlugin.CHECK_TASK_NAME, checkTask -> {
38-
checkTask.dependsOn(checkProhibitedDependencies);
39-
});
37+
project.getTasks().named(JavaBasePlugin.CHECK_TASK_NAME, checkTask -> checkTask.dependsOn(checkProhibitedDependencies));
4038
}
4139
}

buildSrc/src/main/java/org/springframework/gradle/github/changelog/GitHubChangelogPlugin.java

+1-7
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
import org.gradle.api.artifacts.Configuration;
2727
import org.gradle.api.artifacts.DependencySet;
2828
import org.gradle.api.artifacts.repositories.ExclusiveContentRepository;
29-
import org.gradle.api.artifacts.repositories.InclusiveRepositoryContentDescriptor;
3029
import org.gradle.api.artifacts.repositories.IvyArtifactRepository;
3130
import org.gradle.api.artifacts.repositories.IvyPatternRepositoryLayout;
3231
import org.gradle.api.tasks.JavaExec;
@@ -91,12 +90,7 @@ public void execute(IvyPatternRepositoryLayout layout) {
9190
@Override
9291
public void execute(ExclusiveContentRepository exclusiveContentRepository) {
9392
exclusiveContentRepository.forRepositories(repository);
94-
exclusiveContentRepository.filter(new Action<InclusiveRepositoryContentDescriptor>() {
95-
@Override
96-
public void execute(InclusiveRepositoryContentDescriptor descriptor) {
97-
descriptor.includeGroup("spring-io");
98-
}
99-
});
93+
exclusiveContentRepository.filter(descriptor -> descriptor.includeGroup("spring-io"));
10094
}
10195
});
10296
}

buildSrc/src/main/java/org/springframework/gradle/github/milestones/SpringReleaseTrainSpec.java

+20-20
Original file line numberDiff line numberDiff line change
@@ -114,11 +114,11 @@ private Builder() {
114114
}
115115

116116
public Builder train(int train) {
117-
switch (train) {
118-
case 1: this.train = Train.ONE; break;
119-
case 2: this.train = Train.TWO; break;
120-
default: throw new IllegalArgumentException("Invalid train: " + train);
121-
}
117+
this.train = switch (train) {
118+
case 1 -> Train.ONE;
119+
case 2 -> Train.TWO;
120+
default -> throw new IllegalArgumentException("Invalid train: " + train);
121+
};
122122
return this;
123123
}
124124

@@ -156,13 +156,13 @@ public Builder version(String version) {
156156
}
157157

158158
public Builder weekOfMonth(int weekOfMonth) {
159-
switch (weekOfMonth) {
160-
case 1: this.weekOfMonth = WeekOfMonth.FIRST; break;
161-
case 2: this.weekOfMonth = WeekOfMonth.SECOND; break;
162-
case 3: this.weekOfMonth = WeekOfMonth.THIRD; break;
163-
case 4: this.weekOfMonth = WeekOfMonth.FOURTH; break;
164-
default: throw new IllegalArgumentException("Invalid weekOfMonth: " + weekOfMonth);
165-
}
159+
this.weekOfMonth = switch (weekOfMonth) {
160+
case 1 -> WeekOfMonth.FIRST;
161+
case 2 -> WeekOfMonth.SECOND;
162+
case 3 -> WeekOfMonth.THIRD;
163+
case 4 -> WeekOfMonth.FOURTH;
164+
default -> throw new IllegalArgumentException("Invalid weekOfMonth: " + weekOfMonth);
165+
};
166166
return this;
167167
}
168168

@@ -172,14 +172,14 @@ public Builder weekOfMonth(WeekOfMonth weekOfMonth) {
172172
}
173173

174174
public Builder dayOfWeek(int dayOfWeek) {
175-
switch (dayOfWeek) {
176-
case 1: this.dayOfWeek = DayOfWeek.MONDAY; break;
177-
case 2: this.dayOfWeek = DayOfWeek.TUESDAY; break;
178-
case 3: this.dayOfWeek = DayOfWeek.WEDNESDAY; break;
179-
case 4: this.dayOfWeek = DayOfWeek.THURSDAY; break;
180-
case 5: this.dayOfWeek = DayOfWeek.FRIDAY; break;
181-
default: throw new IllegalArgumentException("Invalid dayOfWeek: " + dayOfWeek);
182-
}
175+
this.dayOfWeek = switch (dayOfWeek) {
176+
case 1 -> DayOfWeek.MONDAY;
177+
case 2 -> DayOfWeek.TUESDAY;
178+
case 3 -> DayOfWeek.WEDNESDAY;
179+
case 4 -> DayOfWeek.THURSDAY;
180+
case 5 -> DayOfWeek.FRIDAY;
181+
default -> throw new IllegalArgumentException("Invalid dayOfWeek: " + dayOfWeek);
182+
};
183183
return this;
184184
}
185185

buildSrc/src/main/java/org/springframework/gradle/maven/SpringSigningPlugin.java

+1-7
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
import org.gradle.api.Project;
2222
import org.gradle.api.publish.Publication;
2323
import org.gradle.api.publish.PublishingExtension;
24-
import org.gradle.api.publish.plugins.PublishingPlugin;
2524
import org.gradle.plugins.signing.SigningExtension;
2625
import org.gradle.plugins.signing.SigningPlugin;
2726

@@ -44,12 +43,7 @@ public void execute(SigningPlugin signingPlugin) {
4443

4544
private void sign(Project project) {
4645
SigningExtension signing = project.getExtensions().findByType(SigningExtension.class);
47-
signing.setRequired(new Callable<Boolean>() {
48-
@Override
49-
public Boolean call() throws Exception {
50-
return project.getGradle().getTaskGraph().hasTask("publishArtifacts");
51-
}
52-
});
46+
signing.setRequired((Callable<Boolean>) () -> project.getGradle().getTaskGraph().hasTask("publishArtifacts"));
5347
String signingKeyId = (String) project.findProperty("signingKeyId");
5448
String signingKey = (String) project.findProperty("signingKey");
5549
String signingPassword = (String) project.findProperty("signingPassword");

config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/RSocketMessageHandlerITests.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,7 @@ Flux<String> retrieveFlux(Flux<String> payload) {
294294

295295
@MessageMapping({ "secure.send", "send" })
296296
Mono<Void> send(Mono<String> payload) {
297-
return payload.doOnNext(this::add).then(Mono.fromRunnable(() -> doNotifyAll()));
297+
return payload.doOnNext(this::add).then(Mono.fromRunnable(this::doNotifyAll));
298298
}
299299

300300
private synchronized void doNotifyAll() {

config/src/main/java/org/springframework/security/config/crypto/RsaKeyConversionServicePostProcessor.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,7 @@ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
6868
return;
6969
}
7070
ConversionService service = beanFactory.getConversionService();
71-
if (service instanceof ConverterRegistry) {
72-
ConverterRegistry registry = (ConverterRegistry) service;
71+
if (service instanceof ConverterRegistry registry) {
7372
registry.addConverter(String.class, RSAPrivateKey.class, this.pkcs8);
7473
registry.addConverter(String.class, RSAPublicKey.class, this.x509);
7574
}

config/src/main/java/org/springframework/security/config/http/ChannelAttributeFactory.java

+6-13
Original file line numberDiff line numberDiff line change
@@ -42,19 +42,12 @@ private ChannelAttributeFactory() {
4242
}
4343

4444
public static List<ConfigAttribute> createChannelAttributes(String requiredChannel) {
45-
String channelConfigAttribute;
46-
if (requiredChannel.equals(OPT_REQUIRES_HTTPS)) {
47-
channelConfigAttribute = "REQUIRES_SECURE_CHANNEL";
48-
}
49-
else if (requiredChannel.equals(OPT_REQUIRES_HTTP)) {
50-
channelConfigAttribute = "REQUIRES_INSECURE_CHANNEL";
51-
}
52-
else if (requiredChannel.equals(OPT_ANY_CHANNEL)) {
53-
channelConfigAttribute = ChannelDecisionManagerImpl.ANY_CHANNEL;
54-
}
55-
else {
56-
throw new BeanCreationException("Unknown channel attribute " + requiredChannel);
57-
}
45+
String channelConfigAttribute = switch (requiredChannel) {
46+
case OPT_REQUIRES_HTTPS -> "REQUIRES_SECURE_CHANNEL";
47+
case OPT_REQUIRES_HTTP -> "REQUIRES_INSECURE_CHANNEL";
48+
case OPT_ANY_CHANNEL -> ChannelDecisionManagerImpl.ANY_CHANNEL;
49+
default -> throw new BeanCreationException("Unknown channel attribute " + requiredChannel);
50+
};
5851
return SecurityConfig.createList(channelConfigAttribute);
5952
}
6053

config/src/test/java/org/springframework/security/config/annotation/web/configurers/RequestCacheConfigurerTests.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,7 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
382382
.anyRequest().authenticated()
383383
)
384384
.formLogin(Customizer.withDefaults())
385-
.requestCache((cache) -> cache.disable());
385+
.requestCache(RequestCacheConfigurer::disable);
386386
// @formatter:on
387387
return http.build();
388388
}

config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerTests.java

+1-3
Original file line numberDiff line numberDiff line change
@@ -556,9 +556,7 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
556556
.sessionManagement((sessionManagement) ->
557557
sessionManagement
558558
.requireExplicitAuthenticationStrategy(false)
559-
.sessionFixation((sessionFixation) ->
560-
sessionFixation.newSession()
561-
)
559+
.sessionFixation(SessionManagementConfigurer.SessionFixationConfigurer::newSession)
562560
)
563561
.httpBasic(withDefaults());
564562
// @formatter:on

config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java

+2-5
Original file line numberDiff line numberDiff line change
@@ -868,8 +868,7 @@ public void getJwtDecoderWhenTwoJwtDecoderBeansThenThrowsException() {
868868
context.registerBean("decoderTwo", JwtDecoder.class, () -> decoder);
869869
this.spring.context(context).autowire();
870870
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
871-
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class)
872-
.isThrownBy(() -> jwtConfigurer.getJwtDecoder());
871+
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(jwtConfigurer::getJwtDecoder);
873872
}
874873

875874
@Test
@@ -1885,9 +1884,7 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
18851884
.anyRequest().authenticated()
18861885
)
18871886
.oauth2Login(withDefaults())
1888-
.oauth2ResourceServer((oauth2) -> oauth2
1889-
.jwt()
1890-
);
1887+
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
18911888
return http.build();
18921889
// @formatter:on
18931890
}

config/src/test/java/org/springframework/security/config/annotation/web/socket/SyncExecutorSubscribableChannelPostProcessor.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,7 @@ public class SyncExecutorSubscribableChannelPostProcessor implements BeanPostPro
2727

2828
@Override
2929
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
30-
if (bean instanceof ExecutorSubscribableChannel) {
31-
ExecutorSubscribableChannel original = (ExecutorSubscribableChannel) bean;
30+
if (bean instanceof ExecutorSubscribableChannel original) {
3231
ExecutorSubscribableChannel channel = new ExecutorSubscribableChannel();
3332
channel.setInterceptors(original.getInterceptors());
3433
return channel;

config/src/test/java/org/springframework/security/config/annotation/web/socket/WebSocketMessageBrokerSecurityConfigurationTests.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -627,9 +627,8 @@ static class TestHandshakeHandler implements HandshakeHandler {
627627
public boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
628628
Map<String, Object> attributes) throws HandshakeFailureException {
629629
this.attributes = attributes;
630-
if (wsHandler instanceof SockJsWebSocketHandler) {
630+
if (wsHandler instanceof SockJsWebSocketHandler sockJs) {
631631
// work around SPR-12716
632-
SockJsWebSocketHandler sockJs = (SockJsWebSocketHandler) wsHandler;
633632
WebSocketServerSockJsSession session = (WebSocketServerSockJsSession) ReflectionTestUtils
634633
.getField(sockJs, "sockJsSession");
635634
this.attributes = session.getAttributes();

config/src/test/java/org/springframework/security/config/doc/XmlNode.java

+2-3
Original file line numberDiff line numberDiff line change
@@ -58,16 +58,15 @@ public Optional<XmlNode> child(String name) {
5858

5959
public Optional<XmlNode> parent() {
6060
// @formatter:off
61-
return Optional.ofNullable(this.node.getParentNode())
62-
.map((parent) -> new XmlNode(parent));
61+
return Optional.ofNullable(this.node.getParentNode()).map(XmlNode::new);
6362
// @formatter:on
6463
}
6564

6665
public String attribute(String name) {
6766
// @formatter:off
6867
return Optional.ofNullable(this.node.getAttributes())
6968
.map((attrs) -> attrs.getNamedItem(name))
70-
.map((attr) -> attr.getTextContent())
69+
.map(Node::getTextContent)
7170
.orElse(null);
7271
// @formatter:on
7372
}

config/src/test/java/org/springframework/security/config/test/SpringTestContextExtension.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public class SpringTestContextExtension implements BeforeEachCallback, AfterEach
3131
@Override
3232
public void afterEach(ExtensionContext context) throws Exception {
3333
TestSecurityContextHolder.clearContext();
34-
getContexts(context.getRequiredTestInstance()).forEach((springTestContext) -> springTestContext.close());
34+
getContexts(context.getRequiredTestInstance()).forEach(SpringTestContext::close);
3535
}
3636

3737
@Override

core/src/main/java/org/springframework/security/access/SecurityConfig.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,7 @@ public SecurityConfig(String config) {
3838

3939
@Override
4040
public boolean equals(Object obj) {
41-
if (obj instanceof ConfigAttribute) {
42-
ConfigAttribute attr = (ConfigAttribute) obj;
41+
if (obj instanceof ConfigAttribute attr) {
4342
return this.attrib.equals(attr.getAttribute());
4443
}
4544
return false;

core/src/main/java/org/springframework/security/access/annotation/Jsr250MethodSecurityMetadataSource.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,7 @@ private List<ConfigAttribute> processAnnotations(Annotation[] annotations) {
8989
attributes.add(Jsr250SecurityConfig.PERMIT_ALL_ATTRIBUTE);
9090
return attributes;
9191
}
92-
if (annotation instanceof RolesAllowed) {
93-
RolesAllowed ra = (RolesAllowed) annotation;
92+
if (annotation instanceof RolesAllowed ra) {
9493

9594
for (String allowed : ra.value()) {
9695
String defaultedAllowed = getRoleWithDefaultPrefix(allowed);

core/src/main/java/org/springframework/security/access/method/AbstractMethodSecurityMetadataSource.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,7 @@ public abstract class AbstractMethodSecurityMetadataSource implements MethodSecu
4343

4444
@Override
4545
public final Collection<ConfigAttribute> getAttributes(Object object) {
46-
if (object instanceof MethodInvocation) {
47-
MethodInvocation mi = (MethodInvocation) object;
46+
if (object instanceof MethodInvocation mi) {
4847
Object target = mi.getThis();
4948
Class<?> targetClass = null;
5049
if (target != null) {

core/src/main/java/org/springframework/security/access/method/MapBasedMethodSecurityMetadataSource.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -264,8 +264,7 @@ public boolean equals(Object obj) {
264264
if (this == obj) {
265265
return true;
266266
}
267-
if (obj != null && obj instanceof RegisteredMethod) {
268-
RegisteredMethod rhs = (RegisteredMethod) obj;
267+
if (obj instanceof RegisteredMethod rhs) {
269268
return this.method.equals(rhs.method) && this.registeredJavaType.equals(rhs.registeredJavaType);
270269
}
271270
return false;

core/src/main/java/org/springframework/security/access/vote/ConsensusBased.java

+3-8
Original file line numberDiff line numberDiff line change
@@ -71,14 +71,9 @@ public void decide(Authentication authentication, Object object, Collection<Conf
7171
for (AccessDecisionVoter voter : getDecisionVoters()) {
7272
int result = voter.vote(authentication, object, configAttributes);
7373
switch (result) {
74-
case AccessDecisionVoter.ACCESS_GRANTED:
75-
grant++;
76-
break;
77-
case AccessDecisionVoter.ACCESS_DENIED:
78-
deny++;
79-
break;
80-
default:
81-
break;
74+
case AccessDecisionVoter.ACCESS_GRANTED -> grant++;
75+
case AccessDecisionVoter.ACCESS_DENIED -> deny++;
76+
default -> { }
8277
}
8378
}
8479
if (grant > deny) {

core/src/main/java/org/springframework/security/authentication/ProviderManager.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -256,8 +256,7 @@ private void prepareException(AuthenticationException ex, Authentication auth) {
256256
* @param dest the destination authentication object
257257
*/
258258
private void copyDetails(Authentication source, Authentication dest) {
259-
if ((dest instanceof AbstractAuthenticationToken) && (dest.getDetails() == null)) {
260-
AbstractAuthenticationToken token = (AbstractAuthenticationToken) dest;
259+
if ((dest instanceof AbstractAuthenticationToken token) && (dest.getDetails() == null)) {
261260
token.setDetails(source.getDetails());
262261
}
263262
}

core/src/main/java/org/springframework/security/authentication/RememberMeAuthenticationToken.java

+2-6
Original file line numberDiff line numberDiff line change
@@ -94,12 +94,8 @@ public boolean equals(Object obj) {
9494
if (!super.equals(obj)) {
9595
return false;
9696
}
97-
if (obj instanceof RememberMeAuthenticationToken) {
98-
RememberMeAuthenticationToken other = (RememberMeAuthenticationToken) obj;
99-
if (this.getKeyHash() != other.getKeyHash()) {
100-
return false;
101-
}
102-
return true;
97+
if (obj instanceof RememberMeAuthenticationToken other) {
98+
return this.getKeyHash() == other.getKeyHash();
10399
}
104100
return false;
105101
}

0 commit comments

Comments
 (0)