1
0
mirror of synced 2026-08-03 08:51:58 +00:00

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