Using modern Java features

This commit is contained in:
Krzysztof Krason 2023-01-20 16:45:41 +01:00 committed by Josh Cummings
parent 7e01ebdd92
commit 9b603b99ab
72 changed files with 206 additions and 402 deletions

View File

@ -118,8 +118,7 @@ public class AclPermissionEvaluator implements PermissionEvaluator {
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);

View File

@ -56,10 +56,9 @@ public abstract class AbstractPermission implements Permission {
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());
}

View File

@ -454,7 +454,7 @@ public class JdbcMutableAclServiceTests {
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() {

View File

@ -4,7 +4,6 @@ import org.gradle.api.Action;
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.tasks.TaskProvider;
import org.gradle.language.base.plugins.LifecycleBasePlugin;
@ -27,12 +26,8 @@ public class AntoraVersionPlugin implements Plugin<Project> {
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>() {

View File

@ -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) {

View File

@ -34,8 +34,6 @@ public class CheckProhibitedDependenciesLifecyclePlugin implements Plugin<Projec
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));
}
}

View File

@ -26,7 +26,6 @@ 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.InclusiveRepositoryContentDescriptor;
import org.gradle.api.artifacts.repositories.IvyArtifactRepository;
import org.gradle.api.artifacts.repositories.IvyPatternRepositoryLayout;
import org.gradle.api.tasks.JavaExec;
@ -91,12 +90,7 @@ public class GitHubChangelogPlugin implements Plugin<Project> {
@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"));
}
});
}

View File

@ -114,11 +114,11 @@ public final class SpringReleaseTrainSpec {
}
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;
}
@ -156,13 +156,13 @@ public final class SpringReleaseTrainSpec {
}
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;
}
@ -172,14 +172,14 @@ public final class SpringReleaseTrainSpec {
}
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;
}

View File

@ -21,7 +21,6 @@ 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.api.publish.plugins.PublishingPlugin;
import org.gradle.plugins.signing.SigningExtension;
import org.gradle.plugins.signing.SigningPlugin;
@ -44,12 +43,7 @@ public class SpringSigningPlugin implements Plugin<Project> {
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");

View File

@ -294,7 +294,7 @@ public class RSocketMessageHandlerITests {
@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() {

View File

@ -68,8 +68,7 @@ public class RsaKeyConversionServicePostProcessor implements BeanFactoryPostProc
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);
}

View File

@ -42,19 +42,12 @@ public final class 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);
}

View File

@ -382,7 +382,7 @@ public class RequestCacheConfigurerTests {
.anyRequest().authenticated()
)
.formLogin(Customizer.withDefaults())
.requestCache((cache) -> cache.disable());
.requestCache(RequestCacheConfigurer::disable);
// @formatter:on
return http.build();
}

View File

@ -556,9 +556,7 @@ public class SessionManagementConfigurerTests {
.sessionManagement((sessionManagement) ->
sessionManagement
.requireExplicitAuthenticationStrategy(false)
.sessionFixation((sessionFixation) ->
sessionFixation.newSession()
)
.sessionFixation(SessionManagementConfigurer.SessionFixationConfigurer::newSession)
)
.httpBasic(withDefaults());
// @formatter:on

View File

@ -868,8 +868,7 @@ public class OAuth2ResourceServerConfigurerTests {
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
@ -1885,9 +1884,7 @@ public class OAuth2ResourceServerConfigurerTests {
.anyRequest().authenticated()
)
.oauth2Login(withDefaults())
.oauth2ResourceServer((oauth2) -> oauth2
.jwt()
);
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
return http.build();
// @formatter:on
}

View File

@ -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;

View File

@ -627,9 +627,8 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
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();

View File

@ -58,8 +58,7 @@ public class XmlNode {
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
}
@ -67,7 +66,7 @@ public class XmlNode {
// @formatter:off
return Optional.ofNullable(this.node.getAttributes())
.map((attrs) -> attrs.getNamedItem(name))
.map((attr) -> attr.getTextContent())
.map(Node::getTextContent)
.orElse(null);
// @formatter:on
}

View File

@ -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

View File

@ -38,8 +38,7 @@ public class SecurityConfig implements ConfigAttribute {
@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;

View File

@ -89,8 +89,7 @@ public class Jsr250MethodSecurityMetadataSource extends AbstractFallbackMethodSe
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);

View File

@ -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) {

View File

@ -264,8 +264,7 @@ public class MapBasedMethodSecurityMetadataSource extends AbstractFallbackMethod
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;

View File

@ -71,14 +71,9 @@ public class ConsensusBased extends AbstractAccessDecisionManager {
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) {

View File

@ -256,8 +256,7 @@ public class ProviderManager implements AuthenticationManager, MessageSourceAwar
* @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());
}
}

View File

@ -94,12 +94,8 @@ public class RememberMeAuthenticationToken extends AbstractAuthenticationToken {
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;
}

View File

@ -160,10 +160,9 @@ public abstract class AbstractJaasAuthenticationProvider implements Authenticati
*/
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
if (!(auth instanceof UsernamePasswordAuthenticationToken)) {
if (!(auth instanceof UsernamePasswordAuthenticationToken request)) {
return null;
}
UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) auth;
Set<GrantedAuthority> authorities;
try {
// Create the LoginContext object, and pass our InternallCallbackHandler
@ -233,8 +232,7 @@ public abstract class AbstractJaasAuthenticationProvider implements Authenticati
}
for (SecurityContext context : contexts) {
Authentication auth = context.getAuthentication();
if ((auth != null) && (auth instanceof JaasAuthenticationToken)) {
JaasAuthenticationToken token = (JaasAuthenticationToken) auth;
if ((auth instanceof JaasAuthenticationToken token)) {
try {
LoginContext loginContext = token.getLoginContext();
logout(token, loginContext);

View File

@ -58,8 +58,7 @@ public final class JaasGrantedAuthority implements GrantedAuthority {
if (this == obj) {
return true;
}
if (obj instanceof JaasGrantedAuthority) {
JaasGrantedAuthority jga = (JaasGrantedAuthority) obj;
if (obj instanceof JaasGrantedAuthority jga) {
return this.role.equals(jga.role) && this.principal.equals(jga.principal);
}
return false;

View File

@ -130,23 +130,13 @@ class ComparableVersion implements Comparable<ComparableVersion> {
return (value == 0) ? 0 : 1; // 1.0 == 1, 1.1 > 1
}
switch (item.getType()) {
case INT_ITEM:
int itemValue = ((IntItem) item).value;
return (value < itemValue) ? -1 : ((value == itemValue) ? 0 : 1);
case LONG_ITEM:
case BIGINTEGER_ITEM:
return -1;
case STRING_ITEM:
return 1; // 1.1 > 1-sp
case LIST_ITEM:
return 1; // 1.1 > 1-1
default:
throw new IllegalStateException("invalid item: " + item.getClass());
}
return switch (item.getType()) {
case INT_ITEM -> Integer.compare(value, ((IntItem) item).value);
case LONG_ITEM, BIGINTEGER_ITEM -> -1;
case STRING_ITEM -> 1; // 1.1 > 1-sp
case LIST_ITEM -> 1; // 1.1 > 1-1
default -> throw new IllegalStateException("invalid item: " + item.getClass());
};
}
@Override
@ -204,24 +194,14 @@ class ComparableVersion implements Comparable<ComparableVersion> {
return (value == 0) ? 0 : 1; // 1.0 == 1, 1.1 > 1
}
switch (item.getType()) {
case INT_ITEM:
return 1;
case LONG_ITEM:
long itemValue = ((LongItem) item).value;
return (value < itemValue) ? -1 : ((value == itemValue) ? 0 : 1);
case BIGINTEGER_ITEM:
return -1;
case STRING_ITEM:
return 1; // 1.1 > 1-sp
case LIST_ITEM:
return 1; // 1.1 > 1-1
default:
throw new IllegalStateException("invalid item: " + item.getClass());
}
return switch (item.getType()) {
case INT_ITEM -> 1;
case LONG_ITEM -> Long.compare(value, ((LongItem) item).value);
case BIGINTEGER_ITEM -> -1;
case STRING_ITEM -> 1; // 1.1 > 1-sp
case LIST_ITEM -> 1; // 1.1 > 1-1
default -> throw new IllegalStateException("invalid item: " + item.getClass());
};
}
@Override
@ -278,23 +258,13 @@ class ComparableVersion implements Comparable<ComparableVersion> {
return BigInteger.ZERO.equals(value) ? 0 : 1; // 1.0 == 1, 1.1 > 1
}
switch (item.getType()) {
case INT_ITEM:
case LONG_ITEM:
return 1;
case BIGINTEGER_ITEM:
return value.compareTo(((BigIntegerItem) item).value);
case STRING_ITEM:
return 1; // 1.1 > 1-sp
case LIST_ITEM:
return 1; // 1.1 > 1-1
default:
throw new IllegalStateException("invalid item: " + item.getClass());
}
return switch (item.getType()) {
case INT_ITEM, LONG_ITEM -> 1;
case BIGINTEGER_ITEM -> value.compareTo(((BigIntegerItem) item).value);
case STRING_ITEM -> 1; // 1.1 > 1-sp
case LIST_ITEM -> 1; // 1.1 > 1-1
default -> throw new IllegalStateException("invalid item: " + item.getClass());
};
}
@Override
@ -351,18 +321,12 @@ class ComparableVersion implements Comparable<ComparableVersion> {
StringItem(String value, boolean followedByDigit) {
if (followedByDigit && value.length() == 1) {
// a1 = alpha-1, b1 = beta-1, m1 = milestone-1
switch (value.charAt(0)) {
case 'a':
value = "alpha";
break;
case 'b':
value = "beta";
break;
case 'm':
value = "milestone";
break;
default:
}
value = switch (value.charAt(0)) {
case 'a' -> "alpha";
case 'b' -> "beta";
case 'm' -> "milestone";
default -> value;
};
}
this.value = ALIASES.getProperty(value, value);
}
@ -402,21 +366,13 @@ class ComparableVersion implements Comparable<ComparableVersion> {
// 1-rc < 1, 1-ga > 1
return comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX);
}
switch (item.getType()) {
case INT_ITEM:
case LONG_ITEM:
case BIGINTEGER_ITEM:
return -1; // 1.any < 1.1 ?
case STRING_ITEM:
return comparableQualifier(value).compareTo(comparableQualifier(((StringItem) item).value));
case LIST_ITEM:
return -1; // 1.any < 1-1
default:
throw new IllegalStateException("invalid item: " + item.getClass());
}
return switch (item.getType()) {
case INT_ITEM, LONG_ITEM, BIGINTEGER_ITEM -> -1; // 1.any < 1.1 ?
case STRING_ITEM ->
comparableQualifier(value).compareTo(comparableQualifier(((StringItem) item).value));
case LIST_ITEM -> -1; // 1.any < 1-1
default -> throw new IllegalStateException("invalid item: " + item.getClass());
};
}
@Override
@ -484,36 +440,27 @@ class ComparableVersion implements Comparable<ComparableVersion> {
Item first = get(0);
return first.compareTo(null);
}
switch (item.getType()) {
case INT_ITEM:
case LONG_ITEM:
case BIGINTEGER_ITEM:
return -1; // 1-1 < 1.0.x
return switch (item.getType()) {
case INT_ITEM, LONG_ITEM, BIGINTEGER_ITEM -> -1; // 1-1 < 1.0.x
case STRING_ITEM -> 1; // 1-1 > 1-sp
case LIST_ITEM -> {
Iterator<Item> left = iterator();
Iterator<Item> right = ((ListItem) item).iterator();
while (left.hasNext() || right.hasNext()) {
Item l = left.hasNext() ? left.next() : null;
Item r = right.hasNext() ? right.next() : null;
case STRING_ITEM:
return 1; // 1-1 > 1-sp
// if this is shorter, then invert the compare and mul with -1
int result = l == null ? (r == null ? 0 : -1 * r.compareTo(l)) : l.compareTo(r);
case LIST_ITEM:
Iterator<Item> left = iterator();
Iterator<Item> right = ((ListItem) item).iterator();
while (left.hasNext() || right.hasNext()) {
Item l = left.hasNext() ? left.next() : null;
Item r = right.hasNext() ? right.next() : null;
// if this is shorter, then invert the compare and mul with -1
int result = l == null ? (r == null ? 0 : -1 * r.compareTo(l)) : l.compareTo(r);
if (result != 0) {
return result;
if (result != 0) {
yield result;
}
}
yield 0;
}
return 0;
default:
throw new IllegalStateException("invalid item: " + item.getClass());
}
default -> throw new IllegalStateException("invalid item: " + item.getClass());
};
}
@Override

View File

@ -48,7 +48,7 @@ public interface SecurityContextHolderStrategy {
* @since 5.8
*/
default Supplier<SecurityContext> getDeferredContext() {
return () -> getContext();
return this::getContext;
}
/**

View File

@ -42,8 +42,7 @@ public class SecurityContextImpl implements SecurityContext {
@Override
public boolean equals(Object obj) {
if (obj instanceof SecurityContextImpl) {
SecurityContextImpl other = (SecurityContextImpl) obj;
if (obj instanceof SecurityContextImpl other) {
if ((this.getAuthentication() == null) && (other.getAuthentication() == null)) {
return true;
}

View File

@ -100,13 +100,11 @@ public class SessionRegistryImpl implements SessionRegistry, ApplicationListener
@Override
public void onApplicationEvent(AbstractSessionEvent event) {
if (event instanceof SessionDestroyedEvent) {
SessionDestroyedEvent sessionDestroyedEvent = (SessionDestroyedEvent) event;
if (event instanceof SessionDestroyedEvent sessionDestroyedEvent) {
String sessionId = sessionDestroyedEvent.getId();
removeSessionInformation(sessionId);
}
else if (event instanceof SessionIdChangedEvent) {
SessionIdChangedEvent sessionIdChangedEvent = (SessionIdChangedEvent) event;
else if (event instanceof SessionIdChangedEvent sessionIdChangedEvent) {
String oldSessionId = sessionIdChangedEvent.getOldSessionId();
if (this.sessionIds.containsKey(oldSessionId)) {
Object principal = this.sessionIds.get(oldSessionId).getPrincipal();

View File

@ -59,8 +59,7 @@ public class DefaultToken implements Token {
@Override
public boolean equals(Object obj) {
if (obj != null && obj instanceof DefaultToken) {
DefaultToken rhs = (DefaultToken) obj;
if (obj instanceof DefaultToken rhs) {
return this.key.equals(rhs.key) && this.keyCreationTime == rhs.keyCreationTime
&& this.extendedInformation.equals(rhs.extendedInformation);
}
@ -71,7 +70,7 @@ public class DefaultToken implements Token {
public int hashCode() {
int code = 979;
code = code * this.key.hashCode();
code = code * new Long(this.keyCreationTime).hashCode();
code = code * Long.valueOf(this.keyCreationTime).hashCode();
code = code * this.extendedInformation.hashCode();
return code;
}

View File

@ -142,7 +142,7 @@ public class KeyBasedPersistenceTokenService implements TokenService, Initializi
}
private String computeServerSecretApplicableAt(long time) {
return this.serverSecret + ":" + new Long(time % this.serverInteger).intValue();
return this.serverSecret + ":" + Long.valueOf(time % this.serverInteger).intValue();
}
/**

View File

@ -44,8 +44,7 @@ class UnmodifiableListDeserializer extends JsonDeserializer<List> {
JsonNode node = mapper.readTree(jp);
List<Object> result = new ArrayList<>();
if (node != null) {
if (node instanceof ArrayNode) {
ArrayNode arrayNode = (ArrayNode) node;
if (node instanceof ArrayNode arrayNode) {
for (JsonNode elementNode : arrayNode) {
result.add(mapper.readValue(elementNode.traverse(mapper), Object.class));
}

View File

@ -44,8 +44,7 @@ class UnmodifiableSetDeserializer extends JsonDeserializer<Set> {
JsonNode node = mapper.readTree(jp);
Set<Object> resultSet = new HashSet<>();
if (node != null) {
if (node instanceof ArrayNode) {
ArrayNode arrayNode = (ArrayNode) node;
if (node instanceof ArrayNode arrayNode) {
for (JsonNode elementNode : arrayNode) {
resultSet.add(mapper.readValue(elementNode.traverse(mapper), Object.class));
}

View File

@ -60,8 +60,7 @@ public final class MethodInvocationUtils {
// Determine the type that declares the requested method,
// taking into account proxies
Class<?> target = AopUtils.getTargetClass(object);
if (object instanceof Advised) {
Advised a = (Advised) object;
if (object instanceof Advised a) {
if (!a.isProxyTargetClass()) {
Class<?>[] possibleInterfaces = a.getProxiedInterfaces();
for (Class<?> possibleInterface : possibleInterfaces) {

View File

@ -17,7 +17,6 @@
package org.springframework.security.access.vote;
import java.util.Collection;
import java.util.Iterator;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
@ -47,9 +46,7 @@ public class DenyAgainVoter implements AccessDecisionVoter<Object> {
@Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
Iterator<ConfigAttribute> iter = attributes.iterator();
while (iter.hasNext()) {
ConfigAttribute attribute = iter.next();
for (ConfigAttribute attribute : attributes) {
if (this.supports(attribute)) {
return ACCESS_DENIED;
}

View File

@ -17,7 +17,6 @@
package org.springframework.security.access.vote;
import java.util.Collection;
import java.util.Iterator;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
@ -49,9 +48,7 @@ public class DenyVoter implements AccessDecisionVoter<Object> {
@Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
Iterator<ConfigAttribute> iter = attributes.iterator();
while (iter.hasNext()) {
ConfigAttribute attribute = iter.next();
for (ConfigAttribute attribute : attributes) {
if (this.supports(attribute)) {
return ACCESS_DENIED;
}

View File

@ -222,16 +222,13 @@ public class DefaultJaasAuthenticationProviderTests {
public void javadocExample() {
String resName = "/" + getClass().getName().replace('.', '/') + ".xml";
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(resName);
context.registerShutdownHook();
try {
try (context) {
context.registerShutdownHook();
this.provider = context.getBean(DefaultJaasAuthenticationProvider.class);
Authentication auth = this.provider.authenticate(this.token);
assertThat(auth.isAuthenticated()).isEqualTo(true);
assertThat(auth.getPrincipal()).isEqualTo(this.token.getPrincipal());
}
finally {
context.close();
}
}
private void verifyFailedLogin() {

View File

@ -174,8 +174,7 @@ public class JaasAuthenticationProviderTests {
assertThat(set.contains("ROLE_TEST2")).withFailMessage("GrantedAuthorities should contain ROLE_TEST2").isTrue();
boolean foundit = false;
for (GrantedAuthority a : list) {
if (a instanceof JaasGrantedAuthority) {
JaasGrantedAuthority grant = (JaasGrantedAuthority) a;
if (a instanceof JaasGrantedAuthority grant) {
assertThat(grant.getPrincipal()).withFailMessage("Principal was null on JaasGrantedAuthority")
.isNotNull();
foundit = true;

View File

@ -30,8 +30,7 @@ public class TestCallbackHandler implements JaasAuthenticationCallbackHandler {
@Override
public void handle(Callback callback, Authentication auth) {
if (callback instanceof TextInputCallback) {
TextInputCallback tic = (TextInputCallback) callback;
if (callback instanceof TextInputCallback tic) {
tic.setText(auth.getPrincipal().toString());
}
}

View File

@ -38,7 +38,7 @@ import static org.mockito.Mockito.verifyNoInteractions;
*/
public class SpringAuthorizationEventPublisherTests {
Supplier<Authentication> authentication = () -> TestAuthentication.authenticatedUser();
Supplier<Authentication> authentication = TestAuthentication::authenticatedUser;
ApplicationEventPublisher applicationEventPublisher;

View File

@ -68,13 +68,7 @@ final class StaticFinalReflectionUtils {
field.set(null, newValue);
}
}
catch (SecurityException ex) {
throw new RuntimeException(ex);
}
catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
}
catch (IllegalArgumentException ex) {
catch (SecurityException | IllegalAccessException | IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
}

View File

@ -57,7 +57,7 @@ class ThreadLocalSecurityContextHolderStrategyTests {
void deferredContextValidates() {
this.strategy.setDeferredContext(() -> null);
Supplier<SecurityContext> deferredContext = this.strategy.getDeferredContext();
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> deferredContext.get());
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(deferredContext::get);
}
@Test

View File

@ -58,19 +58,14 @@ final class Argon2EncodingUtils {
*/
static String encode(byte[] hash, Argon2Parameters parameters) throws IllegalArgumentException {
StringBuilder stringBuilder = new StringBuilder();
switch (parameters.getType()) {
case Argon2Parameters.ARGON2_d:
stringBuilder.append("$argon2d");
break;
case Argon2Parameters.ARGON2_i:
stringBuilder.append("$argon2i");
break;
case Argon2Parameters.ARGON2_id:
stringBuilder.append("$argon2id");
break;
default:
throw new IllegalArgumentException("Invalid algorithm type: " + parameters.getType());
}
stringBuilder.append(
switch (parameters.getType()) {
case Argon2Parameters.ARGON2_d -> "$argon2d";
case Argon2Parameters.ARGON2_i -> "$argon2i";
case Argon2Parameters.ARGON2_id -> "$argon2id";
default -> throw new IllegalArgumentException("Invalid algorithm type: " + parameters.getType());
}
);
stringBuilder.append("$v=").append(parameters.getVersion()).append("$m=").append(parameters.getMemory())
.append(",t=").append(parameters.getIterations()).append(",p=").append(parameters.getLanes());
if (parameters.getSalt() != null) {
@ -107,19 +102,12 @@ final class Argon2EncodingUtils {
throw new IllegalArgumentException("Invalid encoded Argon2-hash");
}
int currentPart = 1;
switch (parts[currentPart++]) {
case "argon2d":
paramsBuilder = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_d);
break;
case "argon2i":
paramsBuilder = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_i);
break;
case "argon2id":
paramsBuilder = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_id);
break;
default:
throw new IllegalArgumentException("Invalid algorithm type: " + parts[0]);
}
paramsBuilder = switch (parts[currentPart++]) {
case "argon2d" -> new Argon2Parameters.Builder(Argon2Parameters.ARGON2_d);
case "argon2i" -> new Argon2Parameters.Builder(Argon2Parameters.ARGON2_i);
case "argon2id" -> new Argon2Parameters.Builder(Argon2Parameters.ARGON2_id);
default -> throw new IllegalArgumentException("Invalid algorithm type: " + parts[0]);
};
if (parts[currentPart].startsWith("v=")) {
paramsBuilder.withVersion(Integer.parseInt(parts[currentPart].substring(2)));
currentPart++;

View File

@ -260,43 +260,30 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda
String hexString = Integer.toHexString(code);
Throwable cause = new ActiveDirectoryAuthenticationException(hexString, exception.getMessage(), exception);
switch (code) {
case PASSWORD_EXPIRED:
throw new CredentialsExpiredException(this.messages.getMessage(
case PASSWORD_EXPIRED -> throw new CredentialsExpiredException(this.messages.getMessage(
"LdapAuthenticationProvider.credentialsExpired", "User credentials have expired"), cause);
case ACCOUNT_DISABLED:
throw new DisabledException(
case ACCOUNT_DISABLED -> throw new DisabledException(
this.messages.getMessage("LdapAuthenticationProvider.disabled", "User is disabled"), cause);
case ACCOUNT_EXPIRED:
throw new AccountExpiredException(
case ACCOUNT_EXPIRED -> throw new AccountExpiredException(
this.messages.getMessage("LdapAuthenticationProvider.expired", "User account has expired"), cause);
case ACCOUNT_LOCKED:
throw new LockedException(
case ACCOUNT_LOCKED -> throw new LockedException(
this.messages.getMessage("LdapAuthenticationProvider.locked", "User account is locked"), cause);
default:
throw badCredentials(cause);
default -> throw badCredentials(cause);
}
}
private String subCodeToLogMessage(int code) {
switch (code) {
case USERNAME_NOT_FOUND:
return "User was not found in directory";
case INVALID_PASSWORD:
return "Supplied password was invalid";
case NOT_PERMITTED:
return "User not permitted to logon at this time";
case PASSWORD_EXPIRED:
return "Password has expired";
case ACCOUNT_DISABLED:
return "Account is disabled";
case ACCOUNT_EXPIRED:
return "Account expired";
case PASSWORD_NEEDS_RESET:
return "User must reset password";
case ACCOUNT_LOCKED:
return "Account locked";
}
return "Unknown (error code " + Integer.toHexString(code) + ")";
return switch (code) {
case USERNAME_NOT_FOUND -> "User was not found in directory";
case INVALID_PASSWORD -> "Supplied password was invalid";
case NOT_PERMITTED -> "User not permitted to logon at this time";
case PASSWORD_EXPIRED -> "Password has expired";
case ACCOUNT_DISABLED -> "Account is disabled";
case ACCOUNT_EXPIRED -> "Account expired";
case PASSWORD_NEEDS_RESET -> "User must reset password";
case ACCOUNT_LOCKED -> "Account locked";
default -> "Unknown (error code " + Integer.toHexString(code) + ")";
};
}
private BadCredentialsException badCredentials() {

View File

@ -85,8 +85,7 @@ public final class MessageMatcherDelegatingAuthorizationManager implements Autho
if (!matcher.matches((Message) message)) {
return null;
}
if (matcher instanceof SimpDestinationMessageMatcher) {
SimpDestinationMessageMatcher simp = (SimpDestinationMessageMatcher) matcher;
if (matcher instanceof SimpDestinationMessageMatcher simp) {
return new MessageAuthorizationContext<>(message, simp.extractPathVariables(message));
}
if (matcher instanceof Builder.LazySimpDestinationMessageMatcher) {
@ -111,7 +110,7 @@ public final class MessageMatcherDelegatingAuthorizationManager implements Autho
private final List<Entry<AuthorizationManager<MessageAuthorizationContext<?>>>> mappings = new ArrayList<>();
private Supplier<PathMatcher> pathMatcher = () -> new AntPathMatcher();
private Supplier<PathMatcher> pathMatcher = AntPathMatcher::new;
public Builder() {
}

View File

@ -57,10 +57,9 @@ public class SimpMessageTypeMatcher implements MessageMatcher<Object> {
if (this == other) {
return true;
}
if (!(other instanceof SimpMessageTypeMatcher)) {
if (!(other instanceof SimpMessageTypeMatcher otherMatcher)) {
return false;
}
SimpMessageTypeMatcher otherMatcher = (SimpMessageTypeMatcher) other;
return ObjectUtils.nullSafeEquals(this.typeToMatch, otherMatcher.typeToMatch);
}

View File

@ -396,8 +396,7 @@ public class JdbcOAuth2AuthorizedClientService implements OAuth2AuthorizedClient
@Override
protected void doSetValue(PreparedStatement ps, int parameterPosition, Object argValue) throws SQLException {
if (argValue instanceof SqlParameterValue) {
SqlParameterValue paramValue = (SqlParameterValue) argValue;
if (argValue instanceof SqlParameterValue paramValue) {
if (paramValue.getSqlType() == Types.BLOB) {
if (paramValue.getValue() != null) {
Assert.isInstanceOf(byte[].class, paramValue.getValue(),

View File

@ -110,9 +110,8 @@ public class RemoveAuthorizedClientOAuth2AuthorizationFailureHandler implements
@Override
public void onAuthorizationFailure(OAuth2AuthorizationException authorizationException, Authentication principal,
Map<String, Object> attributes) {
if (authorizationException instanceof ClientAuthorizationException
if (authorizationException instanceof ClientAuthorizationException clientAuthorizationException
&& hasRemovalErrorCode(authorizationException)) {
ClientAuthorizationException clientAuthorizationException = (ClientAuthorizationException) authorizationException;
this.delegate.removeAuthorizedClient(clientAuthorizationException.getClientRegistrationId(), principal,
attributes);
}

View File

@ -112,9 +112,8 @@ public class RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler
@Override
public Mono<Void> onAuthorizationFailure(OAuth2AuthorizationException authorizationException,
Authentication principal, Map<String, Object> attributes) {
if (authorizationException instanceof ClientAuthorizationException
if (authorizationException instanceof ClientAuthorizationException clientAuthorizationException
&& hasRemovalErrorCode(authorizationException)) {
ClientAuthorizationException clientAuthorizationException = (ClientAuthorizationException) authorizationException;
return this.delegate.removeAuthorizedClient(clientAuthorizationException.getClientRegistrationId(),
principal, attributes);
}

View File

@ -70,13 +70,13 @@ public class OAuth2AuthorizationCodeReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenErrorThenOAuth2AuthorizationException() {
this.authorizationResponse = TestOAuth2AuthorizationResponses.error();
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> authenticate());
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(this::authenticate);
}
@Test
public void authenticateWhenStateNotEqualThenOAuth2AuthorizationException() {
this.authorizationRequest.state("notequal");
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> authenticate());
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(this::authenticate);
}
@Test

View File

@ -478,12 +478,11 @@ public class ClientRegistrationsTests {
final Dispatcher dispatcher = new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) {
switch (request.getPath()) {
case "/.well-known/oauth-authorization-server/issuer1":
case "/.well-known/oauth-authorization-server/":
return buildSuccessMockResponse(responseBody);
}
return new MockResponse().setResponseCode(404);
return switch (request.getPath()) {
case "/.well-known/oauth-authorization-server/issuer1", "/.well-known/oauth-authorization-server/" ->
buildSuccessMockResponse(responseBody);
default -> new MockResponse().setResponseCode(404);
};
}
};
this.server.setDispatcher(dispatcher);
@ -514,12 +513,11 @@ public class ClientRegistrationsTests {
final Dispatcher dispatcher = new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) {
switch (request.getPath()) {
case "/issuer1/.well-known/openid-configuration":
case "/.well-known/openid-configuration/":
return buildSuccessMockResponse(responseBody);
}
return new MockResponse().setResponseCode(404);
return switch (request.getPath()) {
case "/issuer1/.well-known/openid-configuration", "/.well-known/openid-configuration/" ->
buildSuccessMockResponse(responseBody);
default -> new MockResponse().setResponseCode(404);
};
}
};
this.server.setDispatcher(dispatcher);

View File

@ -87,7 +87,7 @@ final class ReactiveJwtDecoderProviderConfigurationUtils {
}
Assert.notEmpty(jwsAlgorithms, "Failed to find any algorithms from the JWK set");
return jwsAlgorithms;
}).onErrorMap(KeySourceException.class, (ex) -> new IllegalStateException(ex));
}).onErrorMap(KeySourceException.class, IllegalStateException::new);
}
static Mono<Map<String, Object>> getConfigurationForIssuerLocation(String issuer, WebClient web) {

View File

@ -61,10 +61,10 @@ class ReactiveRemoteJWKSource implements ReactiveJWKSource {
public Mono<List<JWK>> get(JWKSelector jwkSelector) {
// @formatter:off
return this.cachedJWKSet.get()
.switchIfEmpty(Mono.defer(() -> getJWKSet()))
.switchIfEmpty(Mono.defer(this::getJWKSet))
.flatMap((jwkSet) -> get(jwkSelector, jwkSet))
.switchIfEmpty(Mono.defer(() -> getJWKSet()
.map((jwkSet) -> jwkSelector.select(jwkSet)))
.map(jwkSelector::select))
);
// @formatter:on
}

View File

@ -101,10 +101,9 @@ public final class OpaqueTokenAuthenticationProvider implements AuthenticationPr
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (!(authentication instanceof BearerTokenAuthenticationToken)) {
if (!(authentication instanceof BearerTokenAuthenticationToken bearer)) {
return null;
}
BearerTokenAuthenticationToken bearer = (BearerTokenAuthenticationToken) authentication;
OAuth2AuthenticatedPrincipal principal = getOAuth2AuthenticatedPrincipal(bearer);
Authentication result = this.authenticationConverter.convert(bearer.getToken(), principal);
if (result == null) {

View File

@ -74,8 +74,7 @@ public final class BearerTokenAuthenticationEntryPoint implements Authentication
if (StringUtils.hasText(error.getUri())) {
parameters.put("error_uri", error.getUri());
}
if (error instanceof BearerTokenError) {
BearerTokenError bearerTokenError = (BearerTokenError) error;
if (error instanceof BearerTokenError bearerTokenError) {
if (StringUtils.hasText(bearerTokenError.getScope())) {
parameters.put("scope", bearerTokenError.getScope());
}

View File

@ -82,8 +82,7 @@ public final class BearerTokenServerAuthenticationEntryPoint implements ServerAu
if (StringUtils.hasText(error.getUri())) {
parameters.put("error_uri", error.getUri());
}
if (error instanceof BearerTokenError) {
BearerTokenError bearerTokenError = (BearerTokenError) error;
if (error instanceof BearerTokenError bearerTokenError) {
if (StringUtils.hasText(bearerTokenError.getScope())) {
parameters.put("scope", bearerTokenError.getScope());
}

View File

@ -91,9 +91,9 @@ class PayloadInterceptorRSocket extends RSocketProxy {
public Flux<Payload> requestChannel(Publisher<Payload> payloads) {
return Flux.from(payloads).switchOnFirst((signal, innerFlux) -> {
Payload firstPayload = signal.get();
return intercept(PayloadExchangeType.REQUEST_CHANNEL, firstPayload).flatMapMany((context) -> innerFlux
.index().concatMap((tuple) -> justOrIntercept(tuple.getT1(), tuple.getT2()))
.transform((securedPayloads) -> this.source.requestChannel(securedPayloads)).contextWrite(context));
return intercept(PayloadExchangeType.REQUEST_CHANNEL, firstPayload).flatMapMany(
(context) -> innerFlux.index().concatMap((tuple) -> justOrIntercept(tuple.getT1(), tuple.getT2()))
.transform(this.source::requestChannel).contextWrite(context));
});
}
@ -112,8 +112,8 @@ class PayloadInterceptorRSocket extends RSocketProxy {
ContextPayloadInterceptorChain chain = new ContextPayloadInterceptorChain(this.interceptors);
DefaultPayloadExchange exchange = new DefaultPayloadExchange(type, payload, this.metadataMimeType,
this.dataMimeType);
return chain.next(exchange).then(Mono.fromCallable(() -> chain.getContext()))
.defaultIfEmpty(Context.empty()).contextWrite(this.context);
return chain.next(exchange).then(Mono.fromCallable(chain::getContext)).defaultIfEmpty(Context.empty())
.contextWrite(this.context);
});
}

View File

@ -83,8 +83,7 @@ class PayloadSocketAcceptor implements SocketAcceptor {
ContextPayloadInterceptorChain chain = new ContextPayloadInterceptorChain(this.interceptors);
DefaultPayloadExchange exchange = new DefaultPayloadExchange(PayloadExchangeType.SETUP, payload,
metadataMimeType, dataMimeType);
return chain.next(exchange).then(Mono.fromCallable(() -> chain.getContext()))
.defaultIfEmpty(Context.empty());
return chain.next(exchange).then(Mono.fromCallable(chain::getContext)).defaultIfEmpty(Context.empty());
});
}

View File

@ -16,9 +16,6 @@
package org.springframework.security.rsocket.util.matcher;
import reactor.core.publisher.Mono;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.api.PayloadExchangeType;
/**
@ -30,37 +27,17 @@ public final class PayloadExchangeMatchers {
}
public static PayloadExchangeMatcher setup() {
return new PayloadExchangeMatcher() {
@Override
public Mono<MatchResult> matches(PayloadExchange exchange) {
return PayloadExchangeType.SETUP.equals(exchange.getType()) ? MatchResult.match()
: MatchResult.notMatch();
}
};
return (exchange) -> PayloadExchangeType.SETUP.equals(exchange.getType())
? PayloadExchangeMatcher.MatchResult.match() : PayloadExchangeMatcher.MatchResult.notMatch();
}
public static PayloadExchangeMatcher anyRequest() {
return new PayloadExchangeMatcher() {
@Override
public Mono<MatchResult> matches(PayloadExchange exchange) {
return exchange.getType().isRequest() ? MatchResult.match() : MatchResult.notMatch();
}
};
return (exchange) -> exchange.getType().isRequest() ? PayloadExchangeMatcher.MatchResult.match()
: PayloadExchangeMatcher.MatchResult.notMatch();
}
public static PayloadExchangeMatcher anyExchange() {
return new PayloadExchangeMatcher() {
@Override
public Mono<MatchResult> matches(PayloadExchange exchange) {
return MatchResult.match();
}
};
return (exchange) -> PayloadExchangeMatcher.MatchResult.match();
}
}

View File

@ -52,8 +52,8 @@ public class RoutePayloadExchangeMatcher implements PayloadExchangeMatcher {
Map<String, Object> metadata = this.metadataExtractor.extract(exchange.getPayload(),
exchange.getMetadataMimeType());
return Optional.ofNullable((String) metadata.get(MetadataExtractor.ROUTE_KEY))
.map((routeValue) -> this.routeMatcher.parseRoute(routeValue))
.map((route) -> this.routeMatcher.matchAndExtract(this.pattern, route)).map((v) -> MatchResult.match(v))
.map(this.routeMatcher::parseRoute)
.map((route) -> this.routeMatcher.matchAndExtract(this.pattern, route)).map(MatchResult::match)
.orElse(MatchResult.notMatch());
}

View File

@ -129,8 +129,7 @@ public class Saml2WebSsoAuthenticationFilter extends AbstractAuthenticationProce
private void setAuthenticationRequestRepositoryIntoAuthenticationConverter(
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository) {
if (this.authenticationConverter instanceof Saml2AuthenticationTokenConverter) {
Saml2AuthenticationTokenConverter authenticationTokenConverter = (Saml2AuthenticationTokenConverter) this.authenticationConverter;
if (this.authenticationConverter instanceof Saml2AuthenticationTokenConverter authenticationTokenConverter) {
authenticationTokenConverter.setAuthenticationRequestRepository(authenticationRequestRepository);
}
}

View File

@ -48,10 +48,9 @@ public class RequestKey {
@Override
public boolean equals(Object obj) {
if (!(obj instanceof RequestKey)) {
if (!(obj instanceof RequestKey key)) {
return false;
}
RequestKey key = (RequestKey) obj;
if (!this.url.equals(key.url)) {
return false;
}

View File

@ -167,7 +167,7 @@ public class TokenBasedRememberMeServices extends AbstractRememberMeServices {
private long getTokenExpiryTime(String[] cookieTokens) {
try {
return new Long(cookieTokens[1]);
return Long.valueOf(cookieTokens[1]);
}
catch (NumberFormatException nfe) {
throw new InvalidCookieException(

View File

@ -385,7 +385,7 @@ public class DigestAuthenticationFilter extends GenericFilterBean implements Mes
}
// Extract expiry time from nonce
try {
this.nonceExpiryTime = new Long(nonceTokens[0]);
this.nonceExpiryTime = Long.valueOf(nonceTokens[0]);
}
catch (NumberFormatException nfe) {
throw new BadCredentialsException(DigestAuthenticationFilter.this.messages.getMessage(

View File

@ -46,7 +46,7 @@ public class ServerFormLoginAuthenticationConverter implements Function<ServerWe
@Override
@Deprecated
public Mono<Authentication> apply(ServerWebExchange exchange) {
return exchange.getFormData().map((data) -> createAuthentication(data));
return exchange.getFormData().map(this::createAuthentication);
}
private UsernamePasswordAuthenticationToken createAuthentication(MultiValueMap<String, String> data) {

View File

@ -277,8 +277,7 @@ public class SwitchUserWebFilter implements WebFilter {
private Optional<Authentication> extractSourceAuthentication(Authentication currentAuthentication) {
// iterate over granted authorities and find the 'switch user' authority
for (GrantedAuthority authority : currentAuthentication.getAuthorities()) {
if (authority instanceof SwitchUserGrantedAuthority) {
SwitchUserGrantedAuthority switchAuthority = (SwitchUserGrantedAuthority) authority;
if (authority instanceof SwitchUserGrantedAuthority switchAuthority) {
return Optional.of(switchAuthority.getSource());
}
}

View File

@ -41,7 +41,7 @@ public class ThrowableAnalyzer {
*
* @see Throwable#getCause()
*/
public static final ThrowableCauseExtractor DEFAULT_EXTRACTOR = (throwable) -> throwable.getCause();
public static final ThrowableCauseExtractor DEFAULT_EXTRACTOR = Throwable::getCause;
/**
* Default extractor for {@link InvocationTargetException} instances.

View File

@ -226,10 +226,9 @@ public final class AntPathRequestMatcher implements RequestMatcher, RequestVaria
@Override
public boolean equals(Object obj) {
if (!(obj instanceof AntPathRequestMatcher)) {
if (!(obj instanceof AntPathRequestMatcher other)) {
return false;
}
AntPathRequestMatcher other = (AntPathRequestMatcher) obj;
return this.pattern.equals(other.pattern) && this.httpMethod == other.httpMethod
&& this.caseSensitive == other.caseSensitive;
}

View File

@ -88,7 +88,7 @@ public class MediaTypeRequestMatcherTests {
@Test
public void constructorWhenEmptyMediaTypeThenIAE() {
assertThatIllegalArgumentException().isThrownBy(() -> new MediaTypeRequestMatcher());
assertThatIllegalArgumentException().isThrownBy(MediaTypeRequestMatcher::new);
}
@Test