Skip to content

Using modern Java features #12569

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,7 @@ List<Permission> resolvePermission(Object permission) {
if (permission instanceof Permission[]) {
return Arrays.asList((Permission[]) permission);
}
if (permission instanceof String) {
String permString = (String) permission;
if (permission instanceof String permString) {
Permission p = buildPermission(permString);
if (p != null) {
return Arrays.asList(p);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,9 @@ public final boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof Permission)) {
if (!(obj instanceof Permission other)) {
return false;
}
Permission other = (Permission) obj;
return (this.mask == other.getMask());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ public void testProcessingCustomSid() {
CustomSid customSid = new CustomSid("Custom sid");
given(customJdbcMutableAclService.createOrRetrieveSidPrimaryKey("Custom sid", false, false)).willReturn(1L);
Long result = customJdbcMutableAclService.createOrRetrieveSidPrimaryKey(customSid, false);
assertThat(new Long(1L)).isEqualTo(result);
assertThat(Long.valueOf(1L)).isEqualTo(result);
}

protected Authentication getAuth() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.tasks.TaskProvider;
import org.gradle.language.base.plugins.LifecycleBasePlugin;

Expand All @@ -27,12 +26,8 @@ public void execute(CheckAntoraVersionTask antoraCheckVersion) {
project.getPlugins().withType(LifecycleBasePlugin.class, new Action<LifecycleBasePlugin>() {
@Override
public void execute(LifecycleBasePlugin lifecycleBasePlugin) {
project.getTasks().named(LifecycleBasePlugin.CHECK_TASK_NAME).configure(new Action<Task>() {
@Override
public void execute(Task check) {
check.dependsOn(antoraCheckVersion);
}
});
project.getTasks().named(LifecycleBasePlugin.CHECK_TASK_NAME)
.configure(check -> check.dependsOn(antoraCheckVersion));
}
});
project.getTasks().register("antoraUpdateVersion", UpdateAntoraVersionTask.class, new Action<UpdateAntoraVersionTask>() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,7 @@ public class CheckClasspathForProhibitedDependenciesPlugin implements Plugin<Pro
@Override
public void apply(Project project) {
project.getPlugins().apply(CheckProhibitedDependenciesLifecyclePlugin.class);
project.getPlugins().withType(JavaBasePlugin.class, javaBasePlugin -> {
configureProhibitedDependencyChecks(project);
});
project.getPlugins().withType(JavaBasePlugin.class, javaBasePlugin -> configureProhibitedDependencyChecks(project));
}

private void configureProhibitedDependencyChecks(Project project) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ public void apply(Project project) {
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);
});
project.getTasks().named(JavaBasePlugin.CHECK_TASK_NAME, checkTask -> checkTask.dependsOn(checkProhibitedDependencies));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
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.InclusiveRepositoryContentDescriptor;
import org.gradle.api.artifacts.repositories.IvyArtifactRepository;
import org.gradle.api.artifacts.repositories.IvyPatternRepositoryLayout;
import org.gradle.api.tasks.JavaExec;
Expand Down Expand Up @@ -91,12 +90,7 @@ public void execute(IvyPatternRepositoryLayout layout) {
@Override
public void execute(ExclusiveContentRepository exclusiveContentRepository) {
exclusiveContentRepository.forRepositories(repository);
exclusiveContentRepository.filter(new Action<InclusiveRepositoryContentDescriptor>() {
@Override
public void execute(InclusiveRepositoryContentDescriptor descriptor) {
descriptor.includeGroup("spring-io");
}
});
exclusiveContentRepository.filter(descriptor -> descriptor.includeGroup("spring-io"));
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,11 @@ private Builder() {
}

public Builder train(int train) {
switch (train) {
case 1: this.train = Train.ONE; break;
case 2: this.train = Train.TWO; break;
default: throw new IllegalArgumentException("Invalid train: " + train);
}
this.train = switch (train) {
case 1 -> Train.ONE;
case 2 -> Train.TWO;
default -> throw new IllegalArgumentException("Invalid train: " + train);
};
return this;
}

Expand Down Expand Up @@ -156,13 +156,13 @@ public Builder version(String version) {
}

public Builder weekOfMonth(int weekOfMonth) {
switch (weekOfMonth) {
case 1: this.weekOfMonth = WeekOfMonth.FIRST; break;
case 2: this.weekOfMonth = WeekOfMonth.SECOND; break;
case 3: this.weekOfMonth = WeekOfMonth.THIRD; break;
case 4: this.weekOfMonth = WeekOfMonth.FOURTH; break;
default: throw new IllegalArgumentException("Invalid weekOfMonth: " + 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;
}

Expand All @@ -172,14 +172,14 @@ public Builder weekOfMonth(WeekOfMonth weekOfMonth) {
}

public Builder dayOfWeek(int dayOfWeek) {
switch (dayOfWeek) {
case 1: this.dayOfWeek = DayOfWeek.MONDAY; break;
case 2: this.dayOfWeek = DayOfWeek.TUESDAY; break;
case 3: this.dayOfWeek = DayOfWeek.WEDNESDAY; break;
case 4: this.dayOfWeek = DayOfWeek.THURSDAY; break;
case 5: this.dayOfWeek = DayOfWeek.FRIDAY; break;
default: throw new IllegalArgumentException("Invalid dayOfWeek: " + 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;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import org.gradle.api.Project;
import org.gradle.api.publish.Publication;
import org.gradle.api.publish.PublishingExtension;
import org.gradle.api.publish.plugins.PublishingPlugin;
import org.gradle.plugins.signing.SigningExtension;
import org.gradle.plugins.signing.SigningPlugin;

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

private void sign(Project project) {
SigningExtension signing = project.getExtensions().findByType(SigningExtension.class);
signing.setRequired(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return project.getGradle().getTaskGraph().hasTask("publishArtifacts");
}
});
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");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ Flux<String> retrieveFlux(Flux<String> payload) {

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

private synchronized void doNotifyAll() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
return;
}
ConversionService service = beanFactory.getConversionService();
if (service instanceof ConverterRegistry) {
ConverterRegistry registry = (ConverterRegistry) service;
if (service instanceof ConverterRegistry registry) {
registry.addConverter(String.class, RSAPrivateKey.class, this.pkcs8);
registry.addConverter(String.class, RSAPublicKey.class, this.x509);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,12 @@ private ChannelAttributeFactory() {
}

public static List<ConfigAttribute> createChannelAttributes(String requiredChannel) {
String channelConfigAttribute;
if (requiredChannel.equals(OPT_REQUIRES_HTTPS)) {
channelConfigAttribute = "REQUIRES_SECURE_CHANNEL";
}
else if (requiredChannel.equals(OPT_REQUIRES_HTTP)) {
channelConfigAttribute = "REQUIRES_INSECURE_CHANNEL";
}
else if (requiredChannel.equals(OPT_ANY_CHANNEL)) {
channelConfigAttribute = ChannelDecisionManagerImpl.ANY_CHANNEL;
}
else {
throw new BeanCreationException("Unknown channel attribute " + requiredChannel);
}
String channelConfigAttribute = switch (requiredChannel) {
case OPT_REQUIRES_HTTPS -> "REQUIRES_SECURE_CHANNEL";
case OPT_REQUIRES_HTTP -> "REQUIRES_INSECURE_CHANNEL";
case OPT_ANY_CHANNEL -> ChannelDecisionManagerImpl.ANY_CHANNEL;
default -> throw new BeanCreationException("Unknown channel attribute " + requiredChannel);
};
return SecurityConfig.createList(channelConfigAttribute);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.anyRequest().authenticated()
)
.formLogin(Customizer.withDefaults())
.requestCache((cache) -> cache.disable());
.requestCache(RequestCacheConfigurer::disable);
// @formatter:on
return http.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -556,9 +556,7 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.sessionManagement((sessionManagement) ->
sessionManagement
.requireExplicitAuthenticationStrategy(false)
.sessionFixation((sessionFixation) ->
sessionFixation.newSession()
)
.sessionFixation(SessionManagementConfigurer.SessionFixationConfigurer::newSession)
)
.httpBasic(withDefaults());
// @formatter:on
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -868,8 +868,7 @@ public void getJwtDecoderWhenTwoJwtDecoderBeansThenThrowsException() {
context.registerBean("decoderTwo", JwtDecoder.class, () -> decoder);
this.spring.context(context).autowire();
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class)
.isThrownBy(() -> jwtConfigurer.getJwtDecoder());
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(jwtConfigurer::getJwtDecoder);
}

@Test
Expand Down Expand Up @@ -1885,9 +1884,7 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.anyRequest().authenticated()
)
.oauth2Login(withDefaults())
.oauth2ResourceServer((oauth2) -> oauth2
.jwt()
);
.oauth2ResourceServer((oauth2) -> oauth2.jwt(withDefaults()));
return http.build();
// @formatter:on
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ public class SyncExecutorSubscribableChannelPostProcessor implements BeanPostPro

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof ExecutorSubscribableChannel) {
ExecutorSubscribableChannel original = (ExecutorSubscribableChannel) bean;
if (bean instanceof ExecutorSubscribableChannel original) {
ExecutorSubscribableChannel channel = new ExecutorSubscribableChannel();
channel.setInterceptors(original.getInterceptors());
return channel;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -627,9 +627,8 @@ static class TestHandshakeHandler implements HandshakeHandler {
public boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws HandshakeFailureException {
this.attributes = attributes;
if (wsHandler instanceof SockJsWebSocketHandler) {
if (wsHandler instanceof SockJsWebSocketHandler sockJs) {
// work around SPR-12716
SockJsWebSocketHandler sockJs = (SockJsWebSocketHandler) wsHandler;
WebSocketServerSockJsSession session = (WebSocketServerSockJsSession) ReflectionTestUtils
.getField(sockJs, "sockJsSession");
this.attributes = session.getAttributes();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,15 @@ public Optional<XmlNode> child(String name) {

public Optional<XmlNode> parent() {
// @formatter:off
return Optional.ofNullable(this.node.getParentNode())
.map((parent) -> new XmlNode(parent));
return Optional.ofNullable(this.node.getParentNode()).map(XmlNode::new);
// @formatter:on
}

public String attribute(String name) {
// @formatter:off
return Optional.ofNullable(this.node.getAttributes())
.map((attrs) -> attrs.getNamedItem(name))
.map((attr) -> attr.getTextContent())
.map(Node::getTextContent)
.orElse(null);
// @formatter:on
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class SpringTestContextExtension implements BeforeEachCallback, AfterEach
@Override
public void afterEach(ExtensionContext context) throws Exception {
TestSecurityContextHolder.clearContext();
getContexts(context.getRequiredTestInstance()).forEach((springTestContext) -> springTestContext.close());
getContexts(context.getRequiredTestInstance()).forEach(SpringTestContext::close);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@ public SecurityConfig(String config) {

@Override
public boolean equals(Object obj) {
if (obj instanceof ConfigAttribute) {
ConfigAttribute attr = (ConfigAttribute) obj;
if (obj instanceof ConfigAttribute attr) {
return this.attrib.equals(attr.getAttribute());
}
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,7 @@ private List<ConfigAttribute> processAnnotations(Annotation[] annotations) {
attributes.add(Jsr250SecurityConfig.PERMIT_ALL_ATTRIBUTE);
return attributes;
}
if (annotation instanceof RolesAllowed) {
RolesAllowed ra = (RolesAllowed) annotation;
if (annotation instanceof RolesAllowed ra) {

for (String allowed : ra.value()) {
String defaultedAllowed = getRoleWithDefaultPrefix(allowed);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@ public abstract class AbstractMethodSecurityMetadataSource implements MethodSecu

@Override
public final Collection<ConfigAttribute> getAttributes(Object object) {
if (object instanceof MethodInvocation) {
MethodInvocation mi = (MethodInvocation) object;
if (object instanceof MethodInvocation mi) {
Object target = mi.getThis();
Class<?> targetClass = null;
if (target != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -264,8 +264,7 @@ public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj != null && obj instanceof RegisteredMethod) {
RegisteredMethod rhs = (RegisteredMethod) obj;
if (obj instanceof RegisteredMethod rhs) {
return this.method.equals(rhs.method) && this.registeredJavaType.equals(rhs.registeredJavaType);
}
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,9 @@ public void decide(Authentication authentication, Object object, Collection<Conf
for (AccessDecisionVoter voter : getDecisionVoters()) {
int result = voter.vote(authentication, object, configAttributes);
switch (result) {
case AccessDecisionVoter.ACCESS_GRANTED:
grant++;
break;
case AccessDecisionVoter.ACCESS_DENIED:
deny++;
break;
default:
break;
case AccessDecisionVoter.ACCESS_GRANTED -> grant++;
case AccessDecisionVoter.ACCESS_DENIED -> deny++;
default -> { }
}
}
if (grant > deny) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,8 +256,7 @@ private void prepareException(AuthenticationException ex, Authentication auth) {
* @param dest the destination authentication object
*/
private void copyDetails(Authentication source, Authentication dest) {
if ((dest instanceof AbstractAuthenticationToken) && (dest.getDetails() == null)) {
AbstractAuthenticationToken token = (AbstractAuthenticationToken) dest;
if ((dest instanceof AbstractAuthenticationToken token) && (dest.getDetails() == null)) {
token.setDetails(source.getDetails());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,8 @@ public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
if (obj instanceof RememberMeAuthenticationToken) {
RememberMeAuthenticationToken other = (RememberMeAuthenticationToken) obj;
if (this.getKeyHash() != other.getKeyHash()) {
return false;
}
return true;
if (obj instanceof RememberMeAuthenticationToken other) {
return this.getKeyHash() == other.getKeyHash();
}
return false;
}
Expand Down
Loading