diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 3a5d849650..1e4804e2e6 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -38,7 +38,7 @@ jobs: - name: Set up JDK uses: actions/setup-java@f2beeb24e141e01a676f977032f5a29d81c9e27e # v5.1.0 with: - java-version: 11 + java-version: 17 distribution: temurin - name: License Check diff --git a/config/core/src/main/java/org/apache/shiro/config/Ini.java b/config/core/src/main/java/org/apache/shiro/config/Ini.java index b854c5e7b4..bc1a897ced 100644 --- a/config/core/src/main/java/org/apache/shiro/config/Ini.java +++ b/config/core/src/main/java/org/apache/shiro/config/Ini.java @@ -446,8 +446,7 @@ protected static String getSectionName(String line) { } public boolean equals(Object obj) { - if (obj instanceof Ini) { - Ini ini = (Ini) obj; + if (obj instanceof Ini ini) { return this.sections.equals(ini.sections); } return false; @@ -710,8 +709,7 @@ public String toString() { @Override public boolean equals(Object obj) { - if (obj instanceof Section) { - Section other = (Section) obj; + if (obj instanceof Section other) { return getName().equals(other.getName()) && this.props.equals(other.props); } return false; diff --git a/config/ogdl/src/main/java/org/apache/shiro/config/ogdl/ReflectionBuilder.java b/config/ogdl/src/main/java/org/apache/shiro/config/ogdl/ReflectionBuilder.java index c5f575b456..e6de827af6 100644 --- a/config/ogdl/src/main/java/org/apache/shiro/config/ogdl/ReflectionBuilder.java +++ b/config/ogdl/src/main/java/org/apache/shiro/config/ogdl/ReflectionBuilder.java @@ -232,14 +232,14 @@ protected EventBus findEventBus(Map objects) { //prefer a named object first: Object value = objects.get(EVENT_BUS_NAME); - if (value instanceof EventBus) { - return (EventBus) value; + if (value instanceof EventBus bus) { + return bus; } //couldn't find a named 'eventBus' EventBus object. Try to find the first typed value we can: for (Object v : objects.values()) { - if (v instanceof EventBus) { - return (EventBus) v; + if (v instanceof EventBus bus) { + return bus; } } @@ -247,8 +247,8 @@ protected EventBus findEventBus(Map objects) { } private boolean applyEventBusIfNecessary(Object value) { - if (value instanceof EventBusAware) { - ((EventBusAware) value).setEventBus(this.eventBus); + if (value instanceof EventBusAware aware) { + aware.setEventBus(this.eventBus); return true; } return false; @@ -357,8 +357,8 @@ protected void createNewInstance(Map objects, String name, Strin Object instance; try { instance = ClassUtils.newInstance(value); - if (instance instanceof Nameable) { - ((Nameable) instance).setName(name); + if (instance instanceof Nameable nameable) { + nameable.setName(name); } } catch (Exception e) { instance = alternateObjectSupplier.apply(value); @@ -455,8 +455,8 @@ protected Object resolveReference(String reference) { String id = getId(reference); LOGGER.debug("Encountered object reference '{}'. Looking up object with id '{}'", reference, id); final Object referencedObject = getReferencedObject(id); - if (referencedObject instanceof Factory) { - return ((Factory) referencedObject).getInstance(); + if (referencedObject instanceof Factory factory) { + return factory.getInstance(); } return referencedObject; } @@ -492,8 +492,8 @@ protected Set toSet(String sValue) { //SHIRO-423: check to see if the value is a referenced Set already, and if so, return it immediately: if (tokens.length == 1 && isReference(tokens[0])) { Object reference = resolveReference(tokens[0]); - if (reference instanceof Set) { - return (Set) reference; + if (reference instanceof Set set) { + return set; } } @@ -518,8 +518,8 @@ protected Set toSet(String sValue) { //SHIRO-423: check to see if the value is a referenced Map already, and if so, return it immediately: if (tokens.length == 1 && isReference(tokens[0])) { Object reference = resolveReference(tokens[0]); - if (reference instanceof Map) { - return (Map) reference; + if (reference instanceof Map map) { + return map; } } @@ -556,8 +556,8 @@ protected Collection toCollection(String sValue) { //SHIRO-423: check to see if the value is a referenced Collection already, and if so, return it immediately: if (tokens.length == 1 && isReference(tokens[0])) { Object reference = resolveReference(tokens[0]); - if (reference instanceof Collection) { - return (Collection) reference; + if (reference instanceof Collection collection) { + return collection; } } @@ -579,8 +579,8 @@ protected List toList(String sValue) { //SHIRO-423: check to see if the value is a referenced List already, and if so, return it immediately: if (tokens.length == 1 && isReference(tokens[0])) { Object reference = resolveReference(tokens[0]); - if (reference instanceof List) { - return (List) reference; + if (reference instanceof List list) { + return list; } } @@ -806,8 +806,7 @@ public void add(Statement statement) { //we execute bean configuration statements in the order they are declared. statements.add(statement); - if (statement instanceof InstantiationStatement) { - InstantiationStatement is = (InstantiationStatement) statement; + if (statement instanceof InstantiationStatement is) { beanConfigurations.add(new BeanConfiguration(is)); } else { AssignmentStatement as = (AssignmentStatement) statement; diff --git a/core/src/main/java/org/apache/shiro/authc/AbstractAuthenticator.java b/core/src/main/java/org/apache/shiro/authc/AbstractAuthenticator.java index 278dae9010..4c78affeeb 100644 --- a/core/src/main/java/org/apache/shiro/authc/AbstractAuthenticator.java +++ b/core/src/main/java/org/apache/shiro/authc/AbstractAuthenticator.java @@ -203,8 +203,8 @@ public final AuthenticationInfo authenticate(AuthenticationToken token) throws A } } catch (Throwable t) { AuthenticationException ae = null; - if (t instanceof AuthenticationException) { - ae = (AuthenticationException) t; + if (t instanceof AuthenticationException exception) { + ae = exception; } if (ae == null) { //Exception thrown was not an expected AuthenticationException. Therefore it is probably a little more diff --git a/core/src/main/java/org/apache/shiro/authc/SimpleAccount.java b/core/src/main/java/org/apache/shiro/authc/SimpleAccount.java index 310522d67f..3dfacf5610 100644 --- a/core/src/main/java/org/apache/shiro/authc/SimpleAccount.java +++ b/core/src/main/java/org/apache/shiro/authc/SimpleAccount.java @@ -99,7 +99,7 @@ public SimpleAccount(Object principal, Object credentials, String realmName) { * @since 1.1 */ public SimpleAccount(Object principal, Object hashedCredentials, ByteSource credentialsSalt, String realmName) { - this(principal instanceof PrincipalCollection ? (PrincipalCollection) principal + this(principal instanceof PrincipalCollection pc ? pc : ImmutablePrincipalCollection.ofSinglePrincipal(principal, realmName), hashedCredentials, credentialsSalt); } @@ -448,8 +448,7 @@ public void merge(AuthenticationInfo info) { authcInfo.merge(info); // Merge SimpleAccount specific info - if (info instanceof SimpleAccount) { - SimpleAccount otherAccount = (SimpleAccount) info; + if (info instanceof SimpleAccount otherAccount) { if (otherAccount.isLocked()) { setLocked(true); } @@ -482,8 +481,7 @@ public boolean equals(Object o) { if (o == this) { return true; } - if (o instanceof SimpleAccount) { - SimpleAccount sa = (SimpleAccount) o; + if (o instanceof SimpleAccount sa) { //principal should be unique across the application, so only check this for equality: return (getPrincipals() != null ? getPrincipals().equals(sa.getPrincipals()) : sa.getPrincipals() == null); } diff --git a/core/src/main/java/org/apache/shiro/authc/SimpleAuthenticationInfo.java b/core/src/main/java/org/apache/shiro/authc/SimpleAuthenticationInfo.java index 2ecae7d5eb..b39c20781a 100644 --- a/core/src/main/java/org/apache/shiro/authc/SimpleAuthenticationInfo.java +++ b/core/src/main/java/org/apache/shiro/authc/SimpleAuthenticationInfo.java @@ -23,6 +23,7 @@ import org.apache.shiro.subject.ImmutablePrincipalCollection; import org.apache.shiro.subject.PrincipalCollection; +import java.io.Serial; import java.util.Collection; import java.util.HashSet; import java.util.Objects; @@ -38,6 +39,7 @@ */ public class SimpleAuthenticationInfo implements MergableAuthenticationInfo, SaltedAuthenticationInfo { + @Serial private static final long serialVersionUID = 5390456512469696779L; /** * The principals identifying the account associated with this AuthenticationInfo instance. @@ -220,8 +222,8 @@ public void merge(AuthenticationInfo info) { //is null, then it can't hurt to pull in a non-null value if one exists. // //since 1.1: - if (this.credentialsSalt == null && info instanceof SaltedAuthenticationInfo) { - this.credentialsSalt = ((SaltedAuthenticationInfo) info).getCredentialsSalt(); + if (this.credentialsSalt == null && info instanceof SaltedAuthenticationInfo authenticationInfo) { + this.credentialsSalt = authenticationInfo.getCredentialsSalt(); } Object thisCredentials = getCredentials(); @@ -245,10 +247,8 @@ public void merge(AuthenticationInfo info) { // At this point, the credentials should be a collection @SuppressWarnings("unchecked") Collection credentialCollection = (Collection) getCredentials(); - if (otherCredentials instanceof Collection) { - @SuppressWarnings("unchecked") - Collection otherCredentialsCollection = (Collection) otherCredentials; - credentialCollection.addAll(otherCredentialsCollection); + if (otherCredentials instanceof Collection collection) { + credentialCollection.addAll(collection); } else { credentialCollection.add(otherCredentials); } diff --git a/core/src/main/java/org/apache/shiro/authc/credential/DefaultPasswordService.java b/core/src/main/java/org/apache/shiro/authc/credential/DefaultPasswordService.java index 8ec5d9fe35..e7a89a884a 100644 --- a/core/src/main/java/org/apache/shiro/authc/credential/DefaultPasswordService.java +++ b/core/src/main/java/org/apache/shiro/authc/credential/DefaultPasswordService.java @@ -169,9 +169,7 @@ public boolean passwordsMatch(Object submittedPlaintext, String saved) { //configuration changes. HashFormat discoveredFormat = this.hashFormatFactory.getInstance(saved); - if (discoveredFormat instanceof ParsableHashFormat) { - - ParsableHashFormat parsableHashFormat = (ParsableHashFormat) discoveredFormat; + if (discoveredFormat instanceof ParsableHashFormat parsableHashFormat) { Hash savedHash = parsableHashFormat.parse(saved); return passwordsMatch(submittedPlaintext, savedHash); diff --git a/core/src/main/java/org/apache/shiro/authc/credential/HashedCredentialsMatcher.java b/core/src/main/java/org/apache/shiro/authc/credential/HashedCredentialsMatcher.java index 262101cdca..032faee48d 100644 --- a/core/src/main/java/org/apache/shiro/authc/credential/HashedCredentialsMatcher.java +++ b/core/src/main/java/org/apache/shiro/authc/credential/HashedCredentialsMatcher.java @@ -402,8 +402,8 @@ public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo */ protected Object hashProvidedCredentials(AuthenticationToken token, AuthenticationInfo info) { final Object salt; - if (info instanceof SaltedAuthenticationInfo) { - salt = ((SaltedAuthenticationInfo) info).getCredentialsSalt(); + if (info instanceof SaltedAuthenticationInfo authenticationInfo) { + salt = authenticationInfo.getCredentialsSalt(); } else if (isHashSalted()) { //retain 1.0 backwards compatibility: salt = getSalt(token); diff --git a/core/src/main/java/org/apache/shiro/authc/credential/PasswordMatcher.java b/core/src/main/java/org/apache/shiro/authc/credential/PasswordMatcher.java index 01e10e357e..b030a71a2e 100644 --- a/core/src/main/java/org/apache/shiro/authc/credential/PasswordMatcher.java +++ b/core/src/main/java/org/apache/shiro/authc/credential/PasswordMatcher.java @@ -49,8 +49,7 @@ public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo Object storedCredentials = getStoredPassword(info); assertStoredCredentialsType(storedCredentials); - if (storedCredentials instanceof Hash) { - Hash hashedPassword = (Hash) storedCredentials; + if (storedCredentials instanceof Hash hashedPassword) { return hashedPassword.matchesPassword(ByteSource.Util.bytes(submittedPassword)); } //otherwise they are a String (asserted in the 'assertStoredCredentialsType' method call above): @@ -89,8 +88,8 @@ private void assertStoredCredentialsType(Object credentials) { protected Object getStoredPassword(AuthenticationInfo storedAccountInfo) { Object stored = storedAccountInfo != null ? storedAccountInfo.getCredentials() : null; //fix for https://issues.apache.org/jira/browse/SHIRO-363 - if (stored instanceof char[]) { - stored = new String((char[]) stored); + if (stored instanceof char[] chars) { + stored = new String(chars); } return stored; } diff --git a/core/src/main/java/org/apache/shiro/authc/pam/AbstractAuthenticationStrategy.java b/core/src/main/java/org/apache/shiro/authc/pam/AbstractAuthenticationStrategy.java index 718578f954..f8cb026fa3 100644 --- a/core/src/main/java/org/apache/shiro/authc/pam/AbstractAuthenticationStrategy.java +++ b/core/src/main/java/org/apache/shiro/authc/pam/AbstractAuthenticationStrategy.java @@ -87,8 +87,8 @@ public AuthenticationInfo afterAttempt(Realm realm, AuthenticationToken token, * {@link org.apache.shiro.authc.MergableAuthenticationInfo MergableAuthenticationInfo} is not desired for some reason. */ protected AuthenticationInfo merge(AuthenticationInfo info, AuthenticationInfo aggregate) { - if (aggregate instanceof MergableAuthenticationInfo) { - ((MergableAuthenticationInfo) aggregate).merge(info); + if (aggregate instanceof MergableAuthenticationInfo authenticationInfo) { + authenticationInfo.merge(info); return aggregate; } else { throw new IllegalArgumentException("Attempt to merge authentication info from multiple realms, but aggregate " diff --git a/core/src/main/java/org/apache/shiro/authc/pam/AllSuccessfulStrategy.java b/core/src/main/java/org/apache/shiro/authc/pam/AllSuccessfulStrategy.java index 8d200a85dc..31cb56ab1f 100644 --- a/core/src/main/java/org/apache/shiro/authc/pam/AllSuccessfulStrategy.java +++ b/core/src/main/java/org/apache/shiro/authc/pam/AllSuccessfulStrategy.java @@ -80,9 +80,9 @@ public AuthenticationInfo afterAttempt(Realm realm, AuthenticationToken token, AuthenticationInfo info, AuthenticationInfo aggregate, Throwable t) throws AuthenticationException { if (t != null) { - if (t instanceof AuthenticationException) { + if (t instanceof AuthenticationException exception) { //propagate: - throw ((AuthenticationException) t); + throw exception; } else { String msg = "Unable to acquire account data from realm [" + realm + "]. The [" + getClass().getName() + " implementation requires all configured realm(s) to operate successfully " diff --git a/core/src/main/java/org/apache/shiro/authc/pam/ModularRealmAuthenticator.java b/core/src/main/java/org/apache/shiro/authc/pam/ModularRealmAuthenticator.java index c59ea6d2c7..596588130e 100644 --- a/core/src/main/java/org/apache/shiro/authc/pam/ModularRealmAuthenticator.java +++ b/core/src/main/java/org/apache/shiro/authc/pam/ModularRealmAuthenticator.java @@ -294,8 +294,8 @@ public void onLogout(PrincipalCollection principals) { Collection realms = getRealms(); if (!CollectionUtils.isEmpty(realms)) { for (Realm realm : realms) { - if (realm instanceof LogoutAware) { - ((LogoutAware) realm).onLogout(principals); + if (realm instanceof LogoutAware aware) { + aware.onLogout(principals); } } } diff --git a/core/src/main/java/org/apache/shiro/authz/ModularRealmAuthorizer.java b/core/src/main/java/org/apache/shiro/authz/ModularRealmAuthorizer.java index 937b7e5cbf..1c1b178b8a 100644 --- a/core/src/main/java/org/apache/shiro/authz/ModularRealmAuthorizer.java +++ b/core/src/main/java/org/apache/shiro/authz/ModularRealmAuthorizer.java @@ -137,8 +137,8 @@ protected void applyPermissionResolverToRealms() { Collection realms = getRealms(); if (resolver != null && realms != null && !realms.isEmpty()) { for (Realm realm : realms) { - if (realm instanceof PermissionResolverAware) { - ((PermissionResolverAware) realm).setPermissionResolver(resolver); + if (realm instanceof PermissionResolverAware aware) { + aware.setPermissionResolver(resolver); } } } @@ -193,8 +193,8 @@ protected void applyRolePermissionResolverToRealms() { Collection realms = getRealms(); if (resolver != null && realms != null && !realms.isEmpty()) { for (Realm realm : realms) { - if (realm instanceof RolePermissionResolverAware) { - ((RolePermissionResolverAware) realm).setRolePermissionResolver(resolver); + if (realm instanceof RolePermissionResolverAware aware) { + aware.setRolePermissionResolver(resolver); } } } diff --git a/core/src/main/java/org/apache/shiro/authz/SimpleRole.java b/core/src/main/java/org/apache/shiro/authz/SimpleRole.java index 8dcdd876bc..addeccb739 100644 --- a/core/src/main/java/org/apache/shiro/authz/SimpleRole.java +++ b/core/src/main/java/org/apache/shiro/authz/SimpleRole.java @@ -102,8 +102,7 @@ public boolean equals(Object o) { if (o == this) { return true; } - if (o instanceof SimpleRole) { - SimpleRole sr = (SimpleRole) o; + if (o instanceof SimpleRole sr) { //only check name, since role names should be unique across an entire application: return (getName() != null ? getName().equals(sr.getName()) : sr.getName() == null); } diff --git a/core/src/main/java/org/apache/shiro/authz/permission/DomainPermission.java b/core/src/main/java/org/apache/shiro/authz/permission/DomainPermission.java index 154b511b99..765468e5f7 100644 --- a/core/src/main/java/org/apache/shiro/authz/permission/DomainPermission.java +++ b/core/src/main/java/org/apache/shiro/authz/permission/DomainPermission.java @@ -20,6 +20,7 @@ import org.apache.shiro.lang.util.StringUtils; +import java.io.Serial; import java.util.Set; /** @@ -32,6 +33,7 @@ */ public class DomainPermission extends WildcardPermission { + @Serial private static final long serialVersionUID = 1L; private String domain; diff --git a/core/src/main/java/org/apache/shiro/authz/permission/WildcardPermission.java b/core/src/main/java/org/apache/shiro/authz/permission/WildcardPermission.java index dd8f1c5011..0f80e77b13 100644 --- a/core/src/main/java/org/apache/shiro/authz/permission/WildcardPermission.java +++ b/core/src/main/java/org/apache/shiro/authz/permission/WildcardPermission.java @@ -252,8 +252,7 @@ public String toString() { } public boolean equals(Object o) { - if (o instanceof WildcardPermission) { - WildcardPermission wp = (WildcardPermission) o; + if (o instanceof WildcardPermission wp) { return parts.equals(wp.parts); } return false; diff --git a/core/src/main/java/org/apache/shiro/ini/IniSecurityManagerFactory.java b/core/src/main/java/org/apache/shiro/ini/IniSecurityManagerFactory.java index 328dce68bc..98d90d0beb 100644 --- a/core/src/main/java/org/apache/shiro/ini/IniSecurityManagerFactory.java +++ b/core/src/main/java/org/apache/shiro/ini/IniSecurityManagerFactory.java @@ -132,9 +132,8 @@ private Ini.Section getConfigSection(Ini ini) { protected boolean isAutoApplyRealms(SecurityManager securityManager) { boolean autoApply = true; - if (securityManager instanceof RealmSecurityManager) { - //only apply realms if they haven't been explicitly set by the user: - RealmSecurityManager realmSecurityManager = (RealmSecurityManager) securityManager; + if (securityManager instanceof RealmSecurityManager realmSecurityManager) { + // only apply realms if they haven't been explicitly set by the user: Collection realms = realmSecurityManager.getRealms(); if (!CollectionUtils.isEmpty(realms)) { LOGGER.info("Realms have been explicitly set on the SecurityManager instance - auto-setting of " @@ -215,15 +214,14 @@ private Collection getRealms(Map instances) { String name = entry.getKey(); Object value = entry.getValue(); - if (value instanceof RealmFactory) { - addToRealms(realms, (RealmFactory) value); - } else if (value instanceof Realm) { - Realm realm = (Realm) value; + if (value instanceof RealmFactory factory) { + addToRealms(realms, factory); + } else if (value instanceof Realm realm) { //set the name if null: String existingName = realm.getName(); if (existingName == null || existingName.startsWith(realm.getClass().getName())) { - if (realm instanceof Nameable) { - ((Nameable) realm).setName(name); + if (realm instanceof Nameable nameable) { + nameable.setName(name); LOGGER.debug("Applied name '{}' to Nameable realm instance {}", name, realm); } else { LOGGER.info("Realm does not implement the {} interface. Configured name will not be applied.", diff --git a/core/src/main/java/org/apache/shiro/mgt/AbstractRememberMeManager.java b/core/src/main/java/org/apache/shiro/mgt/AbstractRememberMeManager.java index 9107cd679d..6ddee7e4e4 100644 --- a/core/src/main/java/org/apache/shiro/mgt/AbstractRememberMeManager.java +++ b/core/src/main/java/org/apache/shiro/mgt/AbstractRememberMeManager.java @@ -276,7 +276,7 @@ public void setCipherKey(byte[] cipherKey) { * @return true if remember me services should be performed as a result of the successful authentication attempt. */ protected boolean isRememberMe(AuthenticationToken token) { - return token instanceof RememberMeAuthenticationToken && ((RememberMeAuthenticationToken) token).isRememberMe(); + return token instanceof RememberMeAuthenticationToken rmat && rmat.isRememberMe(); } /** diff --git a/core/src/main/java/org/apache/shiro/mgt/AuthenticatingSecurityManager.java b/core/src/main/java/org/apache/shiro/mgt/AuthenticatingSecurityManager.java index a455e0898d..8696a21588 100644 --- a/core/src/main/java/org/apache/shiro/mgt/AuthenticatingSecurityManager.java +++ b/core/src/main/java/org/apache/shiro/mgt/AuthenticatingSecurityManager.java @@ -94,8 +94,8 @@ public void setAuthenticator(Authenticator authenticator) throws IllegalArgument */ protected void afterRealmsSet() { super.afterRealmsSet(); - if (this.authenticator instanceof ModularRealmAuthenticator) { - ((ModularRealmAuthenticator) this.authenticator).setRealms(getRealms()); + if (this.authenticator instanceof ModularRealmAuthenticator realmAuthenticator) { + realmAuthenticator.setRealms(getRealms()); } } diff --git a/core/src/main/java/org/apache/shiro/mgt/AuthorizingSecurityManager.java b/core/src/main/java/org/apache/shiro/mgt/AuthorizingSecurityManager.java index 0cbea9dc02..9152d0182b 100644 --- a/core/src/main/java/org/apache/shiro/mgt/AuthorizingSecurityManager.java +++ b/core/src/main/java/org/apache/shiro/mgt/AuthorizingSecurityManager.java @@ -98,8 +98,8 @@ public void setAuthorizer(Authorizer authorizer) { */ protected void afterRealmsSet() { super.afterRealmsSet(); - if (this.authorizer instanceof ModularRealmAuthorizer) { - ((ModularRealmAuthorizer) this.authorizer).setRealms(getRealms()); + if (this.authorizer instanceof ModularRealmAuthorizer realmAuthorizer) { + realmAuthorizer.setRealms(getRealms()); } } diff --git a/core/src/main/java/org/apache/shiro/mgt/CachingSecurityManager.java b/core/src/main/java/org/apache/shiro/mgt/CachingSecurityManager.java index d83f971fc8..52eb434d50 100644 --- a/core/src/main/java/org/apache/shiro/mgt/CachingSecurityManager.java +++ b/core/src/main/java/org/apache/shiro/mgt/CachingSecurityManager.java @@ -124,8 +124,8 @@ public void setEventBus(EventBus eventBus) { * @since 1.3 */ protected void applyEventBusToCacheManager() { - if (this.eventBus != null && this.cacheManager != null && this.cacheManager instanceof EventBusAware) { - ((EventBusAware) this.cacheManager).setEventBus(this.eventBus); + if (this.eventBus != null && this.cacheManager != null && this.cacheManager instanceof EventBusAware aware) { + aware.setEventBus(this.eventBus); } } diff --git a/core/src/main/java/org/apache/shiro/mgt/DefaultSecurityManager.java b/core/src/main/java/org/apache/shiro/mgt/DefaultSecurityManager.java index 4739971942..73fdfe505b 100644 --- a/core/src/main/java/org/apache/shiro/mgt/DefaultSecurityManager.java +++ b/core/src/main/java/org/apache/shiro/mgt/DefaultSecurityManager.java @@ -564,8 +564,8 @@ public void logout(Subject subject) { LOGGER.debug("Logging out subject with primary principal {}", principals.getPrimaryPrincipal()); } Authenticator authc = getAuthenticator(); - if (authc instanceof LogoutAware) { - ((LogoutAware) authc).onLogout(principals); + if (authc instanceof LogoutAware aware) { + aware.onLogout(principals); } } diff --git a/core/src/main/java/org/apache/shiro/mgt/RealmSecurityManager.java b/core/src/main/java/org/apache/shiro/mgt/RealmSecurityManager.java index 748ddd169a..b7323d2477 100644 --- a/core/src/main/java/org/apache/shiro/mgt/RealmSecurityManager.java +++ b/core/src/main/java/org/apache/shiro/mgt/RealmSecurityManager.java @@ -114,8 +114,8 @@ protected void applyCacheManagerToRealms() { Collection realms = getRealms(); if (cacheManager != null && realms != null && !realms.isEmpty()) { for (Realm realm : realms) { - if (realm instanceof CacheManagerAware) { - ((CacheManagerAware) realm).setCacheManager(cacheManager); + if (realm instanceof CacheManagerAware aware) { + aware.setCacheManager(cacheManager); } } } @@ -140,8 +140,8 @@ protected void applyEventBusToRealms() { Collection realms = getRealms(); if (eventBus != null && realms != null && !realms.isEmpty()) { for (Realm realm : realms) { - if (realm instanceof EventBusAware) { - ((EventBusAware) realm).setEventBus(eventBus); + if (realm instanceof EventBusAware aware) { + aware.setEventBus(eventBus); } } } diff --git a/core/src/main/java/org/apache/shiro/mgt/SessionsSecurityManager.java b/core/src/main/java/org/apache/shiro/mgt/SessionsSecurityManager.java index e2180888e8..277f0edf7b 100644 --- a/core/src/main/java/org/apache/shiro/mgt/SessionsSecurityManager.java +++ b/core/src/main/java/org/apache/shiro/mgt/SessionsSecurityManager.java @@ -127,8 +127,8 @@ protected void afterEventBusSet() { * instance implements the {@link CacheManagerAware CacheManagerAware} interface. */ protected void applyCacheManagerToSessionManager() { - if (this.sessionManager instanceof CacheManagerAware) { - ((CacheManagerAware) this.sessionManager).setCacheManager(getCacheManager()); + if (this.sessionManager instanceof CacheManagerAware aware) { + aware.setCacheManager(getCacheManager()); } } @@ -143,8 +143,8 @@ protected void applyCacheManagerToSessionManager() { */ protected void applyEventBusToSessionManager() { EventBus eventBus = getEventBus(); - if (eventBus != null && this.sessionManager instanceof EventBusAware) { - ((EventBusAware) this.sessionManager).setEventBus(eventBus); + if (eventBus != null && this.sessionManager instanceof EventBusAware aware) { + aware.setEventBus(eventBus); } } diff --git a/core/src/main/java/org/apache/shiro/realm/ldap/DefaultLdapRealm.java b/core/src/main/java/org/apache/shiro/realm/ldap/DefaultLdapRealm.java index d742f7bf30..7f52f2b18c 100644 --- a/core/src/main/java/org/apache/shiro/realm/ldap/DefaultLdapRealm.java +++ b/core/src/main/java/org/apache/shiro/realm/ldap/DefaultLdapRealm.java @@ -336,8 +336,7 @@ protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal */ protected Object getLdapPrincipal(AuthenticationToken token) { Object principal = token.getPrincipal(); - if (principal instanceof String) { - String sPrincipal = (String) principal; + if (principal instanceof String sPrincipal) { return getUserDn(sPrincipal); } return principal; diff --git a/core/src/main/java/org/apache/shiro/realm/ldap/JndiLdapContextFactory.java b/core/src/main/java/org/apache/shiro/realm/ldap/JndiLdapContextFactory.java index 9b25b81d75..a7806a7245 100644 --- a/core/src/main/java/org/apache/shiro/realm/ldap/JndiLdapContextFactory.java +++ b/core/src/main/java/org/apache/shiro/realm/ldap/JndiLdapContextFactory.java @@ -518,8 +518,8 @@ protected void validateAuthenticationInfo(Hashtable environment) // from the FAQ, we need to check for empty credentials: // http://docs.oracle.com/javase/tutorial/jndi/ldap/faq.html if (credentials == null - || (credentials instanceof byte[] && ((byte[]) credentials).length <= 0) - || (credentials instanceof char[] && ((char[]) credentials).length <= 0) + || (credentials instanceof byte[] bytes && bytes.length <= 0) + || (credentials instanceof char[] chars && chars.length <= 0) || (String.class.isInstance(credentials) && !StringUtils.hasText(String.valueOf(credentials)))) { throw new javax.naming.AuthenticationException("LDAP Simple authentication requires both a " diff --git a/core/src/main/java/org/apache/shiro/session/Session.java b/core/src/main/java/org/apache/shiro/session/Session.java index 109dc69129..5a929e4658 100644 --- a/core/src/main/java/org/apache/shiro/session/Session.java +++ b/core/src/main/java/org/apache/shiro/session/Session.java @@ -29,7 +29,7 @@ * A {@code Session} is intended to be managed by the business tier and accessible via other * tiers without being tied to any given client technology. This is a great benefit to Java * systems, since until now, the only viable session mechanisms were the - * {@code javax.servlet.http.HttpSession} or Stateful Session EJB's, which many times + * {@code jakarta.servlet.http.HttpSession} or Stateful Session EJB's, which many times * unnecessarily coupled applications to web or ejb technologies. * * @since 0.1 diff --git a/core/src/main/java/org/apache/shiro/session/mgt/AbstractValidatingSessionManager.java b/core/src/main/java/org/apache/shiro/session/mgt/AbstractValidatingSessionManager.java index d289660674..79d037aa31 100644 --- a/core/src/main/java/org/apache/shiro/session/mgt/AbstractValidatingSessionManager.java +++ b/core/src/main/java/org/apache/shiro/session/mgt/AbstractValidatingSessionManager.java @@ -174,8 +174,8 @@ protected void afterExpired(Session session) { } protected void onInvalidation(Session s, InvalidSessionException ise, SessionKey key) { - if (ise instanceof ExpiredSessionException) { - onExpiration(s, (ExpiredSessionException) ise, key); + if (ise instanceof ExpiredSessionException exception) { + onExpiration(s, exception, key); return; } LOGGER.trace("Session with id [{}] is invalid.", s.getId()); @@ -188,8 +188,8 @@ protected void onInvalidation(Session s, InvalidSessionException ise, SessionKey } protected void doValidate(Session session) throws InvalidSessionException { - if (session instanceof ValidatingSession) { - ((ValidatingSession) session).validate(); + if (session instanceof ValidatingSession validatingSession) { + validatingSession.validate(); } else { String msg = "The " + getClass().getName() + " implementation only supports validating " + "Session implementations of the " + ValidatingSession.class.getName() + " interface. " diff --git a/core/src/main/java/org/apache/shiro/session/mgt/DefaultSessionContext.java b/core/src/main/java/org/apache/shiro/session/mgt/DefaultSessionContext.java index 2f08b2dc83..702148dbc8 100644 --- a/core/src/main/java/org/apache/shiro/session/mgt/DefaultSessionContext.java +++ b/core/src/main/java/org/apache/shiro/session/mgt/DefaultSessionContext.java @@ -21,6 +21,7 @@ import org.apache.shiro.util.MapContext; import org.apache.shiro.lang.util.StringUtils; +import java.io.Serial; import java.io.Serializable; import java.util.Map; @@ -32,6 +33,7 @@ */ public class DefaultSessionContext extends MapContext implements SessionContext { + @Serial private static final long serialVersionUID = -1424160751361252966L; private static final String HOST = DefaultSessionContext.class.getName() + ".HOST"; diff --git a/core/src/main/java/org/apache/shiro/session/mgt/DefaultSessionManager.java b/core/src/main/java/org/apache/shiro/session/mgt/DefaultSessionManager.java index 604a9de425..07c62cdea7 100644 --- a/core/src/main/java/org/apache/shiro/session/mgt/DefaultSessionManager.java +++ b/core/src/main/java/org/apache/shiro/session/mgt/DefaultSessionManager.java @@ -145,8 +145,8 @@ public void setCacheManager(CacheManager cacheManager) { * @since 1.0 */ private void applyCacheManagerToSessionDAO() { - if (this.cacheManager != null && this.sessionDAO != null && this.sessionDAO instanceof CacheManagerAware) { - ((CacheManagerAware) this.sessionDAO).setCacheManager(this.cacheManager); + if (this.cacheManager != null && this.sessionDAO != null && this.sessionDAO instanceof CacheManagerAware aware) { + aware.setCacheManager(this.cacheManager); } } @@ -179,8 +179,7 @@ protected void create(Session session) { @Override protected void onStop(Session session) { - if (session instanceof SimpleSession) { - SimpleSession ss = (SimpleSession) session; + if (session instanceof SimpleSession ss) { Date stopTs = ss.getStopTimestamp(); ss.setLastAccessTime(stopTs); } @@ -195,8 +194,8 @@ protected void afterStopped(Session session) { } protected void onExpiration(Session session) { - if (session instanceof SimpleSession) { - ((SimpleSession) session).setExpired(true); + if (session instanceof SimpleSession simpleSession) { + simpleSession.setExpired(true); } onChange(session); } diff --git a/core/src/main/java/org/apache/shiro/session/mgt/SessionContext.java b/core/src/main/java/org/apache/shiro/session/mgt/SessionContext.java index 36471ed57f..fb9950d3da 100644 --- a/core/src/main/java/org/apache/shiro/session/mgt/SessionContext.java +++ b/core/src/main/java/org/apache/shiro/session/mgt/SessionContext.java @@ -46,7 +46,7 @@ public interface SessionContext extends Map { * {@code Session}. *

* In web-based systems, this host can be inferred from the incoming request, e.g. - * {@code javax.servlet.ServletRequest#getRemoteAddr()} or {@code javax.servlet.ServletRequest#getRemoteHost()} + * {@code jakarta.servlet.ServletRequest#getRemoteAddr()} or {@code jakarta.servlet.ServletRequest#getRemoteHost()} * methods, or in socket-based systems, it can be obtained via inspecting the socket * initiator's host IP. *

diff --git a/core/src/main/java/org/apache/shiro/session/mgt/SimpleSession.java b/core/src/main/java/org/apache/shiro/session/mgt/SimpleSession.java index 8b125a3184..fbe8df02a1 100644 --- a/core/src/main/java/org/apache/shiro/session/mgt/SimpleSession.java +++ b/core/src/main/java/org/apache/shiro/session/mgt/SimpleSession.java @@ -28,6 +28,7 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.io.Serial; import java.io.Serializable; import java.text.DateFormat; import java.util.Collection; @@ -58,6 +59,7 @@ public class SimpleSession implements ValidatingSession, Serializable { // that is NOT serialization backwards compatible. Serialization-compatible // changes do not require a change to this number. If you need to generate // a new number in this case, use the JDK's 'serialver' program to generate it. + @Serial private static final long serialVersionUID = -7125642695178165650L; private static final Logger LOGGER = LoggerFactory.getLogger(SimpleSession.class); @@ -357,8 +359,7 @@ public boolean equals(Object obj) { if (this == obj) { return true; } - if (obj instanceof SimpleSession) { - SimpleSession other = (SimpleSession) obj; + if (obj instanceof SimpleSession other) { Serializable thisId = getId(); Serializable otherId = other.getId(); if (thisId != null && otherId != null) { diff --git a/core/src/main/java/org/apache/shiro/session/mgt/eis/CachingSessionDAO.java b/core/src/main/java/org/apache/shiro/session/mgt/eis/CachingSessionDAO.java index 6ed409c187..211d0f6e94 100644 --- a/core/src/main/java/org/apache/shiro/session/mgt/eis/CachingSessionDAO.java +++ b/core/src/main/java/org/apache/shiro/session/mgt/eis/CachingSessionDAO.java @@ -275,8 +275,8 @@ public Session readSession(Serializable sessionId) throws UnknownSessionExceptio */ public void update(Session session) throws UnknownSessionException { doUpdate(session); - if (session instanceof ValidatingSession) { - if (((ValidatingSession) session).isValid()) { + if (session instanceof ValidatingSession validatingSession) { + if (validatingSession.isValid()) { cache(session, session.getId()); } else { uncache(session); diff --git a/core/src/main/java/org/apache/shiro/subject/SimplePrincipalCollection.java b/core/src/main/java/org/apache/shiro/subject/SimplePrincipalCollection.java index ea1bdbe6d6..b488480480 100644 --- a/core/src/main/java/org/apache/shiro/subject/SimplePrincipalCollection.java +++ b/core/src/main/java/org/apache/shiro/subject/SimplePrincipalCollection.java @@ -24,6 +24,7 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.io.Serial; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -57,6 +58,7 @@ public class SimplePrincipalCollection implements MutablePrincipalCollection { // that is NOT serialization backwards compatible. Serialization-compatible // changes do not require a change to this number. If you need to generate // a new number in this case, use the JDK's 'serialver' program to generate it. + @Serial private static final long serialVersionUID = -6305224034025797558L; //TODO - complete JavaDoc @@ -69,8 +71,8 @@ public SimplePrincipalCollection() { } public SimplePrincipalCollection(Object principal, String realmName) { - if (principal instanceof Collection) { - addAll((Collection) principal, realmName); + if (principal instanceof Collection collection) { + addAll(collection, realmName); } else { add(principal, realmName); } @@ -243,8 +245,7 @@ public boolean equals(Object o) { if (o == this) { return true; } - if (o instanceof SimplePrincipalCollection) { - SimplePrincipalCollection other = (SimplePrincipalCollection) o; + if (o instanceof SimplePrincipalCollection other) { return Objects.equals(this.realmPrincipals, other.realmPrincipals); } return false; diff --git a/core/src/main/java/org/apache/shiro/subject/support/DefaultSubjectContext.java b/core/src/main/java/org/apache/shiro/subject/support/DefaultSubjectContext.java index b2d9d99986..54cb73e4dc 100644 --- a/core/src/main/java/org/apache/shiro/subject/support/DefaultSubjectContext.java +++ b/core/src/main/java/org/apache/shiro/subject/support/DefaultSubjectContext.java @@ -265,8 +265,8 @@ public String resolveHost() { if (host == null) { //check to see if there is an AuthenticationToken from which to retrieve it: AuthenticationToken token = getAuthenticationToken(); - if (token instanceof HostAuthenticationToken) { - host = ((HostAuthenticationToken) token).getHost(); + if (token instanceof HostAuthenticationToken authenticationToken) { + host = authenticationToken.getHost(); } } diff --git a/core/src/main/java/org/apache/shiro/subject/support/DelegatingSubject.java b/core/src/main/java/org/apache/shiro/subject/support/DelegatingSubject.java index b96c97d1b2..903006bc57 100644 --- a/core/src/main/java/org/apache/shiro/subject/support/DelegatingSubject.java +++ b/core/src/main/java/org/apache/shiro/subject/support/DelegatingSubject.java @@ -265,8 +265,7 @@ public void login(AuthenticationToken token) throws AuthenticationException { String host = null; - if (subject instanceof DelegatingSubject) { - DelegatingSubject delegating = (DelegatingSubject) subject; + if (subject instanceof DelegatingSubject delegating) { //we have to do this in case there are assumed identities - we don't want to lose the 'real' principals: principals = delegating.principals; host = delegating.host; @@ -281,8 +280,8 @@ public void login(AuthenticationToken token) throws AuthenticationException { } this.principals = principals; this.authenticated = true; - if (token instanceof HostAuthenticationToken) { - host = ((HostAuthenticationToken) token).getHost(); + if (token instanceof HostAuthenticationToken authenticationToken) { + host = authenticationToken.getHost(); } if (host != null) { this.host = host; diff --git a/core/src/main/java/org/apache/shiro/subject/support/SubjectThreadState.java b/core/src/main/java/org/apache/shiro/subject/support/SubjectThreadState.java index 50a9c043d0..43d47259a2 100644 --- a/core/src/main/java/org/apache/shiro/subject/support/SubjectThreadState.java +++ b/core/src/main/java/org/apache/shiro/subject/support/SubjectThreadState.java @@ -59,8 +59,8 @@ public SubjectThreadState(Subject subject) { this.subject = subject; SecurityManager securityManager = null; - if (subject instanceof DelegatingSubject) { - securityManager = ((DelegatingSubject) subject).getSecurityManager(); + if (subject instanceof DelegatingSubject delegatingSubject) { + securityManager = delegatingSubject.getSecurityManager(); } if (securityManager == null) { securityManager = ThreadContext.getSecurityManager(); diff --git a/core/src/main/java/org/apache/shiro/util/MapContext.java b/core/src/main/java/org/apache/shiro/util/MapContext.java index 9adbc4d91a..c379d8a25e 100644 --- a/core/src/main/java/org/apache/shiro/util/MapContext.java +++ b/core/src/main/java/org/apache/shiro/util/MapContext.java @@ -18,6 +18,7 @@ */ package org.apache.shiro.util; +import java.io.Serial; import java.io.Serializable; import java.util.Collection; import java.util.Collections; @@ -35,6 +36,7 @@ */ public class MapContext implements Map, Serializable { + @Serial private static final long serialVersionUID = 5373399119017820322L; private final Map backingMap; diff --git a/core/src/test/java/org/apache/shiro/realm/text/TextConfigurationRealmTest.java b/core/src/test/java/org/apache/shiro/realm/text/TextConfigurationRealmTest.java index 98f37fb3d7..4384a6fa44 100644 --- a/core/src/test/java/org/apache/shiro/realm/text/TextConfigurationRealmTest.java +++ b/core/src/test/java/org/apache/shiro/realm/text/TextConfigurationRealmTest.java @@ -46,7 +46,7 @@ private void setRoles() { private void setUsers() { StringBuilder userDefinitions = new StringBuilder(); for (int i = 1; i < 3; i++) { - userDefinitions.append(String.format("user%1$d = user%1$d_password, role1, role2%n", i)); + userDefinitions.append("user%1$d = user%1$d_password, role1, role2%n".formatted(i)); } realm.setUserDefinitions(userDefinitions.toString()); } diff --git a/core/src/test/java/org/apache/shiro/session/mgt/DefaultSessionManagerTest.java b/core/src/test/java/org/apache/shiro/session/mgt/DefaultSessionManagerTest.java index fe57038985..b0b88d7308 100644 --- a/core/src/test/java/org/apache/shiro/session/mgt/DefaultSessionManagerTest.java +++ b/core/src/test/java/org/apache/shiro/session/mgt/DefaultSessionManagerTest.java @@ -252,7 +252,7 @@ public void appendTo(StringBuffer buffer) { } public boolean matches(Object o) { - return o instanceof Session && ((Session) o).getTimeout() == this.timeout; + return o instanceof Session session && session.getTimeout() == this.timeout; } } } diff --git a/core/src/test/resources/log4j2-list.xml b/core/src/test/resources/log4j2-list.xml index fcba6549d2..4b7d36a058 100644 --- a/core/src/test/resources/log4j2-list.xml +++ b/core/src/test/resources/log4j2-list.xml @@ -30,7 +30,7 @@ - + diff --git a/core/src/test/resources/log4j2-test.xml b/core/src/test/resources/log4j2-test.xml index 6238801f34..a045f754ca 100644 --- a/core/src/test/resources/log4j2-test.xml +++ b/core/src/test/resources/log4j2-test.xml @@ -30,7 +30,7 @@ - + diff --git a/crypto/hash/src/main/java/org/apache/shiro/crypto/hash/AbstractCryptHash.java b/crypto/hash/src/main/java/org/apache/shiro/crypto/hash/AbstractCryptHash.java index 631505b8d9..9d13435b62 100644 --- a/crypto/hash/src/main/java/org/apache/shiro/crypto/hash/AbstractCryptHash.java +++ b/crypto/hash/src/main/java/org/apache/shiro/crypto/hash/AbstractCryptHash.java @@ -23,6 +23,7 @@ import org.apache.shiro.lang.codec.Hex; import org.apache.shiro.lang.util.ByteSource; +import java.io.Serial; import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.util.Arrays; @@ -49,6 +50,7 @@ public abstract class AbstractCryptHash implements Hash, Serializable { protected static final Pattern DELIMITER = Pattern.compile("\\$"); + @Serial private static final long serialVersionUID = 2483214646921027859L; private final String algorithmName; @@ -215,8 +217,7 @@ public String toBase64() { */ @Override public boolean equals(final Object other) { - if (other instanceof AbstractCryptHash) { - final AbstractCryptHash that = (AbstractCryptHash) other; + if (other instanceof AbstractCryptHash that) { return this.formatToCryptString().equals(that.formatToCryptString()); } return false; diff --git a/crypto/hash/src/main/java/org/apache/shiro/crypto/hash/AbstractHash.java b/crypto/hash/src/main/java/org/apache/shiro/crypto/hash/AbstractHash.java index 5c84a8799c..ef96babab7 100644 --- a/crypto/hash/src/main/java/org/apache/shiro/crypto/hash/AbstractHash.java +++ b/crypto/hash/src/main/java/org/apache/shiro/crypto/hash/AbstractHash.java @@ -24,6 +24,7 @@ import org.apache.shiro.lang.codec.CodecSupport; import org.apache.shiro.lang.codec.Hex; +import java.io.Serial; import java.io.Serializable; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -46,6 +47,7 @@ @Deprecated public abstract class AbstractHash extends CodecSupport implements Hash, Serializable { + @Serial private static final long serialVersionUID = -4723044219611288405L; /** * The hashed data @@ -283,8 +285,7 @@ public String toString() { */ @Override public boolean equals(Object o) { - if (o instanceof Hash) { - Hash other = (Hash) o; + if (o instanceof Hash other) { return MessageDigest.isEqual(getBytes(), other.getBytes()); } return false; diff --git a/crypto/hash/src/main/java/org/apache/shiro/crypto/hash/SimpleHash.java b/crypto/hash/src/main/java/org/apache/shiro/crypto/hash/SimpleHash.java index 8764117b78..4cba0f304d 100644 --- a/crypto/hash/src/main/java/org/apache/shiro/crypto/hash/SimpleHash.java +++ b/crypto/hash/src/main/java/org/apache/shiro/crypto/hash/SimpleHash.java @@ -29,6 +29,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.Serial; import java.io.Serializable; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -50,6 +51,7 @@ public class SimpleHash extends CodecSupport implements Hash, Serializable { private static final int DEFAULT_ITERATIONS = 1; + @Serial private static final long serialVersionUID = -6689895264902387303L; private static final Logger LOG = LoggerFactory.getLogger(SimpleHash.class); @@ -245,8 +247,8 @@ protected ByteSource convertSaltToBytes(Object salt) { * @since 1.2 */ protected ByteSource toByteSource(Object object) { - if (object instanceof ByteSource) { - return (ByteSource) object; + if (object instanceof ByteSource source) { + return source; } byte[] bytes = toBytes(object); return ByteSource.Util.bytes(bytes); @@ -460,8 +462,7 @@ public String toString() { */ @Override public boolean equals(Object o) { - if (o instanceof Hash) { - Hash other = (Hash) o; + if (o instanceof Hash other) { return MessageDigest.isEqual(getBytes(), other.getBytes()); } return false; diff --git a/crypto/support/hashes/argon2/src/main/java/org/apache/shiro/crypto/support/hashes/argon2/Argon2Hash.java b/crypto/support/hashes/argon2/src/main/java/org/apache/shiro/crypto/support/hashes/argon2/Argon2Hash.java index ce786916b4..0108450390 100644 --- a/crypto/support/hashes/argon2/src/main/java/org/apache/shiro/crypto/support/hashes/argon2/Argon2Hash.java +++ b/crypto/support/hashes/argon2/src/main/java/org/apache/shiro/crypto/support/hashes/argon2/Argon2Hash.java @@ -28,6 +28,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.Serial; import java.security.SecureRandom; import java.util.Arrays; import java.util.Base64.Encoder; @@ -86,6 +87,7 @@ class Argon2Hash extends AbstractCryptHash { */ public static final int DEFAULT_MEMORY_KIB = 64 * 1024; + @Serial private static final long serialVersionUID = 2647354947284558921L; private static final Logger LOG = LoggerFactory.getLogger(Argon2Hash.class); diff --git a/crypto/support/hashes/bcrypt/src/main/java/org/apache/shiro/crypto/support/hashes/bcrypt/BCryptHash.java b/crypto/support/hashes/bcrypt/src/main/java/org/apache/shiro/crypto/support/hashes/bcrypt/BCryptHash.java index febe8ae999..e4a341965f 100644 --- a/crypto/support/hashes/bcrypt/src/main/java/org/apache/shiro/crypto/support/hashes/bcrypt/BCryptHash.java +++ b/crypto/support/hashes/bcrypt/src/main/java/org/apache/shiro/crypto/support/hashes/bcrypt/BCryptHash.java @@ -27,6 +27,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.Serial; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.Arrays; @@ -48,6 +49,7 @@ class BCryptHash extends AbstractCryptHash { public static final int SALT_LENGTH = 16; + @Serial private static final long serialVersionUID = 6957869292324606101L; private static final Logger LOG = LoggerFactory.getLogger(AbstractCryptHash.class); diff --git a/crypto/support/hashes/bcrypt/src/main/java/org/apache/shiro/crypto/support/hashes/bcrypt/BCryptProvider.java b/crypto/support/hashes/bcrypt/src/main/java/org/apache/shiro/crypto/support/hashes/bcrypt/BCryptProvider.java index 6a31c432d8..3b87b62401 100644 --- a/crypto/support/hashes/bcrypt/src/main/java/org/apache/shiro/crypto/support/hashes/bcrypt/BCryptProvider.java +++ b/crypto/support/hashes/bcrypt/src/main/java/org/apache/shiro/crypto/support/hashes/bcrypt/BCryptProvider.java @@ -90,7 +90,7 @@ private int getCost(HashRequest hashRequest) { final Optional optCostStr = Optional.ofNullable(parameters.get(Parameters.PARAMETER_COST)) .map(obj -> (String) obj); - if (!optCostStr.isPresent()) { + if (optCostStr.isEmpty()) { return BCryptHash.DEFAULT_COST; } @@ -117,7 +117,7 @@ private ByteSource getSalt(HashRequest hashRequest) { final Optional optSaltBase64 = Optional.ofNullable(parameters.get(Parameters.PARAMETER_SALT)) .map(obj -> (String) obj); - if (!optSaltBase64.isPresent()) { + if (optSaltBase64.isEmpty()) { return BCryptHash.createSalt(random); } diff --git a/event/src/main/java/org/apache/shiro/event/support/DefaultEventBus.java b/event/src/main/java/org/apache/shiro/event/support/DefaultEventBus.java index b4f62459bf..4a7e6c66f7 100644 --- a/event/src/main/java/org/apache/shiro/event/support/DefaultEventBus.java +++ b/event/src/main/java/org/apache/shiro/event/support/DefaultEventBus.java @@ -201,8 +201,7 @@ public void onEvent(Object event) { for (EventListener listener : this.listeners) { Object target = listener; - if (listener instanceof SingleArgumentMethodEventListener) { - SingleArgumentMethodEventListener singleArgListener = (SingleArgumentMethodEventListener) listener; + if (listener instanceof SingleArgumentMethodEventListener singleArgListener) { target = singleArgListener.getTarget(); } if (listener.accepts(event) && !delivered.contains(target)) { diff --git a/event/src/main/java/org/apache/shiro/event/support/EventListenerComparator.java b/event/src/main/java/org/apache/shiro/event/support/EventListenerComparator.java index 06e15ddaee..a9a5c616a2 100644 --- a/event/src/main/java/org/apache/shiro/event/support/EventListenerComparator.java +++ b/event/src/main/java/org/apache/shiro/event/support/EventListenerComparator.java @@ -51,10 +51,8 @@ public int compare(EventListener a, EventListener b) { } else if (a == b || a.equals(b)) { return 0; } else { - if (a instanceof TypedEventListener) { - TypedEventListener ta = (TypedEventListener) a; - if (b instanceof TypedEventListener) { - TypedEventListener tb = (TypedEventListener) b; + if (a instanceof TypedEventListener ta) { + if (b instanceof TypedEventListener tb) { return EVENT_CLASS_COMPARATOR.compare(ta.getEventType(), tb.getEventType()); } else { //TypedEventListeners are 'less than' (higher priority) than non typed diff --git a/integration-tests/guice4/pom.xml b/integration-tests/guice/pom.xml similarity index 95% rename from integration-tests/guice4/pom.xml rename to integration-tests/guice/pom.xml index 8eacc33dee..e7dd785f55 100644 --- a/integration-tests/guice4/pom.xml +++ b/integration-tests/guice/pom.xml @@ -27,8 +27,8 @@ 999-SNAPSHOT - shiro-its-guice4 - Apache Shiro :: ITs :: Guice 4 + shiro-its-guice + Apache Shiro :: ITs :: Guice war @@ -38,8 +38,8 @@ - org.eclipse.jetty - jetty-maven-plugin + org.eclipse.jetty.ee11 + jetty-ee11-maven-plugin org.apache.maven.plugins @@ -68,7 +68,7 @@ jakarta.servlet jakarta.servlet-api provided - 6.1.0 + 6.1.0 org.apache.logging.log4j diff --git a/integration-tests/guice3/src/main/java/org/apache/shiro/samples/guice/SampleShiroGuiceBootstrap.java b/integration-tests/guice/src/main/java/org/apache/shiro/samples/guice/SampleShiroGuiceBootstrap.java similarity index 100% rename from integration-tests/guice3/src/main/java/org/apache/shiro/samples/guice/SampleShiroGuiceBootstrap.java rename to integration-tests/guice/src/main/java/org/apache/shiro/samples/guice/SampleShiroGuiceBootstrap.java diff --git a/integration-tests/guice4/src/main/java/org/apache/shiro/samples/guice/SampleShiroServletModule.java b/integration-tests/guice/src/main/java/org/apache/shiro/samples/guice/SampleShiroServletModule.java similarity index 100% rename from integration-tests/guice4/src/main/java/org/apache/shiro/samples/guice/SampleShiroServletModule.java rename to integration-tests/guice/src/main/java/org/apache/shiro/samples/guice/SampleShiroServletModule.java diff --git a/integration-tests/guice4/src/main/resources/log4j2.xml b/integration-tests/guice/src/main/resources/log4j2.xml similarity index 94% rename from integration-tests/guice4/src/main/resources/log4j2.xml rename to integration-tests/guice/src/main/resources/log4j2.xml index e0b3288f58..ac22c066c0 100644 --- a/integration-tests/guice4/src/main/resources/log4j2.xml +++ b/integration-tests/guice/src/main/resources/log4j2.xml @@ -49,7 +49,7 @@ - + @@ -58,7 +58,7 @@ - + diff --git a/integration-tests/guice3/src/main/webapp/WEB-INF/shiro.ini b/integration-tests/guice/src/main/webapp/WEB-INF/shiro.ini similarity index 100% rename from integration-tests/guice3/src/main/webapp/WEB-INF/shiro.ini rename to integration-tests/guice/src/main/webapp/WEB-INF/shiro.ini diff --git a/integration-tests/guice3/src/main/webapp/WEB-INF/web.xml b/integration-tests/guice/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from integration-tests/guice3/src/main/webapp/WEB-INF/web.xml rename to integration-tests/guice/src/main/webapp/WEB-INF/web.xml diff --git a/integration-tests/guice3/src/main/webapp/account/index.jsp b/integration-tests/guice/src/main/webapp/account/index.jsp similarity index 100% rename from integration-tests/guice3/src/main/webapp/account/index.jsp rename to integration-tests/guice/src/main/webapp/account/index.jsp diff --git a/integration-tests/guice3/src/main/webapp/home.jsp b/integration-tests/guice/src/main/webapp/home.jsp similarity index 100% rename from integration-tests/guice3/src/main/webapp/home.jsp rename to integration-tests/guice/src/main/webapp/home.jsp diff --git a/integration-tests/guice3/src/main/webapp/include.jsp b/integration-tests/guice/src/main/webapp/include.jsp similarity index 100% rename from integration-tests/guice3/src/main/webapp/include.jsp rename to integration-tests/guice/src/main/webapp/include.jsp diff --git a/integration-tests/guice3/src/main/webapp/index.jsp b/integration-tests/guice/src/main/webapp/index.jsp similarity index 100% rename from integration-tests/guice3/src/main/webapp/index.jsp rename to integration-tests/guice/src/main/webapp/index.jsp diff --git a/integration-tests/guice3/src/main/webapp/login.jsp b/integration-tests/guice/src/main/webapp/login.jsp similarity index 100% rename from integration-tests/guice3/src/main/webapp/login.jsp rename to integration-tests/guice/src/main/webapp/login.jsp diff --git a/integration-tests/guice3/src/main/webapp/style.css b/integration-tests/guice/src/main/webapp/style.css similarity index 100% rename from integration-tests/guice3/src/main/webapp/style.css rename to integration-tests/guice/src/main/webapp/style.css diff --git a/integration-tests/guice3/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java b/integration-tests/guice/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java similarity index 100% rename from integration-tests/guice3/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java rename to integration-tests/guice/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java diff --git a/integration-tests/guice3/pom.xml b/integration-tests/guice3/pom.xml deleted file mode 100644 index 075e1d59af..0000000000 --- a/integration-tests/guice3/pom.xml +++ /dev/null @@ -1,142 +0,0 @@ - - - - 4.0.0 - - - org.apache.shiro.integrationtests - shiro-integration-tests - 999-SNAPSHOT - - - shiro-its-guice3 - Apache Shiro :: ITs :: Guice 3 - war - - - 4.2.3 - - - - - - org.eclipse.jetty - jetty-maven-plugin - - - - - - - org.apache.taglibs - taglibs-standard-spec - compile - - - org.apache.taglibs - taglibs-standard-impl - compile - - - jakarta.servlet - jakarta.servlet-api - provided - 6.1.0 - - - org.apache.logging.log4j - log4j-slf4j2-impl - runtime - - - org.apache.logging.log4j - log4j-core - runtime - - - org.apache.shiro - shiro-core - - - org.apache.shiro - shiro-web - - - org.apache.shiro - shiro-guice - - - com.google.inject.extensions - guice-servlet - - - org.slf4j - jcl-over-slf4j - runtime - - - - org.apache.shiro - shiro-guice - ${project.version} - tests - test-jar - test - - - org.htmlunit - htmlunit - test - - - org.eclipse.jetty.ee9 - jetty-ee9-apache-jsp - ${jetty.version} - test - - - org.eclipse.jetty - apache-jstl - ${jetty.version} - pom - test - - - org.apache.shiro.integrationtests - shiro-its-support - test - - - - - - jdk17 - - [17,) - - - - --add-opens java.base/java.lang=ALL-UNNAMED - --add-opens java.base/java.lang=ALL-UNNAMED - - - - diff --git a/integration-tests/guice3/src/main/java/org/apache/shiro/samples/guice/SampleShiroServletModule.java b/integration-tests/guice3/src/main/java/org/apache/shiro/samples/guice/SampleShiroServletModule.java deleted file mode 100644 index 007f9e472d..0000000000 --- a/integration-tests/guice3/src/main/java/org/apache/shiro/samples/guice/SampleShiroServletModule.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.shiro.samples.guice; - -import com.google.inject.Provides; -import com.google.inject.binder.AnnotatedBindingBuilder; -import com.google.inject.name.Names; -import org.apache.shiro.lang.codec.Base64; -import org.apache.shiro.config.ConfigurationException; -import org.apache.shiro.config.Ini; -import org.apache.shiro.guice.web.ShiroWebModule; -import org.apache.shiro.realm.text.IniRealm; -import org.apache.shiro.web.mgt.CookieRememberMeManager; -import org.apache.shiro.web.mgt.DefaultWebSecurityManager; -import org.apache.shiro.web.mgt.WebSecurityManager; - -import jakarta.inject.Singleton; -import jakarta.servlet.ServletContext; -import java.net.MalformedURLException; -import java.net.URL; - -public class SampleShiroServletModule extends ShiroWebModule { - private final ServletContext servletContext; - - public SampleShiroServletModule(ServletContext servletContext) { - super(servletContext); - - this.servletContext = servletContext; - } - - @Override - @SuppressWarnings({"unchecked", "deprecation"}) - protected void configureShiroWeb() { - bindConstant().annotatedWith(Names.named("shiro.loginUrl")).to("/login.jsp"); - try { - this.bindRealm().toConstructor(IniRealm.class.getConstructor(Ini.class)); - } catch (NoSuchMethodException e) { - addError("Could not locate proper constructor for IniRealm.", e); - } - - this.addFilterChain("/login.jsp", AUTHC); - this.addFilterChain("/logout", LOGOUT); - this.addFilterChain("/account/**", AUTHC); - - this.addFilterChain("/remoting/**", AUTHC, config(ROLES, "b2bClient"), config(PERMS, "remote:invoke:lan,wan")); - } - - @Provides - @Singleton - Ini loadShiroIni() throws MalformedURLException { - URL iniUrl = servletContext.getResource("/WEB-INF/shiro.ini"); - return Ini.fromResourcePath("url:" + iniUrl.toExternalForm()); - } - - @Override - protected void bindWebSecurityManager(AnnotatedBindingBuilder bind) { - try { - String cipherKey = loadShiroIni().getSectionProperty("main", "securityManager.rememberMeManager.cipherKey"); - - DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); - CookieRememberMeManager rememberMeManager = new CookieRememberMeManager(); - rememberMeManager.setCipherKey(Base64.decode(cipherKey)); - securityManager.setRememberMeManager(rememberMeManager); - bind.toInstance(securityManager); - } catch (MalformedURLException e) { - // for now just throw, you could just call - // super.bindWebSecurityManager(bind) if you do not need rememberMe functionality - throw new ConfigurationException("securityManager.rememberMeManager.cipherKey must be set in shiro.ini."); - } - - - } -} diff --git a/integration-tests/guice3/src/main/resources/log4j2.xml b/integration-tests/guice3/src/main/resources/log4j2.xml deleted file mode 100644 index 46fb635c9c..0000000000 --- a/integration-tests/guice3/src/main/resources/log4j2.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/integration-tests/guice4/src/main/java/org/apache/shiro/samples/guice/SampleShiroGuiceBootstrap.java b/integration-tests/guice4/src/main/java/org/apache/shiro/samples/guice/SampleShiroGuiceBootstrap.java deleted file mode 100644 index f884aefc06..0000000000 --- a/integration-tests/guice4/src/main/java/org/apache/shiro/samples/guice/SampleShiroGuiceBootstrap.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.shiro.samples.guice; - -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.servlet.GuiceServletContextListener; -import org.apache.shiro.guice.web.ShiroWebModule; - -import jakarta.servlet.ServletContext; -import jakarta.servlet.ServletContextEvent; - -public class SampleShiroGuiceBootstrap extends GuiceServletContextListener { - - private ServletContext servletContext; - - @Override - public void contextInitialized(final ServletContextEvent servletContextEvent) { - this.servletContext = servletContextEvent.getServletContext(); - super.contextInitialized(servletContextEvent); - } - - @Override - protected Injector getInjector() { - return Guice.createInjector(new SampleShiroServletModule(servletContext), ShiroWebModule.guiceFilterModule()); - } -} diff --git a/integration-tests/guice4/src/main/webapp/WEB-INF/shiro.ini b/integration-tests/guice4/src/main/webapp/WEB-INF/shiro.ini deleted file mode 100644 index 18bb0dff74..0000000000 --- a/integration-tests/guice4/src/main/webapp/WEB-INF/shiro.ini +++ /dev/null @@ -1,53 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -# INI configuration is very powerful and flexible, while still remaining succinct. -# Please https://shiro.apache.org/configuration.html and -# https://shiro.apache.org/web.html for more. - -[main] -shiro.loginUrl = /login.jsp - -# We need to set the cipherKey, if you want the rememberMe cookie to work after restarting or on multiple nodes. -# YOU MUST SET THIS TO A UNIQUE STRING -securityManager.rememberMeManager.cipherKey = kPH+bIxk5D2deZiIxcaaaA== - -[users] -# format: username = password, role1, role2, ..., roleN -root = secret,admin -guest = guest,guest -presidentskroob = 12345,president -darkhelmet = ludicrousspeed,darklord,schwartz -lonestarr = vespa,goodguy,schwartz - -[roles] -# format: roleName = permission1, permission2, ..., permissionN -admin = * -schwartz = lightsaber:* -goodguy = winnebago:drive:eagle5 - -[urls] -# The /login.jsp is not restricted to authenticated users (otherwise no one could log in!), but -# the 'authc' filter must still be specified for it so it can process that url's -# login submissions. It is 'smart' enough to allow those requests through as specified by the -# shiro.loginUrl above. -/login.jsp = authc -/logout = logout -/account/** = authc -/remoting/** = authc, roles[b2bClient], perms["remote:invoke:lan,wan"] diff --git a/integration-tests/guice4/src/main/webapp/WEB-INF/web.xml b/integration-tests/guice4/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 64681aec7d..0000000000 --- a/integration-tests/guice4/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - org.apache.shiro.samples.guice.SampleShiroGuiceBootstrap - - - - GuiceFilter - com.google.inject.servlet.GuiceFilter - - - - GuiceFilter - /* - - - - index.jsp - - - diff --git a/integration-tests/guice4/src/main/webapp/account/index.jsp b/integration-tests/guice4/src/main/webapp/account/index.jsp deleted file mode 100644 index 013b21a8b4..0000000000 --- a/integration-tests/guice4/src/main/webapp/account/index.jsp +++ /dev/null @@ -1,36 +0,0 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> -<%@ include file="../include.jsp" %> - - - - "/> - - - -

Users only

- -

You are currently logged in.

- -

">Return to the home page.

- -

">Log out.

- - - diff --git a/integration-tests/guice4/src/main/webapp/home.jsp b/integration-tests/guice4/src/main/webapp/home.jsp deleted file mode 100644 index 61dee2552a..0000000000 --- a/integration-tests/guice4/src/main/webapp/home.jsp +++ /dev/null @@ -1,69 +0,0 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> -<%@ include file="include.jsp" %> - - - - "/> - Apache Shiro Quickstart - - - -

Apache Shiro Quickstart

- -

Hi Guest! - ( ">Log out - ">Log in (sample accounts provided) ) -

- -

Welcome to the Apache Shiro Quickstart sample application. - This page represents the home page of any web application.

- -

Visit your ">account page.

-

If you want to access the user-only ">account page, - you will need to log-in first.

- -

Roles

- -

To show some taglibs, here are the roles you have and don't have. Log out and log back in under different user - accounts to see different roles.

- -

Roles you have

- -

- admin
- president
- darklord
- goodguy
- schwartz
-

- -

Roles you DON'T have

- -

- admin
- president
- darklord
- goodguy
- schwartz
-

- - - - diff --git a/integration-tests/guice4/src/main/webapp/include.jsp b/integration-tests/guice4/src/main/webapp/include.jsp deleted file mode 100644 index 8472daca1e..0000000000 --- a/integration-tests/guice4/src/main/webapp/include.jsp +++ /dev/null @@ -1,22 +0,0 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> -<%@ page import="org.apache.shiro.SecurityUtils" %> -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %> diff --git a/integration-tests/guice4/src/main/webapp/index.jsp b/integration-tests/guice4/src/main/webapp/index.jsp deleted file mode 100644 index ec60ad16c0..0000000000 --- a/integration-tests/guice4/src/main/webapp/index.jsp +++ /dev/null @@ -1,21 +0,0 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%-- Forward the user to the home page --%> - diff --git a/integration-tests/guice4/src/main/webapp/login.jsp b/integration-tests/guice4/src/main/webapp/login.jsp deleted file mode 100644 index c80ee54c8a..0000000000 --- a/integration-tests/guice4/src/main/webapp/login.jsp +++ /dev/null @@ -1,110 +0,0 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> -<%@ include file="include.jsp" %> - - - - "/> - - - -

Please Log in

- - -

Here are a few sample accounts to play with in the default text-based Realm (used for this - demo and test installs only). Do you remember the movie these names came from? ;)

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
UsernamePassword
rootsecret
presidentskroob12345
darkhelmetludicrousspeed
lonestarrvespa
-

-
- -
- - - - - - - - - - - - - - - -
Username:
Password:
Remember Me
-
- - - diff --git a/integration-tests/guice4/src/main/webapp/style.css b/integration-tests/guice4/src/main/webapp/style.css deleted file mode 100644 index c3e3944cfa..0000000000 --- a/integration-tests/guice4/src/main/webapp/style.css +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -body { - margin: 15px 0 0 15px; - padding: 1px; /*background: #2370cf;*/ - font: 12px 'Lucida Grande', Geneva, Verdana, Arial, sans-serif; - color: #000; -} - -table, td { - font: 12px 'Lucida Grande', Geneva, Verdana, Arial, sans-serif; - color: #000; -} - -h1 { - font: 24px; -} - -img { - border: thin black solid; -} - -#contentBox { - text-align: center; - width: 50%; - margin: auto; - margin-top: 50px; - color: black; - background: #eee; - border: thick black solid; -} diff --git a/integration-tests/guice4/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java b/integration-tests/guice4/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java deleted file mode 100644 index 550b9e2298..0000000000 --- a/integration-tests/guice4/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.shiro.samples.guice; - -import org.apache.shiro.testing.web.AbstractContainerIT; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.htmlunit.ElementNotFoundException; -import org.htmlunit.FailingHttpStatusCodeException; -import org.htmlunit.WebAssert; -import org.htmlunit.html.HtmlCheckBoxInput; -import org.htmlunit.html.HtmlForm; -import org.htmlunit.html.HtmlPage; - -import java.io.IOException; -import java.net.MalformedURLException; - -public class ContainerIntegrationIT extends AbstractContainerIT { - - @BeforeEach - public void logOut() throws IOException { - // Make sure we are logged out - final HtmlPage homePage = webClient.getPage(getBaseUri()); - try { - homePage.getAnchorByHref("/logout").click(); - } catch (ElementNotFoundException e) { - //Ignore - } - } - - @Test - void logIn() throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException { - - HtmlPage page = webClient.getPage(getBaseUri() + "login.jsp"); - HtmlForm form = page.getFormByName("loginform"); - form.getInputByName("username").setValueAttribute("root"); - form.getInputByName("password").setValueAttribute("secret"); - page = form.getInputByName("submit").click(); - // This'll throw an exception if not logged in - page.getAnchorByHref("/logout"); - } - - @Test - void logInAndRememberMe() throws Exception { - HtmlPage page = webClient.getPage(getBaseUri() + "login.jsp"); - HtmlForm form = page.getFormByName("loginform"); - form.getInputByName("username").setValueAttribute("root"); - form.getInputByName("password").setValueAttribute("secret"); - HtmlCheckBoxInput checkbox = form.getInputByName("rememberMe"); - checkbox.setChecked(true); - page = form.getInputByName("submit").click(); - jetty.stop(); - jetty.start(); - page = webClient.getPage(getBaseUri()); - // page.getAnchorByHref("/logout"); - WebAssert.assertLinkPresentWithText(page, "Log out"); - page = page.getAnchorByHref("/account").click(); - // login page should be shown again - user remembered but not authenticated - WebAssert.assertFormPresent(page, "loginform"); - } - -} diff --git a/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/PropertyPrincipal.java b/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/PropertyPrincipal.java index fdbed033c3..1cbc047d7c 100644 --- a/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/PropertyPrincipal.java +++ b/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/PropertyPrincipal.java @@ -13,6 +13,7 @@ */ package org.apache.shiro.testing.jakarta.ee; +import java.io.Serial; import java.io.Serializable; import jakarta.enterprise.inject.Vetoed; @@ -23,6 +24,7 @@ @AllArgsConstructor @Vetoed public class PropertyPrincipal implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final String userName; diff --git a/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/ProtectedFacesViewScopedBean.java b/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/ProtectedFacesViewScopedBean.java index a448557095..82bf1838f4 100644 --- a/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/ProtectedFacesViewScopedBean.java +++ b/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/ProtectedFacesViewScopedBean.java @@ -15,6 +15,7 @@ import static org.apache.shiro.testing.jakarta.ee.StatisticsResource.increment; +import java.io.Serial; import java.io.Serializable; import java.util.concurrent.atomic.AtomicInteger; import jakarta.annotation.PostConstruct; @@ -34,6 +35,7 @@ @RequiresUser @Slf4j public class ProtectedFacesViewScopedBean implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger(); @@ -50,7 +52,7 @@ void preDestroy() { } public String hello() { - return String.format("Hello from FacesViewScoped %s - %s", count, + return "Hello from FacesViewScoped %s - %s".formatted(count, FacesContext.class.getPackage().getImplementationVersion()); } } diff --git a/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/ProtectedOmniViewScopedBean.java b/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/ProtectedOmniViewScopedBean.java index db5deaae73..c8720a1f5b 100644 --- a/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/ProtectedOmniViewScopedBean.java +++ b/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/ProtectedOmniViewScopedBean.java @@ -15,6 +15,7 @@ import static org.apache.shiro.testing.jakarta.ee.StatisticsResource.increment; +import java.io.Serial; import java.io.Serializable; import java.util.concurrent.atomic.AtomicInteger; import jakarta.annotation.PostConstruct; @@ -34,6 +35,7 @@ @RequiresUser @Slf4j public class ProtectedOmniViewScopedBean implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger(); @@ -50,7 +52,7 @@ void preDestroy() { } public String hello() { - return String.format("Hello from OmniViewScoped %s - %s", count, + return "Hello from OmniViewScoped %s - %s".formatted(count, FacesContext.class.getPackage().getImplementationVersion()); } } diff --git a/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/ProtectedSessionScopedBean.java b/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/ProtectedSessionScopedBean.java index ce3ac2d4da..d35df25b73 100644 --- a/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/ProtectedSessionScopedBean.java +++ b/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/ProtectedSessionScopedBean.java @@ -15,6 +15,7 @@ import static org.apache.shiro.testing.jakarta.ee.StatisticsResource.increment; +import java.io.Serial; import java.io.Serializable; import java.util.concurrent.atomic.AtomicInteger; import jakarta.annotation.PostConstruct; @@ -33,6 +34,7 @@ @RequiresUser @Slf4j public class ProtectedSessionScopedBean implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger(); @@ -49,6 +51,6 @@ void preDestroy() { } public String hello() { - return String.format("Hello from SessionScoped %s", count); + return "Hello from SessionScoped %s".formatted(count); } } diff --git a/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/servlets/ExceptionServlet.java b/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/servlets/ExceptionServlet.java index a0d2cc6236..77476b6d49 100644 --- a/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/servlets/ExceptionServlet.java +++ b/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jakarta/ee/servlets/ExceptionServlet.java @@ -17,6 +17,7 @@ import java.io.IOException; import java.io.PrintWriter; +import java.io.Serial; import java.nio.charset.StandardCharsets; import java.util.logging.LogRecord; import jakarta.servlet.ServletException; @@ -32,6 +33,7 @@ */ @WebServlet("/lastException") public class ExceptionServlet extends HttpServlet { + @Serial private static final long serialVersionUID = 1L; @Override diff --git a/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jaxrs/JsonPojo.java b/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jaxrs/JsonPojo.java index d68df31408..aa46f9afdf 100644 --- a/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jaxrs/JsonPojo.java +++ b/integration-tests/jakarta-ee/src/main/java/org/apache/shiro/testing/jaxrs/JsonPojo.java @@ -13,6 +13,7 @@ */ package org.apache.shiro.testing.jaxrs; +import java.io.Serial; import java.io.Serializable; import lombok.AllArgsConstructor; @@ -27,6 +28,7 @@ @NoArgsConstructor @AllArgsConstructor public class JsonPojo implements Serializable { + @Serial private static final long serialVersionUID = 1L; private String userId; diff --git a/integration-tests/jakarta-ee/src/test/java/org/apache/shiro/testing/cdi/ComponentInjectionIT.java b/integration-tests/jakarta-ee/src/test/java/org/apache/shiro/testing/cdi/ComponentInjectionIT.java index 2bd7a0eff1..7b0d8a0acb 100644 --- a/integration-tests/jakarta-ee/src/test/java/org/apache/shiro/testing/cdi/ComponentInjectionIT.java +++ b/integration-tests/jakarta-ee/src/test/java/org/apache/shiro/testing/cdi/ComponentInjectionIT.java @@ -19,7 +19,6 @@ import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; -import static org.apache.shiro.ee.util.JakartaTransformer.jakartify; import static org.assertj.core.api.Assertions.assertThat; import org.apache.shiro.testing.jakarta.ee.PropertyPrincipal; @@ -119,7 +118,7 @@ public static WebArchive createDeployment(String archive) { var webArchive = ShrinkWrap.create(WebArchive.class, archive) .addAsResource("META-INF/beans.xml") .addAsResource(new StringAsset("org.apache.shiro.cdi.ShiroSecurityExtension"), - jakartify("META-INF/services/javax.enterprise.inject.spi.Extension")) + "META-INF/services/jakarta.enterprise.inject.spi.Extension") .addAsResource("META-INF/services/org.slf4j.spi.SLF4JServiceProvider") .addAsWebInfResource(new StringAsset( ""), diff --git a/integration-tests/jakarta-ee/src/test/java/org/apache/shiro/testing/jakarta/ee/Deployments.java b/integration-tests/jakarta-ee/src/test/java/org/apache/shiro/testing/jakarta/ee/Deployments.java index 44cd895ebd..e48253ad54 100644 --- a/integration-tests/jakarta-ee/src/test/java/org/apache/shiro/testing/jakarta/ee/Deployments.java +++ b/integration-tests/jakarta-ee/src/test/java/org/apache/shiro/testing/jakarta/ee/Deployments.java @@ -20,7 +20,6 @@ import org.apache.shiro.testing.cdi.ComponentInjectionIT; -import static org.apache.shiro.ee.util.JakartaTransformer.jakartify; import static org.apache.shiro.testing.cdi.ComponentInjectionIT.TESTABLE_MODE; import static org.apache.shiro.testing.jakarta.ee.ShiroAuthFormsIT.DEPLOYMENT_DEV_MODE; import static org.apache.shiro.testing.jakarta.ee.ShiroAuthFormsIT.DEPLOYMENT_PROD_MODE; diff --git a/integration-tests/jakarta-ee/src/test/java/org/apache/shiro/testing/jakarta/ee/ShiroAuthFormsIT.java b/integration-tests/jakarta-ee/src/test/java/org/apache/shiro/testing/jakarta/ee/ShiroAuthFormsIT.java index 97db75a45f..a8e9c63cbd 100644 --- a/integration-tests/jakarta-ee/src/test/java/org/apache/shiro/testing/jakarta/ee/ShiroAuthFormsIT.java +++ b/integration-tests/jakarta-ee/src/test/java/org/apache/shiro/testing/jakarta/ee/ShiroAuthFormsIT.java @@ -26,7 +26,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static org.apache.shiro.ee.util.JakartaTransformer.jakartify; import static org.apache.shiro.web.servlet.ShiroHttpSession.DEFAULT_SESSION_ID_NAME; import static org.assertj.core.api.Assertions.assertThat; @@ -373,7 +372,7 @@ static WebArchive createDeploymentProd(String archiveName) { .as(WebArchive.class) .deletePackage("org.apache.shiro.testing.jaxrs"); var productionList = List.of(new Action( - getContextParamValue(jakartify("jakarta.faces.PROJECT_STAGE")), + getContextParamValue("jakarta.faces.PROJECT_STAGE"), node -> node.setTextContent("Production"))); new ShrinkWrapManipulator().webXmlXPath(archive, Stream.concat(productionList.stream(), standardActions.stream()).collect(Collectors.toList())); diff --git a/integration-tests/jakarta-ee/src/test/java/org/apache/shiro/testing/jakarta/ee/ShiroBeansIT.java b/integration-tests/jakarta-ee/src/test/java/org/apache/shiro/testing/jakarta/ee/ShiroBeansIT.java index 4581a34324..54a3e22eba 100644 --- a/integration-tests/jakarta-ee/src/test/java/org/apache/shiro/testing/jakarta/ee/ShiroBeansIT.java +++ b/integration-tests/jakarta-ee/src/test/java/org/apache/shiro/testing/jakarta/ee/ShiroBeansIT.java @@ -15,8 +15,6 @@ import java.net.URL; -import static org.apache.shiro.ee.util.JakartaTransformer.isJakarta; -import static org.apache.shiro.ee.util.JakartaTransformer.jakartify; import static org.apache.shiro.testing.jakarta.ee.ShiroAuthFormsIT.DEPLOYMENT_DEV_MODE; import static org.assertj.core.api.Assertions.assertThat; @@ -116,7 +114,7 @@ void checkDontCallWhenNotAuth() { webDriver.get(baseURL + "lastException"); String exceptionText = webDriver.findElement(By.tagName("body")).getText(); assertThat(exceptionText).startsWith( - jakartify("WARNING: javax.ejb.EJBException: Attempting to perform a user-only operation")); + "WARNING: jakarta.ejb.EJBException: Attempting to perform a user-only operation"); } @Test @@ -141,13 +139,12 @@ void checkCallWhenAuth() { @Test @OperateOnDeployment(DEPLOYMENT_DEV_MODE) void beanDestroyCalled() { - exerciseViewAndSessionScoped(facesViewScoped, "api/statistics/pc_fv", "api/statistics/pd_fv", !isJakarta()); + exerciseViewAndSessionScoped(facesViewScoped, "api/statistics/pc_fv", "api/statistics/pd_fv"); webDriver.get(baseURL + "api/statistics/clear"); - exerciseViewAndSessionScoped(omniViewScoped, "api/statistics/pc_ofv", "api/statistics/pd_ofv", false); + exerciseViewAndSessionScoped(omniViewScoped, "api/statistics/pc_ofv", "api/statistics/pd_ofv"); } - private void exerciseViewAndSessionScoped(WebElement elem, String createStatistic, String destroyStatistic, - boolean isBrokenDestructor) { + private void exerciseViewAndSessionScoped(WebElement elem, String createStatistic, String destroyStatistic) { webDriver.get(baseURL + "shiro/auth/loginform"); login(); @@ -164,7 +161,7 @@ private void exerciseViewAndSessionScoped(WebElement elem, String createStatisti webDriver.get(baseURL + createStatistic); assertThat(webDriver.findElement(By.tagName("body")).getText()).isEqualTo("2"); webDriver.get(baseURL + destroyStatistic); - assertThat(webDriver.findElement(By.tagName("body")).getText()).isEqualTo(isBrokenDestructor && webSessions ? "1" : "2"); + assertThat(webDriver.findElement(By.tagName("body")).getText()).isEqualTo("2"); webDriver.get(baseURL + "api/statistics/pc_ss"); assertThat(webDriver.findElement(By.tagName("body")).getText()).isEqualTo("1"); webDriver.get(baseURL + "api/statistics/pd_ss"); diff --git a/integration-tests/jaxrs/openliberty/pom.xml b/integration-tests/jaxrs/openliberty/pom.xml index 69f034aeb6..c53e3669a7 100644 --- a/integration-tests/jaxrs/openliberty/pom.xml +++ b/integration-tests/jaxrs/openliberty/pom.xml @@ -65,10 +65,10 @@ shiro-its-jaxrs-openliberty true - jaxrs-2.1 - servlet-4.0 - cdi-2.0 - jsonb-1.0 + restfulWS-3.1 + cdi-4.0 + servlet-6.0 + jsonb-3.0 dependencies false diff --git a/integration-tests/jaxrs/openliberty/src/main/liberty/config/server.xml b/integration-tests/jaxrs/openliberty/src/main/liberty/config/server.xml index 7bf5ef9e49..c012e3aa22 100644 --- a/integration-tests/jaxrs/openliberty/src/main/liberty/config/server.xml +++ b/integration-tests/jaxrs/openliberty/src/main/liberty/config/server.xml @@ -22,10 +22,10 @@ - jaxrs-2.1 - cdi-2.0 - servlet-4.0 - jsonb-1.0 + restfulWS-3.1 + cdi-4.0 + servlet-6.0 + jsonb-3.0 diff --git a/integration-tests/jaxrs/tests/pom.xml b/integration-tests/jaxrs/tests/pom.xml index 15fc90a701..30b7704fae 100644 --- a/integration-tests/jaxrs/tests/pom.xml +++ b/integration-tests/jaxrs/tests/pom.xml @@ -52,9 +52,9 @@ provided - javax.json.bind - javax.json.bind-api - 1.0 + jakarta.json.bind + jakarta.json.bind-api + 3.0.1 compile diff --git a/integration-tests/pom.xml b/integration-tests/pom.xml index 889018ac14..5ef25c4824 100644 --- a/integration-tests/pom.xml +++ b/integration-tests/pom.xml @@ -63,8 +63,7 @@ deferred-for-3x support - guice3 - guice4 + guice jakarta-ee diff --git a/integration-tests/support/src/main/java/org/apache/shiro/testing/web/AbstractContainerIT.java b/integration-tests/support/src/main/java/org/apache/shiro/testing/web/AbstractContainerIT.java index 9b77a88822..c9fe76efce 100644 --- a/integration-tests/support/src/main/java/org/apache/shiro/testing/web/AbstractContainerIT.java +++ b/integration-tests/support/src/main/java/org/apache/shiro/testing/web/AbstractContainerIT.java @@ -18,11 +18,11 @@ */ package org.apache.shiro.testing.web; -import org.apache.shiro.lang.codec.Base64; +import java.nio.charset.StandardCharsets; -import com.github.mjeanroy.junit.servers.jetty9.EmbeddedJetty; +import com.github.mjeanroy.junit.servers.jetty12.EmbeddedJetty; import com.github.mjeanroy.junit.servers.jetty.EmbeddedJettyConfiguration; -import org.eclipse.jetty.annotations.AnnotationConfiguration; +import java.util.Base64; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; @@ -30,15 +30,7 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; -import org.eclipse.jetty.util.resource.PathResource; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.eclipse.jetty.webapp.Configuration; -import org.eclipse.jetty.webapp.FragmentConfiguration; -import org.eclipse.jetty.webapp.JettyWebXmlConfiguration; -import org.eclipse.jetty.webapp.MetaInfConfiguration; -import org.eclipse.jetty.webapp.WebAppContext; -import org.eclipse.jetty.webapp.WebInfConfiguration; -import org.eclipse.jetty.webapp.WebXmlConfiguration; import org.htmlunit.WebClient; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -47,14 +39,12 @@ import java.io.File; import java.io.FilenameFilter; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.ServerSocket; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; -import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") @@ -77,64 +67,14 @@ public static void startContainer() throws Exception { .withWebapp(getWarDir()) .build(); - jetty = new EmbeddedJetty(config) { - - /** - * Overriding with contents of this pull request, to make fragment scanning work. - * - */ - @SuppressWarnings("checkstyle:LineLength") - protected WebAppContext createdWebAppContext() throws Exception { - final String path = configuration.getPath(); - final String webapp = configuration.getWebapp(); - final String classpath = configuration.getClasspath(); - - WebAppContext ctx = new WebAppContext(); - ctx.setClassLoader(Thread.currentThread().getContextClassLoader()); - ctx.setContextPath(path); - - // Useful for WebXmlConfiguration - ctx.setBaseResource(newResource(ctx, webapp)); - - ctx.setConfigurations(new Configuration[] { - new WebInfConfiguration(), - new WebXmlConfiguration(), - new AnnotationConfiguration(), - new JettyWebXmlConfiguration(), - new MetaInfConfiguration(), - new FragmentConfiguration(), - }); - - if (isNotBlank(classpath)) { - // Fix to scan Spring WebApplicationInitializer - // This will add compiled classes to jetty classpath - // See: http://stackoverflow.com/questions/13222071/spring-3-1-webapplicationinitializer-embedded-jetty-8-annotationconfiguration - // And more precisely: http://stackoverflow.com/a/18449506/1215828 - File classes = new File(classpath); - var containerResources = new PathResource(classes.toURI()); - ctx.getMetaData().addContainerResource(containerResources); - } - - Server server = getDelegate(); - - // web app - ctx.setParentLoaderPriority(true); - ctx.setWar(webapp); - ctx.setServer(server); - - // Add server context - server.setHandler(ctx); - - return ctx; - } - }; + jetty = new EmbeddedJetty(config); Server server = jetty.getDelegate(); // TLS tlsPort = getFreePort(); - final SslContextFactory sslContextFactory = new SslContextFactory.Server(); + final SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(TEST_KEYSTORE_PATH.getAbsolutePath()); sslContextFactory.setKeyStorePassword(TEST_KEYSTORE_PASSWORD); sslContextFactory.setKeyManagerPassword(TEST_KEYSTORE_PASSWORD); @@ -178,12 +118,11 @@ public boolean accept(File dir, String name) { return warFiles[0].getAbsolutePath().replaceFirst("\\.war$", ""); } - protected static String getBasicAuthorizationHeaderValue(String username, String password) - throws UnsupportedEncodingException { + protected static String getBasicAuthorizationHeaderValue(String username, String password) { String authorizationHeader = username + ":" + password; byte[] valueBytes; - valueBytes = authorizationHeader.getBytes("UTF-8"); - authorizationHeader = new String(Base64.encode(valueBytes)); + valueBytes = authorizationHeader.getBytes(StandardCharsets.UTF_8); + authorizationHeader = new String(Base64.getEncoder().encode(valueBytes)); return "Basic " + authorizationHeader; } diff --git a/lang/pom.xml b/lang/pom.xml index d015f3fb11..71d3bf1ec9 100644 --- a/lang/pom.xml +++ b/lang/pom.xml @@ -74,9 +74,9 @@ org.apache.shiro.lang org.apache.shiro.lang.*;version=${project.version} - + - javax.servlet.jsp*;resolution:=optional, + jakarta.servlet.jsp*;resolution:=optional, * <_removeheaders>Bnd-LastModified diff --git a/lang/src/main/java/org/apache/shiro/lang/codec/CodecSupport.java b/lang/src/main/java/org/apache/shiro/lang/codec/CodecSupport.java index becf3ce9c0..31c9c6de78 100644 --- a/lang/src/main/java/org/apache/shiro/lang/codec/CodecSupport.java +++ b/lang/src/main/java/org/apache/shiro/lang/codec/CodecSupport.java @@ -204,18 +204,18 @@ protected byte[] toBytes(Object object) { String msg = "Argument for byte conversion cannot be null."; throw new IllegalArgumentException(msg); } - if (object instanceof byte[]) { - return (byte[]) object; - } else if (object instanceof ByteSource) { - return ((ByteSource) object).getBytes(); - } else if (object instanceof char[]) { - return toBytes((char[]) object); - } else if (object instanceof String) { - return toBytes((String) object); - } else if (object instanceof File) { - return toBytes((File) object); - } else if (object instanceof InputStream) { - return toBytes((InputStream) object); + if (object instanceof byte[] bytes) { + return bytes; + } else if (object instanceof ByteSource source) { + return source.getBytes(); + } else if (object instanceof char[] chars) { + return toBytes(chars); + } else if (object instanceof String string) { + return toBytes(string); + } else if (object instanceof File file) { + return toBytes(file); + } else if (object instanceof InputStream stream) { + return toBytes(stream); } else { return objectToBytes(object); } @@ -238,12 +238,12 @@ protected String toString(Object o) { String msg = "Argument for String conversion cannot be null."; throw new IllegalArgumentException(msg); } - if (o instanceof byte[]) { - return toString((byte[]) o); - } else if (o instanceof char[]) { - return new String((char[]) o); - } else if (o instanceof String) { - return (String) o; + if (o instanceof byte[] bytes) { + return toString(bytes); + } else if (o instanceof char[] chars) { + return new String(chars); + } else if (o instanceof String string) { + return string; } else { return objectToString(o); } diff --git a/lang/src/main/java/org/apache/shiro/lang/io/ResourceUtils.java b/lang/src/main/java/org/apache/shiro/lang/io/ResourceUtils.java index 85937e5a4f..b7c241cc1f 100644 --- a/lang/src/main/java/org/apache/shiro/lang/io/ResourceUtils.java +++ b/lang/src/main/java/org/apache/shiro/lang/io/ResourceUtils.java @@ -18,6 +18,7 @@ */ package org.apache.shiro.lang.io; +import java.net.URI; import org.apache.shiro.lang.util.ClassUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -120,43 +121,45 @@ public static boolean resourceExists(String resourcePath) { */ public static InputStream getInputStreamForPath(String resourcePath) throws IOException { - InputStream is; - if (resourcePath.startsWith(CLASSPATH_PREFIX)) { - is = loadFromClassPath(stripPrefix(resourcePath)); + URL url = getURLForPath(resourcePath); + if (url == null) { + throw new IOException("Resource [" + resourcePath + "] could not be found."); + } - } else if (resourcePath.startsWith(URL_PREFIX)) { - is = loadFromUrl(stripPrefix(resourcePath)); + return url.openStream(); + } - } else if (resourcePath.startsWith(FILE_PREFIX)) { - is = loadFromFile(stripPrefix(resourcePath)); + /** + * Returns the URL for the resource represented by the specified path, supporting scheme + * prefixes that direct how to acquire the input stream + * ({@link #CLASSPATH_PREFIX CLASSPATH_PREFIX}, + * {@link #URL_PREFIX URL_PREFIX}, or {@link #FILE_PREFIX FILE_PREFIX}). If the path is not prefixed by one + * of these schemes, the path is assumed to be a file-based path that can be loaded with a + * call to {@link URI#create(String)}. + * + * @param resourcePath the String path representing the resource to obtain. + * @return the URL for the specified resource. + * @throws IOException if there is a problem acquiring the resource at the specified path. + */ + public static URL getURLForPath(String resourcePath) throws IOException { + URL url; + if (resourcePath.startsWith(CLASSPATH_PREFIX)) { + url = ClassUtils.getResource(stripPrefix(resourcePath)); + } else if (resourcePath.startsWith(URL_PREFIX)) { + url = URI.create(stripPrefix(resourcePath)).toURL(); } else { - is = loadFromFile(resourcePath); + url = URI.create(resourcePath).toURL(); } - if (is == null) { - throw new IOException("Resource [" + resourcePath + "] could not be found."); + if (url == null) { + return null; } - return is; - } - - private static InputStream loadFromFile(String path) throws IOException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Opening file [" + path + "]..."); + // throw early if resource cannot be acquired + try (InputStream ignored = url.openStream()) { + return url; } - return new FileInputStream(path); - } - - private static InputStream loadFromUrl(String urlPath) throws IOException { - LOGGER.debug("Opening url {}", urlPath); - URL url = new URL(urlPath); - return url.openStream(); - } - - private static InputStream loadFromClassPath(String path) { - LOGGER.debug("Opening resource from class path [{}]", path); - return ClassUtils.getResourceAsStream(path); } private static String stripPrefix(String resourcePath) { diff --git a/lang/src/main/java/org/apache/shiro/lang/util/ByteSource.java b/lang/src/main/java/org/apache/shiro/lang/util/ByteSource.java index c75d074bee..12aabb491d 100644 --- a/lang/src/main/java/org/apache/shiro/lang/util/ByteSource.java +++ b/lang/src/main/java/org/apache/shiro/lang/util/ByteSource.java @@ -173,18 +173,18 @@ public static ByteSource bytes(Object source) throws IllegalArgumentException { + "want to write your own ByteSource implementation to extract its bytes explicitly."; throw new IllegalArgumentException(msg); } - if (source instanceof byte[]) { - return bytes((byte[]) source); - } else if (source instanceof ByteSource) { - return (ByteSource) source; - } else if (source instanceof char[]) { - return bytes((char[]) source); - } else if (source instanceof String) { - return bytes((String) source); - } else if (source instanceof File) { - return bytes((File) source); - } else if (source instanceof InputStream) { - return bytes((InputStream) source); + if (source instanceof byte[] bytes) { + return bytes(bytes); + } else if (source instanceof ByteSource byteSource) { + return byteSource; + } else if (source instanceof char[] chars) { + return bytes(chars); + } else if (source instanceof String string) { + return bytes(string); + } else if (source instanceof File file) { + return bytes(file); + } else if (source instanceof InputStream stream) { + return bytes(stream); } else { throw new IllegalStateException("Encountered unexpected byte source. This is a bug - please notify " + "the Shiro developer list asap (the isCompatible implementation does not reflect this " diff --git a/lang/src/main/java/org/apache/shiro/lang/util/ByteSourceWrapper.java b/lang/src/main/java/org/apache/shiro/lang/util/ByteSourceWrapper.java index bd9270e296..2e41d413a9 100644 --- a/lang/src/main/java/org/apache/shiro/lang/util/ByteSourceWrapper.java +++ b/lang/src/main/java/org/apache/shiro/lang/util/ByteSourceWrapper.java @@ -37,12 +37,10 @@ private ByteSourceWrapper(byte[] bytes) { * This method generically accepts byte array or ByteSource instance. */ public static ByteSourceWrapper wrap(Object value) { - if (value instanceof byte[]) { - byte[] bytes = (byte[]) value; - return new ByteSourceWrapper(bytes); - } else if (value instanceof ByteSource) { - byte[] bytes = ((ByteSource) value).getBytes(); + if (value instanceof byte[] bytes) { return new ByteSourceWrapper(bytes); + } else if (value instanceof ByteSource source) { + return new ByteSourceWrapper(source.getBytes()); } throw new IllegalArgumentException(); } diff --git a/lang/src/main/java/org/apache/shiro/lang/util/ByteUtils.java b/lang/src/main/java/org/apache/shiro/lang/util/ByteUtils.java index 97bc594c65..ff0558e3f9 100644 --- a/lang/src/main/java/org/apache/shiro/lang/util/ByteUtils.java +++ b/lang/src/main/java/org/apache/shiro/lang/util/ByteUtils.java @@ -30,11 +30,9 @@ private ByteUtils() { * @param value An array holding sensitive data */ public static void wipe(Object value) { - if (value instanceof byte[]) { - byte[] array = (byte[]) value; + if (value instanceof byte[] array) { Arrays.fill(array, (byte) 0); - } else if (value instanceof char[]) { - char[] array = (char[]) value; + } else if (value instanceof char[] array) { Arrays.fill(array, '\u0000'); } } diff --git a/lang/src/main/java/org/apache/shiro/lang/util/ClassUtils.java b/lang/src/main/java/org/apache/shiro/lang/util/ClassUtils.java index e7bba5f8d9..2a9b8243b9 100644 --- a/lang/src/main/java/org/apache/shiro/lang/util/ClassUtils.java +++ b/lang/src/main/java/org/apache/shiro/lang/util/ClassUtils.java @@ -18,6 +18,8 @@ */ package org.apache.shiro.lang.util; +import java.io.IOException; +import java.net.URL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -118,42 +120,66 @@ private ClassUtils() { * @param name the name of the resource to acquire from the classloader(s). * @return the InputStream of the resource found, or null if the resource cannot be found from any * of the three mentioned ClassLoaders. + * @see #getResource(String) * @since 0.9 */ public static InputStream getResourceAsStream(String name) { + URL url = getResource(name); + if (url == null) { + return null; + } - InputStream is = THREAD_CL_ACCESSOR.getResourceStream(name); + try { + return url.openStream(); + } catch (IOException e) { + return null; + } + } - if (is == null) { + /** + * Returns the specified resource by checking the current thread's + * {@link Thread#getContextClassLoader() context class loader}, then the + * current ClassLoader (ClassUtils.class.getClassLoader()), then the system/application + * ClassLoader (ClassLoader.getSystemClassLoader(), in that order, using + * {@link ClassLoader#getResource(String) getResource(name)}. + * + * @param name the name of the resource to acquire from the classloader(s). + * @return the URL of the resource found, or null if the resource cannot be found from any + * of the three mentioned ClassLoaders. + * @since 3.0 + */ + public static URL getResource(String name) { + URL url = THREAD_CL_ACCESSOR.getResource(name); + if (url == null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Resource [" + name + "] was not found via the thread context ClassLoader. Trying the " + "current ClassLoader..."); } - is = CLASS_LANG_CL_ACCESSOR.getResourceStream(name); + url = CLASS_LANG_CL_ACCESSOR.getResource(name); } - if (is == null) { + if (url == null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Resource [" + name + "] was not found via the org.apache.shiro.lang ClassLoader. Trying the " + "additionally set ClassLoader..."); } - is = ADDITIONAL_CL_ACCESSOR.getResourceStream(name); + url = ADDITIONAL_CL_ACCESSOR.getResource(name); } - if (is == null) { + if (url == null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Resource [" + name + "] was not found via the current class loader. Trying the " + "system/application ClassLoader..."); } - is = SYSTEM_CL_ACCESSOR.getResourceStream(name); + url = SYSTEM_CL_ACCESSOR.getResource(name); } - if (is == null && LOGGER.isTraceEnabled()) { + if (url == null && LOGGER.isTraceEnabled()) { LOGGER.trace("Resource [" + name + "] was not found via the thread context, current, or " + "system/application ClassLoaders. All heuristics have been exhausted. Returning null."); } - return is; + return url; } /** @@ -315,6 +341,8 @@ private interface ClassLoaderAccessor { Class loadClass(String fqcn); InputStream getResourceStream(String name); + + URL getResource(String name); } /** @@ -347,6 +375,15 @@ public InputStream getResourceStream(String name) { return is; } + public URL getResource(String name) { + URL url = null; + ClassLoader cl = getClassLoader(); + if (cl != null) { + url = cl.getResource(name); + } + return url; + } + protected final ClassLoader getClassLoader() { try { return doGetClassLoader(); diff --git a/lang/src/main/java/org/apache/shiro/lang/util/LifecycleUtils.java b/lang/src/main/java/org/apache/shiro/lang/util/LifecycleUtils.java index 2a57e32735..d1dde1eebb 100644 --- a/lang/src/main/java/org/apache/shiro/lang/util/LifecycleUtils.java +++ b/lang/src/main/java/org/apache/shiro/lang/util/LifecycleUtils.java @@ -36,8 +36,8 @@ public abstract class LifecycleUtils { private static final Logger LOGGER = LoggerFactory.getLogger(LifecycleUtils.class); public static void init(Object o) throws ShiroException { - if (o instanceof Initializable) { - init((Initializable) o); + if (o instanceof Initializable initializable) { + init(initializable); } } @@ -63,10 +63,10 @@ public static void init(Collection c) throws ShiroException { } public static void destroy(Object o) { - if (o instanceof Destroyable) { - destroy((Destroyable) o); - } else if (o instanceof Collection) { - destroy((Collection) o); + if (o instanceof Destroyable destroyable) { + destroy(destroyable); + } else if (o instanceof Collection collection) { + destroy(collection); } } diff --git a/lang/src/main/java/org/apache/shiro/lang/util/SimpleByteSource.java b/lang/src/main/java/org/apache/shiro/lang/util/SimpleByteSource.java index e7351d074e..7b84406c1e 100644 --- a/lang/src/main/java/org/apache/shiro/lang/util/SimpleByteSource.java +++ b/lang/src/main/java/org/apache/shiro/lang/util/SimpleByteSource.java @@ -179,8 +179,7 @@ public boolean equals(Object o) { if (o == this) { return true; } - if (o instanceof ByteSource) { - ByteSource bs = (ByteSource) o; + if (o instanceof ByteSource bs) { return Arrays.equals(getBytes(), bs.getBytes()); } return false; diff --git a/pom.xml b/pom.xml index a318e24713..7bc40a3994 100644 --- a/pom.xml +++ b/pom.xml @@ -82,7 +82,7 @@ nexus-staging - [2, 3) + [3, 4) [1.1,2) @@ -98,7 +98,7 @@ 1.8 - 2.6.11 + 3.10.8 5.6.0 2.7.4 @@ -117,7 +117,6 @@ 4.0.1 7.0.0 4.0.0 - 4.17.0 4.21.0 1.83 @@ -1230,19 +1229,16 @@ ${groovy.version} - net.sf.ehcache - ehcache-core + org.ehcache + ehcache ${ehcache.version} + jakarta true commons-logging commons-logging - - net.sf.ehcache - sizeof-agent - @@ -1257,7 +1253,7 @@ - org.hibernate + org.hibernate.orm hibernate-core ${hibernate.version} true @@ -1287,38 +1283,21 @@ jacc - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api jboss jboss-cache - - net.sf.ehcache - ehcache - asm asm-attrs - - javax.transaction - jta - - - - org.apache.geronimo.specs - geronimo-jta_1.1_spec - 1.1.1 - runtime - true - org.springframework spring-context @@ -1398,11 +1377,6 @@ guice ${guice.version} - - com.google.inject.extensions - guice-multibindings - ${guice.version} - com.google.inject.extensions guice-servlet diff --git a/samples/guice/src/main/resources/log4j2.xml b/samples/guice/src/main/resources/log4j2.xml index 2fe38a9ec5..14974bd936 100644 --- a/samples/guice/src/main/resources/log4j2.xml +++ b/samples/guice/src/main/resources/log4j2.xml @@ -49,7 +49,7 @@ - + diff --git a/samples/quickstart-guice/src/main/resources/log4j2.xml b/samples/quickstart-guice/src/main/resources/log4j2.xml index e0b3288f58..9c12bb7722 100644 --- a/samples/quickstart-guice/src/main/resources/log4j2.xml +++ b/samples/quickstart-guice/src/main/resources/log4j2.xml @@ -49,7 +49,7 @@ - + diff --git a/samples/quickstart/src/main/resources/log4j2.xml b/samples/quickstart/src/main/resources/log4j2.xml index 59d525504d..10fc2f385e 100644 --- a/samples/quickstart/src/main/resources/log4j2.xml +++ b/samples/quickstart/src/main/resources/log4j2.xml @@ -49,7 +49,7 @@ - + diff --git a/samples/servlet-plugin/src/main/resources/log4j2.xml b/samples/servlet-plugin/src/main/resources/log4j2.xml index 74de9adf9a..445015ee16 100644 --- a/samples/servlet-plugin/src/main/resources/log4j2.xml +++ b/samples/servlet-plugin/src/main/resources/log4j2.xml @@ -49,7 +49,7 @@ - + diff --git a/samples/spring-boot-web/pom.xml b/samples/spring-boot-web/pom.xml index 7bb377100d..61087c6fc5 100644 --- a/samples/spring-boot-web/pom.xml +++ b/samples/spring-boot-web/pom.xml @@ -46,7 +46,6 @@ org.springframework.boot spring-boot-starter-thymeleaf - ${spring-boot.version} diff --git a/samples/spring-hibernate/pom.xml b/samples/spring-hibernate/pom.xml index 93b1fff6ad..9825e6bad0 100644 --- a/samples/spring-hibernate/pom.xml +++ b/samples/spring-hibernate/pom.xml @@ -67,30 +67,31 @@ provided - org.hibernate + org.hibernate.orm hibernate-core compile false - - - org.apache.geronimo.specs - geronimo-jta_1.1_spec - org.hsqldb hsqldb - net.sf.ehcache - ehcache-core - runtime + org.glassfish.jaxb + jaxb-runtime + 4.0.5 - org.hibernate - hibernate-ehcache - ${hibernate.version} + org.ehcache + ehcache + jakarta runtime + + + org.glassfish.jaxb + jaxb-runtime + + org.springframework diff --git a/samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/dao/HibernateUserDAO.java b/samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/dao/HibernateUserDAO.java index e493ff19e9..28a5bd16ec 100644 --- a/samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/dao/HibernateUserDAO.java +++ b/samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/dao/HibernateUserDAO.java @@ -25,7 +25,6 @@ import java.util.List; @Repository("userDAO") -@SuppressWarnings("unchecked") public class HibernateUserDAO extends HibernateDao implements UserDAO { public User getUser(Long userId) { @@ -35,26 +34,26 @@ public User getUser(Long userId) { public User findUser(String username) { Assert.hasText(username); String query = "from User u where u.username = :username"; - return (User) getSession().createQuery(query).setParameter("username", username).uniqueResult(); + return getSession().createQuery(query, User.class).setParameter("username", username).uniqueResult(); } public void createUser(User user) { - getSession().save(user); + getSession().persist(user); } public List getAllUsers() { - return getSession().createQuery("from User order by username").list(); + return getSession().createQuery("from User order by username", User.class).list(); } public void deleteUser(Long userId) { User user = getUser(userId); if (user != null) { - getSession().delete(user); + getSession().remove(user); } } public void updateUser(User user) { - getSession().update(user); + getSession().merge(user); } } diff --git a/samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/web/ManageUsersController.java b/samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/web/ManageUsersController.java index 80c9a16f02..1615d99ad6 100644 --- a/samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/web/ManageUsersController.java +++ b/samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/web/ManageUsersController.java @@ -26,9 +26,10 @@ import org.springframework.ui.Model; import org.springframework.util.Assert; import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** @@ -52,7 +53,7 @@ public void manageUsers(Model model) { model.addAttribute("users", userService.getAllUsers()); } - @RequestMapping(value = "/editUser", method = RequestMethod.GET) + @GetMapping("/editUser") @RequiresPermissions("user:edit") public String showEditUserForm(Model model, @RequestParam Long userId, @ModelAttribute EditUserCommand command) { @@ -63,7 +64,7 @@ public String showEditUserForm(Model model, @RequestParam Long userId, @ModelAtt return "editUser"; } - @RequestMapping(value = "/editUser", method = RequestMethod.POST) + @PostMapping("/editUser") @RequiresPermissions("user:edit") public String editUser(Model model, @RequestParam Long userId, @ModelAttribute EditUserCommand command, BindingResult errors) { diff --git a/samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/web/SecurityController.java b/samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/web/SecurityController.java index 640ffbf736..2a097b4054 100644 --- a/samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/web/SecurityController.java +++ b/samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/web/SecurityController.java @@ -24,9 +24,10 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; /** * Web MVC controller that handles security-related web requests, such as login and logout. @@ -36,12 +37,12 @@ public class SecurityController { private LoginValidator loginValidator = new LoginValidator(); - @RequestMapping(value = "/login", method = RequestMethod.GET) + @GetMapping("/login") public String showLoginForm(Model model, @ModelAttribute LoginCommand command) { return "login"; } - @RequestMapping(value = "/login", method = RequestMethod.POST) + @PostMapping("/login") public String login(Model model, @ModelAttribute LoginCommand command, BindingResult errors) { loginValidator.validate(command, errors); diff --git a/samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/web/SignupController.java b/samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/web/SignupController.java index 463c8bb24b..0624be07fd 100644 --- a/samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/web/SignupController.java +++ b/samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/web/SignupController.java @@ -25,9 +25,9 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.PostMapping; /** * Web MVC controller that handles signup requests. @@ -44,12 +44,12 @@ public void setUserService(UserService userService) { this.userService = userService; } - @RequestMapping(value = "/signup", method = RequestMethod.GET) + @GetMapping("/signup") public String showSignupForm(Model model, @ModelAttribute SignupCommand command) { return "signup"; } - @RequestMapping(value = "/signup", method = RequestMethod.POST) + @PostMapping("/signup") public String showSignupForm(Model model, @ModelAttribute SignupCommand command, BindingResult errors) { signupValidator.validate(command, errors); diff --git a/samples/spring-hibernate/src/main/resources/ehcache.xml b/samples/spring-hibernate/src/main/resources/ehcache.xml index f94edbc4ec..e45450ac3d 100644 --- a/samples/spring-hibernate/src/main/resources/ehcache.xml +++ b/samples/spring-hibernate/src/main/resources/ehcache.xml @@ -16,41 +16,52 @@ ~ specific language governing permissions and limitations ~ under the License. --> - + + - - - - + + java.io.Serializable + java.io.Serializable + + 10 + + + 1000 + 50 + + - - - + + + + + 100 + - + + + + + 100 + - + + + 1 + + 1000 + - + + + 1 + + 1000 + + diff --git a/samples/spring-mvc/pom.xml b/samples/spring-mvc/pom.xml index 137e2856d5..da1a4daaa0 100644 --- a/samples/spring-mvc/pom.xml +++ b/samples/spring-mvc/pom.xml @@ -70,9 +70,21 @@ 3.0.0 - net.sf.ehcache - ehcache-core + org.glassfish.jaxb + jaxb-runtime + 4.0.5 + + + org.ehcache + ehcache + jakarta false + + + org.glassfish.jaxb + jaxb-runtime + + org.apache.shiro diff --git a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/BootstrapDataPopulator.java b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/BootstrapDataPopulator.java index a2e014aaae..4f358a0b94 100644 --- a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/BootstrapDataPopulator.java +++ b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/BootstrapDataPopulator.java @@ -34,26 +34,28 @@ */ public class BootstrapDataPopulator implements InitializingBean { - private static final String CREATE_TABLES = "create table users (\n" - + " username varchar(255) primary key,\n" - + " password varchar(255) not null\n" - + ");\n" - + "\n" - + "create table roles (\n" - + " role_name varchar(255) primary key\n" - + ");\n" - + "\n" - + "create table user_roles (\n" - + " username varchar(255) not null,\n" - + " role_name varchar(255) not null,\n" - + " constraint user_roles_uq unique ( username, role_name )\n" - + ");\n" - + "\n" - + "create table roles_permissions (\n" - + " role_name varchar(255) not null,\n" - + " permission varchar(255) not null,\n" - + " primary key (role_name, permission)\n" - + ");"; + private static final String CREATE_TABLES = """ + create table users ( + username varchar(255) primary key, + password varchar(255) not null + ); + + create table roles ( + role_name varchar(255) primary key + ); + + create table user_roles ( + username varchar(255) not null, + role_name varchar(255) not null, + constraint user_roles_uq unique ( username, role_name ) + ); + + create table roles_permissions ( + role_name varchar(255) not null, + permission varchar(255) not null, + primary key (role_name, permission) + );\ + """; private static final Logger LOGGER = LoggerFactory.getLogger(BootstrapDataPopulator.class); diff --git a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/config/ApplicationConfig.java b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/config/ApplicationConfig.java index 04b28b65b9..36c8a8d031 100644 --- a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/config/ApplicationConfig.java +++ b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/config/ApplicationConfig.java @@ -20,18 +20,17 @@ import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.cache.ehcache.EhCacheManager; -import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.samples.spring.BootstrapDataPopulator; import org.apache.shiro.samples.spring.DefaultSampleManager; import org.apache.shiro.samples.spring.realm.SaltAwareJdbcRealm; import org.apache.shiro.spring.config.ShiroAnnotationProcessorConfiguration; import org.apache.shiro.spring.config.ShiroBeanConfiguration; -import org.apache.shiro.spring.remoting.SecureRemoteInvocationExecutor; import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition; import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition; import org.apache.shiro.spring.web.config.ShiroRequestMappingConfig; import org.apache.shiro.spring.web.config.ShiroWebConfiguration; import org.apache.shiro.spring.web.config.ShiroWebFilterConfiguration; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -51,7 +50,6 @@ ShiroWebConfiguration.class, ShiroWebFilterConfiguration.class, JspViewsConfig.class, - RemotingServletConfig.class, ShiroRequestMappingConfig.class}) @ComponentScan("org.apache.shiro.samples.spring") public class ApplicationConfig { @@ -118,23 +116,6 @@ protected EhCacheManager cacheManager() { return ehCacheManager; } - /** - * Secure Spring remoting: Ensure any Spring Remoting method invocations can be associated - * with a Subject for security checks. - * - * @param securityManager - * @return - */ - @Bean - protected SecureRemoteInvocationExecutor secureRemoteInvocationExecutor(SecurityManager securityManager) { - - SecureRemoteInvocationExecutor executor = new SecureRemoteInvocationExecutor(); - executor.setSecurityManager(securityManager); - - return executor; - } - - /** * Simulated business-tier "Manager", not Shiro related, just an example * @@ -174,8 +155,6 @@ public ShiroFilterChainDefinition shiroFilterChainDefinition() { chainDefinition.addPathDefinition("/s/login", "anon"); //allow WebStart to pull the jars for the swing app chainDefinition.addPathDefinition("/*.jar", "anon"); - // protected using SecureRemoteInvocationExecutor - chainDefinition.addPathDefinition("/remoting/**", "anon"); chainDefinition.addPathDefinition("/**", "authc"); diff --git a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/config/RemotingServletConfig.java b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/config/RemotingServletConfig.java deleted file mode 100644 index 403f0761b1..0000000000 --- a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/config/RemotingServletConfig.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.shiro.samples.spring.config; - -import org.apache.shiro.samples.spring.SampleManager; -import org.apache.shiro.spring.remoting.SecureRemoteInvocationExecutor; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter; - -/** - * Remoting bean definitions. - */ -@Configuration -@ComponentScan("org.apache.shiro.samples.spring") -public class RemotingServletConfig { - - @Bean(name = "/sampleManager") - @SuppressWarnings("deprecation") - public HttpInvokerServiceExporter accountServiceExporter(SampleManager sampleManager, - SecureRemoteInvocationExecutor secureRemoteInvocationExecutor) { - - HttpInvokerServiceExporter httpInvokerServiceExporter = new HttpInvokerServiceExporter(); - httpInvokerServiceExporter.setService(sampleManager); - httpInvokerServiceExporter.setServiceInterface(SampleManager.class); - httpInvokerServiceExporter.setRemoteInvocationExecutor(secureRemoteInvocationExecutor); - return httpInvokerServiceExporter; - } -} diff --git a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/config/ServletApplicationInitializer.java b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/config/ServletApplicationInitializer.java index 560471bc43..5d62b00de3 100644 --- a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/config/ServletApplicationInitializer.java +++ b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/config/ServletApplicationInitializer.java @@ -49,11 +49,6 @@ public void onStartup(ServletContext container) { shiroFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*"); - ServletRegistration.Dynamic remotingDispatcher = container.addServlet("remoting", new DispatcherServlet(appContext)); - remotingDispatcher.setLoadOnStartup(1); - remotingDispatcher.addMapping("/remoting/*"); - - ServletRegistration.Dynamic dispatcher = container.addServlet("DispatcherServlet", new DispatcherServlet(appContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); diff --git a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/IndexController.java b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/IndexController.java index 5ec0eef9a4..996bdfbae3 100644 --- a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/IndexController.java +++ b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/IndexController.java @@ -25,8 +25,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.util.LinkedHashMap; @@ -69,7 +70,7 @@ public void setSampleManager(SampleManager sampleManager) { | M E T H O D S | ============================================*/ - @RequestMapping(method = RequestMethod.GET) + @GetMapping protected String doGet(Model model) { buildModel(model); @@ -98,7 +99,7 @@ protected Model buildModel(Model model) { return model; } - @RequestMapping(method = RequestMethod.POST) + @PostMapping protected String doPost(@RequestParam("value") String newSessionValue, Model model) { sampleManager.setValue(newSessionValue); diff --git a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/JnlpController.java b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/JnlpController.java index 6ac04f520c..4b0b73371b 100644 --- a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/JnlpController.java +++ b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/JnlpController.java @@ -22,8 +22,8 @@ import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Component; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; @@ -68,7 +68,7 @@ public void setJnlpView(String jnlpView) { ============================================*/ @SuppressWarnings("checkstyle:MagicNumber") - @RequestMapping(method = RequestMethod.GET) + @GetMapping protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { Subject subject = SecurityUtils.getSubject(); diff --git a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/LoginController.java b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/LoginController.java index 22b8ad457f..1747ec2c90 100644 --- a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/LoginController.java +++ b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/LoginController.java @@ -25,8 +25,9 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** @@ -42,14 +43,14 @@ public class LoginController { private static String loginview = "login"; - @RequestMapping(method = RequestMethod.GET) + @GetMapping protected String view() { return loginview; } - @RequestMapping(method = RequestMethod.POST) - protected String onSubmit(@RequestParam("username") String username, - @RequestParam("password") String password, + @PostMapping + protected String onSubmit(@RequestParam String username, + @RequestParam String password, Model model) throws Exception { UsernamePasswordToken token = new UsernamePasswordToken(username, password); diff --git a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/LogoutController.java b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/LogoutController.java index e0974e13af..a8dfa1a494 100644 --- a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/LogoutController.java +++ b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/LogoutController.java @@ -20,8 +20,8 @@ import org.apache.shiro.SecurityUtils; import org.springframework.stereotype.Component; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; @@ -38,7 +38,7 @@ @RequestMapping("/s/logout") public class LogoutController extends AbstractController { - @RequestMapping(method = RequestMethod.GET) + @GetMapping protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { SecurityUtils.getSubject().logout(); return new ModelAndView("redirect:login"); diff --git a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/RootRedirectController.java b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/RootRedirectController.java index 6f64306c30..bfc5b9dbc8 100644 --- a/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/RootRedirectController.java +++ b/samples/spring-mvc/src/main/java/org/apache/shiro/samples/spring/web/RootRedirectController.java @@ -19,8 +19,8 @@ package org.apache.shiro.samples.spring.web; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; /** * Implements the root {@code welcome-file}j as a {@code @RequestMapping}. @@ -29,7 +29,7 @@ @RequestMapping({"/"}) public class RootRedirectController { - @RequestMapping(method = RequestMethod.GET) + @GetMapping public String redirect() { return "redirect:/s/login"; } diff --git a/samples/spring-mvc/src/main/resources/ehcache.xml b/samples/spring-mvc/src/main/resources/ehcache.xml index eb3504d41c..b5c7c9769b 100644 --- a/samples/spring-mvc/src/main/resources/ehcache.xml +++ b/samples/spring-mvc/src/main/resources/ehcache.xml @@ -18,8 +18,9 @@ --> - - + - - + (specified as LFU) --> - + + java.io.Serializable + java.io.Serializable + + 2 + + 10000 + - + + + + + + 10000 + 50 + + - + + org.apache.shiro.authz.AuthorizationInfo + + 10 + + 100 + - + diff --git a/samples/web-jakarta/src/main/resources/log4j2.xml b/samples/web-jakarta/src/main/resources/log4j2.xml index a91b7f33e4..4dea7a8b64 100644 --- a/samples/web-jakarta/src/main/resources/log4j2.xml +++ b/samples/web-jakarta/src/main/resources/log4j2.xml @@ -49,7 +49,7 @@ - + diff --git a/samples/web-jakarta/src/test/resources/log4j2.xml b/samples/web-jakarta/src/test/resources/log4j2.xml index 6fa211e03c..2dde25ba47 100644 --- a/samples/web-jakarta/src/test/resources/log4j2.xml +++ b/samples/web-jakarta/src/test/resources/log4j2.xml @@ -30,7 +30,7 @@ - + diff --git a/samples/web/src/main/resources/log4j2.xml b/samples/web/src/main/resources/log4j2.xml index a91b7f33e4..4dea7a8b64 100644 --- a/samples/web/src/main/resources/log4j2.xml +++ b/samples/web/src/main/resources/log4j2.xml @@ -49,7 +49,7 @@ - + diff --git a/support/cdi/src/main/java/org/apache/shiro/cdi/ShiroSecurityInterceptor.java b/support/cdi/src/main/java/org/apache/shiro/cdi/ShiroSecurityInterceptor.java index be152234a9..c2e1c992f6 100644 --- a/support/cdi/src/main/java/org/apache/shiro/cdi/ShiroSecurityInterceptor.java +++ b/support/cdi/src/main/java/org/apache/shiro/cdi/ShiroSecurityInterceptor.java @@ -13,6 +13,7 @@ */ package org.apache.shiro.cdi; +import java.io.Serial; import java.io.Serializable; import java.util.List; import jakarta.annotation.Priority; @@ -31,6 +32,7 @@ @Dependent @Priority(Interceptor.Priority.LIBRARY_BEFORE) public class ShiroSecurityInterceptor implements Serializable { + @Serial private static final long serialVersionUID = 1L; @AroundInvoke diff --git a/support/ehcache/pom.xml b/support/ehcache/pom.xml index be200dc8a4..77ab21905a 100644 --- a/support/ehcache/pom.xml +++ b/support/ehcache/pom.xml @@ -40,8 +40,20 @@ shiro-cache - net.sf.ehcache - ehcache-core + org.glassfish.jaxb + jaxb-runtime + 4.0.5 + + + org.ehcache + ehcache + jakarta + + + org.glassfish.jaxb + jaxb-runtime + + @@ -72,7 +84,7 @@ org.apache.shiro.cache.ehcache*;version=${project.version} org.apache.shiro.cache*;version="${shiro.osgi.importRange}", - net.sf.ehcache*;version="[2.5, 3)", + org.ehcache*;version="[3.10, 4)", * <_removeheaders>Bnd-LastModified diff --git a/support/ehcache/src/main/java/org/apache/shiro/cache/ehcache/EhCache.java b/support/ehcache/src/main/java/org/apache/shiro/cache/ehcache/EhCache.java index a138887774..358eb39231 100644 --- a/support/ehcache/src/main/java/org/apache/shiro/cache/ehcache/EhCache.java +++ b/support/ehcache/src/main/java/org/apache/shiro/cache/ehcache/EhCache.java @@ -18,7 +18,7 @@ */ package org.apache.shiro.cache.ehcache; -import net.sf.ehcache.Element; +import java.util.LinkedList; import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.CacheException; import org.slf4j.Logger; @@ -33,7 +33,7 @@ /** - * Shiro {@link org.apache.shiro.cache.Cache} implementation that wraps an {@link net.sf.ehcache.Ehcache} instance. + * Shiro {@link org.apache.shiro.cache.Cache} implementation that wraps an {@link org.ehcache.core.Ehcache} instance. * * @param K * @param V @@ -49,14 +49,14 @@ public class EhCache implements Cache { /** * The wrapped Ehcache instance. */ - private net.sf.ehcache.Ehcache cache; + private org.ehcache.Cache cache; /** * Constructs a new EhCache instance with the given cache. * * @param cache - delegate EhCache instance this Shiro cache instance will wrap. */ - public EhCache(net.sf.ehcache.Ehcache cache) { + public EhCache(org.ehcache.Cache cache) { if (cache == null) { throw new IllegalArgumentException("Cache argument cannot be null."); } @@ -69,23 +69,22 @@ public EhCache(net.sf.ehcache.Ehcache cache) { * @param key the key of the element to return. * @return The value placed into the cache with an earlier put, or null if not found or expired */ - @SuppressWarnings("unchecked") public V get(K key) throws CacheException { try { if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Getting object from cache [" + cache.getName() + "] for key [" + key + "]"); + LOGGER.trace("Getting object from cache [{}] for key [{}]", cache, key); } if (key == null) { return null; } else { - Element element = cache.get(key); + V element = cache.get(key); if (element == null) { if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Element for [" + key + "] is null."); + LOGGER.trace("Element for [{}] is null.", key); } return null; } else { - return (V) element.getObjectValue(); + return element; } } } catch (Throwable t) { @@ -101,12 +100,11 @@ public V get(K key) throws CacheException { */ public V put(K key, V value) throws CacheException { if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Putting object in cache [" + cache.getName() + "] for key [" + key + "]"); + LOGGER.trace("Putting object in cache [{}] for key [{}]", cache, key); } try { V previous = get(key); - Element element = new Element(key, value); - cache.put(element); + cache.put(key, value); return previous; } catch (Throwable t) { throw new CacheException(t); @@ -122,7 +120,7 @@ public V put(K key, V value) throws CacheException { */ public V remove(K key) throws CacheException { if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Removing object from cache [" + cache.getName() + "] for key [" + key + "]"); + LOGGER.trace("Removing object from cache [{}] for key [{}]", cache, key); } try { V previous = get(key); @@ -138,10 +136,10 @@ public V remove(K key) throws CacheException { */ public void clear() throws CacheException { if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Clearing all objects from cache [" + cache.getName() + "]"); + LOGGER.trace("Clearing all objects from cache [{}]", cache); } try { - cache.removeAll(); + cache.removeAll(keys()); } catch (Throwable t) { throw new CacheException(t); } @@ -149,7 +147,11 @@ public void clear() throws CacheException { public int size() { try { - return cache.getSize(); + int size = 0; + for (org.ehcache.Cache.Entry ignored : cache) { + size++; + } + return size; } catch (Throwable t) { throw new CacheException(t); } @@ -157,10 +159,13 @@ public int size() { public Set keys() { try { - @SuppressWarnings({"unchecked"}) - List keys = cache.getKeys(); + List keys = new LinkedList<>(); + for (org.ehcache.Cache.Entry entry : cache) { + keys.add(entry.getKey()); + } + if (!isEmpty(keys)) { - return Collections.unmodifiableSet(new LinkedHashSet(keys)); + return Collections.unmodifiableSet(new LinkedHashSet<>(keys)); } else { return Collections.emptySet(); } @@ -171,10 +176,9 @@ public Set keys() { public Collection values() { try { - @SuppressWarnings({"unchecked"}) - List keys = cache.getKeys(); + Set keys = keys(); if (!isEmpty(keys)) { - List values = new ArrayList(keys.size()); + List values = new ArrayList<>(keys.size()); for (K key : keys) { V value = get(key); if (value != null) { @@ -198,11 +202,7 @@ public Collection values() { * number is unknown or cannot be calculated. */ public long getMemoryUsage() { - try { - return cache.calculateInMemorySize(); - } catch (Throwable t) { - return -1; - } + return -1; } /** @@ -213,11 +213,7 @@ public long getMemoryUsage() { * that number is unknown or cannot be calculated. */ public long getMemoryStoreSize() { - try { - return cache.getMemoryStoreSize(); - } catch (Throwable t) { - throw new CacheException(t); - } + return -1; } /** @@ -228,20 +224,16 @@ public long getMemoryStoreSize() { * that number is unknown or cannot be calculated. */ public long getDiskStoreSize() { - try { - return cache.getDiskStoreSize(); - } catch (Throwable t) { - throw new CacheException(t); - } + return -1; } /** - * Returns "EhCache [" + cache.getName() + "]" + * Returns "EhCache [" + cache + "]" * - * @return "EhCache [" + cache.getName() + "]" + * @return "EhCache [" + cache + "]" */ public String toString() { - return "EhCache [" + cache.getName() + "]"; + return "EhCache [" + cache + "]"; } ////////////////////////// @@ -249,7 +241,7 @@ public String toString() { ////////////////////////// // CollectionUtils cannot be removed from shiro-core until 2.0 as it has a dependency on PrincipalCollection - private static boolean isEmpty(Collection c) { + private static boolean isEmpty(Collection c) { return c == null || c.isEmpty(); } } diff --git a/support/ehcache/src/main/java/org/apache/shiro/cache/ehcache/EhCacheManager.java b/support/ehcache/src/main/java/org/apache/shiro/cache/ehcache/EhCacheManager.java index eb4518878c..985276beaf 100644 --- a/support/ehcache/src/main/java/org/apache/shiro/cache/ehcache/EhCacheManager.java +++ b/support/ehcache/src/main/java/org/apache/shiro/cache/ehcache/EhCacheManager.java @@ -18,12 +18,17 @@ */ package org.apache.shiro.cache.ehcache; +import java.io.Serializable; +import java.net.URL; import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.CacheException; import org.apache.shiro.cache.CacheManager; import org.apache.shiro.lang.io.ResourceUtils; import org.apache.shiro.lang.util.Destroyable; import org.apache.shiro.lang.util.Initializable; +import org.ehcache.config.CacheConfiguration; +import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.xml.XmlConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,17 +38,17 @@ /** * Shiro {@code CacheManager} implementation utilizing the Ehcache framework for all cache functionality. *

- * This class can {@link #setCacheManager(net.sf.ehcache.CacheManager) accept} a manually configured - * {@link net.sf.ehcache.CacheManager net.sf.ehcache.CacheManager} instance, + * This class can {@link #setCacheManager(org.ehcache.CacheManager) accept} a manually configured + * {@link org.ehcache.CacheManager org.ehcache.CacheManager} instance, * or an {@code ehcache.xml} path location can be specified instead and one will be constructed. If neither are * specified, Shiro's failsafe ehcache.xml file will be used by default. *

* This implementation requires EhCache 1.2 and above. Make sure EhCache 1.1 or earlier * is not in the classpath or it will not work. *

- * Please see the Ehcache website for their documentation. + * Please see the Ehcache website for their documentation. * - * @see The Ehcache website + * @see The Ehcache website * @since 0.2 */ public class EhCacheManager implements CacheManager, Initializable, Destroyable { @@ -56,7 +61,7 @@ public class EhCacheManager implements CacheManager, Initializable, Destroyable /** * The EhCache cache manager used by this implementation to create caches. */ - protected net.sf.ehcache.CacheManager manager; + protected org.ehcache.CacheManager manager; /** * Indicates if the CacheManager instance was implicitly/automatically created by this instance, indicating that @@ -76,20 +81,20 @@ public EhCacheManager() { } /** - * Returns the wrapped Ehcache {@link net.sf.ehcache.CacheManager CacheManager} instance. + * Returns the wrapped Ehcache {@link org.ehcache.CacheManager CacheManager} instance. * - * @return the wrapped Ehcache {@link net.sf.ehcache.CacheManager CacheManager} instance. + * @return the wrapped Ehcache {@link org.ehcache.CacheManager CacheManager} instance. */ - public net.sf.ehcache.CacheManager getCacheManager() { + public org.ehcache.CacheManager getCacheManager() { return manager; } /** - * Sets the wrapped Ehcache {@link net.sf.ehcache.CacheManager CacheManager} instance. + * Sets the wrapped Ehcache {@link org.ehcache.CacheManager CacheManager} instance. * - * @param manager the wrapped Ehcache {@link net.sf.ehcache.CacheManager CacheManager} instance. + * @param manager the wrapped Ehcache {@link org.ehcache.CacheManager CacheManager} instance. */ - public void setCacheManager(net.sf.ehcache.CacheManager manager) { + public void setCacheManager(org.ehcache.CacheManager manager) { this.manager = manager; } @@ -140,37 +145,58 @@ protected InputStream getCacheManagerConfigFileInputStream() { } } + /** + * Acquires the URL for the ehcache configuration file using + * {@link ResourceUtils#getURLForPath(String) ResourceUtils.getURLForPath} with the + * path returned from {@link #getCacheManagerConfigFile() getCacheManagerConfigFile()}. + * + * @return the URL for the ehcache configuration file. + */ + protected URL getCacheManagerConfigFileUrl() { + final var configFile = getCacheManagerConfigFile(); + try { + return ResourceUtils.getURLForPath(configFile); + } catch (IOException e) { + throw new IllegalStateException("Unable to parse cacheManagerConfigFile [" + + configFile + "]", e); + } + } + /** * Loads an existing EhCache from the cache manager, or starts a new cache if one is not found. * * @param name the name of the cache to load/create. */ - public final Cache getCache(String name) throws CacheException { + @Override + public final Cache getCache(String name) + throws CacheException { if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Acquiring EhCache instance named [" + name + "]"); + LOGGER.trace("Acquiring EhCache instance named [{}]", name); } try { - net.sf.ehcache.Ehcache cache = ensureCacheManager().getEhcache(name); + org.ehcache.Cache cache = (org.ehcache.Cache) ensureCacheManager() + .getCache(name, Serializable.class, Serializable.class); if (cache == null) { if (LOGGER.isInfoEnabled()) { LOGGER.info("Cache with name '{}' does not yet exist. Creating now.", name); } - this.manager.addCache(name); - - cache = manager.getCache(name); + CacheConfiguration config = (CacheConfiguration) new XmlConfiguration(getCacheManagerConfigFileUrl()) + .newCacheConfigurationBuilderFromTemplate("default", Serializable.class, Serializable.class) + .build(); + cache = manager.createCache(name, config); if (LOGGER.isInfoEnabled()) { - LOGGER.info("Added EhCache named [" + name + "]"); + LOGGER.info("Added EhCache named [{}]", name); } } else { if (LOGGER.isInfoEnabled()) { - LOGGER.info("Using existing EHCache named [" + cache.getName() + "]"); + LOGGER.info("Using existing EHCache named [{}]", name); } } - return new EhCache(cache); - } catch (net.sf.ehcache.CacheException e) { + return new EhCache<>(cache); + } catch (IllegalArgumentException | IllegalStateException | ReflectiveOperationException e) { throw new CacheException(e); } } @@ -191,24 +217,21 @@ public final Cache getCache(String name) throws CacheException { * this case. * * @throws org.apache.shiro.cache.CacheException if there are any CacheExceptions thrown by EhCache. - * @see net.sf.ehcache.CacheManager#create + * @see org.ehcache.CacheManager#createCache(String, org.ehcache.config.CacheConfiguration) */ public final void init() throws CacheException { ensureCacheManager(); } - private net.sf.ehcache.CacheManager ensureCacheManager() { + private org.ehcache.CacheManager ensureCacheManager() { try { if (this.manager == null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("cacheManager property not set. Constructing CacheManager instance... "); } - //using the CacheManager constructor, the resulting instance is _not_ a VM singleton - //(as would be the case by calling CacheManager.getInstance(). We do not use the getInstance here - //because we need to know if we need to destroy the CacheManager instance - using the static call, - //we don't know which component is responsible for shutting it down. By using a single EhCacheManager, - //it will always know to shut down the instance if it was responsible for creating it. - this.manager = new net.sf.ehcache.CacheManager(getCacheManagerConfigFileInputStream()); + final XmlConfiguration xmlConfig = new XmlConfiguration(getCacheManagerConfigFileUrl()); + this.manager = CacheManagerBuilder.newCacheManager(xmlConfig); + this.manager.init(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("instantiated Ehcache CacheManager instance."); } @@ -233,8 +256,8 @@ private net.sf.ehcache.CacheManager ensureCacheManager() { public void destroy() { if (cacheManagerImplicitlyCreated) { try { - net.sf.ehcache.CacheManager cacheMgr = getCacheManager(); - cacheMgr.shutdown(); + org.ehcache.CacheManager cacheMgr = getCacheManager(); + cacheMgr.close(); } catch (Throwable t) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Unable to cleanly shutdown implicitly created CacheManager instance. " @@ -246,4 +269,5 @@ public void destroy() { } } } + } diff --git a/support/ehcache/src/main/resources/org/apache/shiro/cache/ehcache/ehcache.xml b/support/ehcache/src/main/resources/org/apache/shiro/cache/ehcache/ehcache.xml index dc310543ca..e232e922fe 100644 --- a/support/ehcache/src/main/resources/org/apache/shiro/cache/ehcache/ehcache.xml +++ b/support/ehcache/src/main/resources/org/apache/shiro/cache/ehcache/ehcache.xml @@ -16,7 +16,9 @@ ~ specific language governing permissions and limitations ~ under the License. --> - + - + - + + + 120 + + 10000 + - + + java.io.Serializable + java.io.Serializable + + + + + 10000 + 50 + + - + + java.io.Serializable + java.io.Serializable + + + + + 10000 + 50 + + - + diff --git a/support/ehcache/src/test/java/org/apache/shiro/cache/ehcache/EhCacheManagerTest.java b/support/ehcache/src/test/java/org/apache/shiro/cache/ehcache/EhCacheManagerTest.java index 8bbef12727..1efcb201f3 100644 --- a/support/ehcache/src/test/java/org/apache/shiro/cache/ehcache/EhCacheManagerTest.java +++ b/support/ehcache/src/test/java/org/apache/shiro/cache/ehcache/EhCacheManagerTest.java @@ -52,7 +52,7 @@ public void tearDown() { @Test void testCacheManagerCreationDuringInit() { - net.sf.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager(); + org.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager(); assertThat(ehCacheManager).isNull(); cacheManager.init(); //now assert that an internal CacheManager has been created: @@ -62,7 +62,7 @@ void testCacheManagerCreationDuringInit() { @Test void testLazyCacheManagerCreationWithoutCallingInit() { - net.sf.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager(); + org.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager(); assertThat(ehCacheManager).isNull(); //don't call init here - the ehcache CacheManager should be lazily created @@ -82,7 +82,7 @@ void testLazyCacheManagerCreationWithoutCallingInit() { @Test void testRemove() { - net.sf.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager(); + org.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager(); assertThat(ehCacheManager).isNull(); Cache cache = cacheManager.getCache("test"); @@ -109,7 +109,7 @@ void testRemove() { @Test void testClear() { - net.sf.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager(); + org.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager(); assertThat(ehCacheManager).isNull(); Cache cache = cacheManager.getCache("test"); @@ -134,7 +134,7 @@ void testClear() { @Test void testKeys() { - net.sf.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager(); + org.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager(); assertThat(ehCacheManager).isNull(); Cache cache = cacheManager.getCache("test"); @@ -168,7 +168,7 @@ void testKeys() { @Test void testValues() { - net.sf.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager(); + org.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager(); assertThat(ehCacheManager).isNull(); Cache cache = cacheManager.getCache("test"); diff --git a/support/ehcache/src/test/resources/log4j2-test.xml b/support/ehcache/src/test/resources/log4j2-test.xml index f8c691e638..bd8c3cb391 100644 --- a/support/ehcache/src/test/resources/log4j2-test.xml +++ b/support/ehcache/src/test/resources/log4j2-test.xml @@ -46,7 +46,7 @@ - + diff --git a/support/features/pom.xml b/support/features/pom.xml index 4d3dac8e08..6b9ddb1cfe 100644 --- a/support/features/pom.xml +++ b/support/features/pom.xml @@ -34,7 +34,7 @@ 1.9.4_1 0.9.5.4_1 - 2.6.11_1 + 3.10.8_1 2.4.13 2.3.2_1 diff --git a/support/features/src/main/resources/features.xml b/support/features/src/main/resources/features.xml index d7fc94c9f9..cf816c962f 100644 --- a/support/features/src/main/resources/features.xml +++ b/support/features/src/main/resources/features.xml @@ -27,7 +27,6 @@ mvn:org.apache.commons/commons-configuration2/${commons.configuration2.version} mvn:commons-collections/commons-collections/${commons.collection.version} mvn:org.apache.commons/commons-text/${commons.text.version} - mvn:org.apache.geronimo.specs/geronimo-annotation_1.3_spec/1.1 mvn:org.apache.shiro/shiro-lang/${project.version} mvn:org.apache.shiro/shiro-cache/${project.version} mvn:org.apache.shiro/shiro-config-ogdl/${project.version} @@ -68,7 +67,6 @@ shiro-core - mvn:org.apache.geronimo.specs/geronimo-jta_1.1_spec/1.1.1 mvn:com.hazelcast/hazelcast-all/${hazelcast.version} mvn:org.apache.shiro/shiro-hazelcast/${project.version} @@ -96,7 +94,7 @@ shiro-web - spring + spring mvn:org.apache.shiro/shiro-spring/${project.version} diff --git a/support/guice/src/main/java/org/apache/shiro/guice/BeanTypeListener.java b/support/guice/src/main/java/org/apache/shiro/guice/BeanTypeListener.java index 29690ca10f..c5e6ed06e2 100644 --- a/support/guice/src/main/java/org/apache/shiro/guice/BeanTypeListener.java +++ b/support/guice/src/main/java/org/apache/shiro/guice/BeanTypeListener.java @@ -147,8 +147,7 @@ private static Key createDependencyKey(PropertyDescriptor propertyDescriptor, } private static boolean requiresName(Type propertyType) { - if (propertyType instanceof Class) { - Class aClass = (Class) propertyType; + if (propertyType instanceof Class aClass) { return aClass.isPrimitive() || aClass.isEnum() || WRAPPER_TYPES.contains(aClass) diff --git a/support/guice/src/main/java/org/apache/shiro/guice/web/ShiroWebModule.java b/support/guice/src/main/java/org/apache/shiro/guice/web/ShiroWebModule.java index 8beb0c2494..d33ec0c60a 100644 --- a/support/guice/src/main/java/org/apache/shiro/guice/web/ShiroWebModule.java +++ b/support/guice/src/main/java/org/apache/shiro/guice/web/ShiroWebModule.java @@ -276,8 +276,8 @@ protected void bindWebEnvironment(AnnotatedBindingBuilder key) { // check for legacy API - if (key instanceof FilterConfigKey) { - addLegacyFilterChain(pattern, (FilterConfigKey) key); + if (key instanceof FilterConfigKey configKey) { + addLegacyFilterChain(pattern, configKey); } else { addFilterChain(pattern, new FilterConfig((Key) key, "")); } @@ -412,9 +412,7 @@ protected final void addFilterChain(String pattern, Key... key for (int ii = 0; ii < keys.length; ii++) { Key key = keys[ii]; // If this is a path matching filter, we need to remember the config - if (key instanceof FilterConfigKey) { - // legacy config - FilterConfigKey legacyKey = (FilterConfigKey) key; + if (key instanceof FilterConfigKey legacyKey) { filterConfigs[ii] = new FilterConfig(legacyKey.getKey(), legacyKey.getConfigValue()); } else { // Some other type of Filter key, no config diff --git a/support/guice/src/test/java/org/apache/shiro/guice/aop/ShiroAopModuleTest.java b/support/guice/src/test/java/org/apache/shiro/guice/aop/ShiroAopModuleTest.java index fea7732419..d569eb0a8e 100644 --- a/support/guice/src/test/java/org/apache/shiro/guice/aop/ShiroAopModuleTest.java +++ b/support/guice/src/test/java/org/apache/shiro/guice/aop/ShiroAopModuleTest.java @@ -93,8 +93,8 @@ protected void configureInterceptors(AnnotationResolver resolver) { boolean calledCustom = false; for (Element e : Elements.getElements(underTest)) { - if (e instanceof Binding) { - Key key = ((Binding) e).getKey(); + if (e instanceof Binding binding) { + Key key = binding.getKey(); if (Named.class.isAssignableFrom(key.getAnnotation().annotationType()) && "configureInterceptors".equals(((Named) key.getAnnotation()).value()) && key.getTypeLiteral().getRawType().equals(Object.class)) { @@ -123,8 +123,7 @@ protected void configureInterceptors(AnnotationResolver resolver) { List elements = Elements.getElements(underTest); for (Element element : elements) { - if (element instanceof InterceptorBinding) { - InterceptorBinding binding = (InterceptorBinding) element; + if (element instanceof InterceptorBinding binding) { assertThat(binding.getClassMatcher().matches(getClass())).isTrue(); Method method = null; Class theAnnotation = null; diff --git a/support/guice/src/test/java/org/apache/shiro/guice/web/ShiroWebModuleTest.java b/support/guice/src/test/java/org/apache/shiro/guice/web/ShiroWebModuleTest.java index 2432c72537..dca40c6bfb 100644 --- a/support/guice/src/test/java/org/apache/shiro/guice/web/ShiroWebModuleTest.java +++ b/support/guice/src/test/java/org/apache/shiro/guice/web/ShiroWebModuleTest.java @@ -53,6 +53,7 @@ import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; +import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; @@ -188,15 +189,15 @@ void testAddFilterChainGuice3and4() { HttpServletRequest request = createMock(HttpServletRequest.class); servletContext.setAttribute(eq(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY), EasyMock.anyObject()); - expect(request.getAttribute("javax.servlet.include.context_path")).andReturn("").anyTimes(); + expect(request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH)).andReturn("").anyTimes(); expect(request.getCharacterEncoding()).andReturn("UTF-8").anyTimes(); - expect(request.getAttribute("javax.servlet.include.path_info")).andReturn(null).anyTimes(); + expect(request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO)).andReturn(null).anyTimes(); expect(request.getPathInfo()).andReturn(null).anyTimes(); - expect(request.getAttribute("javax.servlet.include.servlet_path")).andReturn("/test_authc"); - expect(request.getAttribute("javax.servlet.include.servlet_path")).andReturn("/test_custom_filter"); - expect(request.getAttribute("javax.servlet.include.servlet_path")).andReturn("/test_authc_basic"); - expect(request.getAttribute("javax.servlet.include.servlet_path")).andReturn("/test_perms"); - expect(request.getAttribute("javax.servlet.include.servlet_path")).andReturn("/multiple_configs"); + expect(request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH)).andReturn("/test_authc"); + expect(request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH)).andReturn("/test_custom_filter"); + expect(request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH)).andReturn("/test_authc_basic"); + expect(request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH)).andReturn("/test_perms"); + expect(request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH)).andReturn("/multiple_configs"); replay(servletContext, request); Injector injector = Guice.createInjector(new ShiroWebModule(servletContext) { @@ -279,12 +280,12 @@ void testAddFilterChainGuice3Only() { HttpServletRequest request = createMock(HttpServletRequest.class); servletContext.setAttribute(eq(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY), EasyMock.anyObject()); - expect(request.getAttribute("javax.servlet.include.context_path")).andReturn("").anyTimes(); + expect(request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH)).andReturn("").anyTimes(); expect(request.getCharacterEncoding()).andReturn("UTF-8").anyTimes(); - expect(request.getAttribute("javax.servlet.include.request_uri")).andReturn("/test_authc"); - expect(request.getAttribute("javax.servlet.include.request_uri")).andReturn("/test_custom_filter"); - expect(request.getAttribute("javax.servlet.include.request_uri")).andReturn("/test_perms"); - expect(request.getAttribute("javax.servlet.include.request_uri")).andReturn("/multiple_configs"); + expect(request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH)).andReturn("/test_authc"); + expect(request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH)).andReturn("/test_custom_filter"); + expect(request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH)).andReturn("/test_perms"); + expect(request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH)).andReturn("/multiple_configs"); replay(servletContext, request); Injector injector = Guice.createInjector(new ShiroWebModule(servletContext) { @@ -350,11 +351,11 @@ void testDefaultPath() { HttpServletRequest request = createMock(HttpServletRequest.class); servletContext.setAttribute(eq(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY), EasyMock.anyObject()); - expect(request.getAttribute("javax.servlet.include.context_path")).andReturn("").anyTimes(); + expect(request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH)).andReturn("").anyTimes(); expect(request.getCharacterEncoding()).andReturn("UTF-8").anyTimes(); - expect(request.getAttribute("javax.servlet.include.path_info")).andReturn(null).anyTimes(); + expect(request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO)).andReturn(null).anyTimes(); expect(request.getPathInfo()).andReturn(null).anyTimes(); - expect(request.getAttribute("javax.servlet.include.servlet_path")).andReturn("/test/foobar"); + expect(request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH)).andReturn("/test/foobar"); replay(servletContext, request); Injector injector = Guice.createInjector(new ShiroWebModule(servletContext) { @@ -393,11 +394,11 @@ void testDisableGlobalFilters() { HttpServletRequest request = createMock(HttpServletRequest.class); servletContext.setAttribute(eq(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY), EasyMock.anyObject()); - expect(request.getAttribute("javax.servlet.include.context_path")).andReturn("").anyTimes(); + expect(request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH)).andReturn("").anyTimes(); expect(request.getCharacterEncoding()).andReturn("UTF-8").anyTimes(); - expect(request.getAttribute("javax.servlet.include.path_info")).andReturn(null).anyTimes(); + expect(request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO)).andReturn(null).anyTimes(); expect(request.getPathInfo()).andReturn(null).anyTimes(); - expect(request.getAttribute("javax.servlet.include.servlet_path")).andReturn("/test/foobar"); + expect(request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH)).andReturn("/test/foobar"); replay(servletContext, request); Injector injector = Guice.createInjector(new ShiroWebModule(servletContext) { @@ -441,11 +442,11 @@ void testChangeInvalidFilterConfig() { HttpServletRequest request = createMock(HttpServletRequest.class); servletContext.setAttribute(eq(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY), EasyMock.anyObject()); - expect(request.getAttribute("javax.servlet.include.context_path")).andReturn("").anyTimes(); + expect(request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH)).andReturn("").anyTimes(); expect(request.getCharacterEncoding()).andReturn("UTF-8").anyTimes(); - expect(request.getAttribute("javax.servlet.include.path_info")).andReturn(null).anyTimes(); + expect(request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO)).andReturn(null).anyTimes(); expect(request.getPathInfo()).andReturn(null).anyTimes(); - expect(request.getAttribute("javax.servlet.include.servlet_path")).andReturn("/test/foobar"); + expect(request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH)).andReturn("/test/foobar"); replay(servletContext, request); Injector injector = Guice.createInjector(new ShiroWebModule(servletContext) { diff --git a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/cdi/ShiroFacesViewScoped.java b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/cdi/ShiroFacesViewScoped.java index 9c8ce15992..6cfb4fee97 100644 --- a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/cdi/ShiroFacesViewScoped.java +++ b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/cdi/ShiroFacesViewScoped.java @@ -20,7 +20,7 @@ import jakarta.inject.Scope; /** - * {@code @javax.faces.view.ViewScoped} interface that works with Shiro sessions + * {@code @jakarta.faces.view.ViewScoped} interface that works with Shiro sessions * Primarily for plugging into Shiro destruction pipeline *

* This is an internal class and should not be used by applications diff --git a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/cdi/ShiroScopeContext.java b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/cdi/ShiroScopeContext.java index 540cf64fb2..cad0ba8942 100644 --- a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/cdi/ShiroScopeContext.java +++ b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/cdi/ShiroScopeContext.java @@ -15,6 +15,7 @@ import static org.apache.shiro.ee.filters.FormResubmitSupport.getNativeSessionManager; +import java.io.Serial; import java.io.Serializable; import java.lang.annotation.Annotation; import jakarta.enterprise.context.spi.Context; @@ -37,6 +38,7 @@ */ public class ShiroScopeContext implements Context, Serializable { private static final String BEAN_STORAGE_KEY = "org.apache.shiro.ee.bean-storage"; + @Serial private static final long serialVersionUID = 1L; private final Class scopeType; private final Class webScopeType; @@ -100,8 +102,7 @@ void onDestroy(Session session) { } public static boolean isWebContainerSessions(SecurityManager sm) { - if (sm instanceof WebSecurityManager) { - WebSecurityManager wsm = (WebSecurityManager) sm; + if (sm instanceof WebSecurityManager wsm) { return wsm.isHttpSessionMode(); } return false; diff --git a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/cdi/ShiroSessionScopeExtension.java b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/cdi/ShiroSessionScopeExtension.java index 805cac2bd1..6b522a1ddd 100644 --- a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/cdi/ShiroSessionScopeExtension.java +++ b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/cdi/ShiroSessionScopeExtension.java @@ -13,6 +13,7 @@ */ package org.apache.shiro.ee.cdi; +import java.io.Serial; import java.io.Serializable; import java.util.Collection; import java.util.List; @@ -37,6 +38,7 @@ * Entry point for Shiro Session scope CDI extension */ public class ShiroSessionScopeExtension implements Extension, Serializable { + @Serial private static final long serialVersionUID = 1L; @SuppressWarnings("ConstantName") private static final List contexts = Stream.of( diff --git a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitSupport.java b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitSupport.java index c5ac9e1bc0..64d54e3e7c 100644 --- a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitSupport.java +++ b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitSupport.java @@ -68,7 +68,6 @@ import lombok.ToString; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.SecurityUtils; -import static org.apache.shiro.ee.util.JakartaTransformer.jakartify; import org.apache.shiro.mgt.AbstractRememberMeManager; import org.apache.shiro.mgt.DefaultSecurityManager; import org.apache.shiro.mgt.SecurityManager; @@ -91,13 +90,13 @@ public class FormResubmitSupport { static final String SESSION_EXPIRED_PARAMETER = "org.apache.shiro.sessionExpired"; static final String FORM_IS_RESUBMITTED = "org.apache.shiro.form-is-resubmitted"; // encoded view state - private static final String FACES_VIEW_STATE = jakartify("jakarta.faces.ViewState"); + private static final String FACES_VIEW_STATE = "jakarta.faces.ViewState"; private static final String FACES_VIEW_STATE_EQUALS = FACES_VIEW_STATE + "="; private static final Pattern VIEW_STATE_PATTERN = Pattern.compile(String.format("(.*)(%s[-]?[\\d]+:[-]?[\\d]+)(.*)", FACES_VIEW_STATE_EQUALS)); - private static final String PARTIAL_VIEW = jakartify("jakarta.faces.partial"); + private static final String PARTIAL_VIEW = "jakarta.faces.partial"; private static final Pattern PARTIAL_REQUEST_PATTERN - = Pattern.compile(String.format("[\\&]?%s.\\w+=[\\w\\s:%%\\d]*", PARTIAL_VIEW)); + = Pattern.compile("[\\&]?%s.\\w+=[\\w\\s:%%\\d]*".formatted(PARTIAL_VIEW)); private static final Pattern INITIAL_AMPERSAND = Pattern.compile("^\\&"); private static final String FORM_DATA_CACHE = "org.apache.shiro.form-data-cache"; private static final String FORM_RESUBMIT_HOST = "org.apache.shiro.form-resubmit-host"; @@ -535,11 +534,10 @@ private static HttpClient buildHttpClient(URI savedRequest, ServletContext servl public static DefaultWebSessionManager getNativeSessionManager(SecurityManager securityManager) { DefaultWebSessionManager rv = null; SecurityManager unwrapped = unwrapSecurityManager(securityManager, SecurityManager.class, type -> false); - if (unwrapped instanceof SessionsSecurityManager) { - var ssm = (SessionsSecurityManager) unwrapped; + if (unwrapped instanceof SessionsSecurityManager ssm) { var sm = ssm.getSessionManager(); - if (sm instanceof DefaultWebSessionManager) { - rv = (DefaultWebSessionManager) sm; + if (sm instanceof DefaultWebSessionManager manager) { + rv = manager; } } return rv; @@ -556,13 +554,13 @@ private static String getJSFNewViewState(URI savedRequest, HttpClient client, St } static String extractJSFNewViewState(@NonNull String responseBody, @NonNull String savedFormData) { - Elements elts = Jsoup.parse(responseBody).select(String.format("input[name=%s]", FACES_VIEW_STATE)); + Elements elts = Jsoup.parse(responseBody).select("input[name=%s]".formatted(FACES_VIEW_STATE)); if (!elts.isEmpty()) { String viewState = elts.first().attr("value"); var matcher = VIEW_STATE_PATTERN.matcher(savedFormData); if (matcher.matches()) { - savedFormData = matcher.replaceFirst(String.format("$1%s%s$3", + savedFormData = matcher.replaceFirst("$1%s%s$3".formatted( FACES_VIEW_STATE_EQUALS, viewState)); log.debug("Encoded w/Replaced ViewState: {}", savedFormData); } diff --git a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/ShiroFilter.java b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/ShiroFilter.java index 1f18215090..0742d25b1b 100644 --- a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/ShiroFilter.java +++ b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/ShiroFilter.java @@ -169,8 +169,7 @@ static class WrappedSecurityManager implements WebSecurityManager, org.apache.sh @Override public Subject createSubject(SubjectContext context) { - if (context instanceof WebSubjectContext && wrapped instanceof DefaultSecurityManager) { - WebSubjectContext webContext = (WebSubjectContext) context; + if (context instanceof WebSubjectContext webContext && wrapped instanceof DefaultSecurityManager) { DefaultWebSecurityManager wsm = (DefaultWebSecurityManager) wrapped; Session session = null; try { diff --git a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/util/JakartaTransformer.java b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/util/JakartaTransformer.java deleted file mode 100644 index 8e7a0a6f9b..0000000000 --- a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/util/JakartaTransformer.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.shiro.ee.util; - -import java.util.regex.Pattern; -import jakarta.servlet.http.HttpServletRequest; - -import lombok.AccessLevel; -import lombok.Getter; -import lombok.NoArgsConstructor; - -/** - * transforms Java to Jakarta namespace - */ -@NoArgsConstructor(access = AccessLevel.PRIVATE) -@SuppressWarnings("HideUtilityClassConstructor") -public class JakartaTransformer { - @Getter - @SuppressWarnings("ConstantName") - private static final boolean jakarta = HttpServletRequest.class.getPackageName().startsWith("jakarta"); - private static final Pattern REPLACE_JAVA_WITH_JAKARTA_PATTERN = Pattern.compile("javax\\.(\\w+)\\."); - - public static String jakartify(String className) { - return REPLACE_JAVA_WITH_JAKARTA_PATTERN.matcher(className).replaceAll( - isJakarta() ? "jakarta.$1." : "javax.$1."); - } -} diff --git a/support/jakarta-ee/src/test/java/org/apache/shiro/ee/cdi/ShiroScopeContextTest.java b/support/jakarta-ee/src/test/java/org/apache/shiro/ee/cdi/ShiroScopeContextTest.java index 204bde427c..3d564fa1dc 100644 --- a/support/jakarta-ee/src/test/java/org/apache/shiro/ee/cdi/ShiroScopeContextTest.java +++ b/support/jakarta-ee/src/test/java/org/apache/shiro/ee/cdi/ShiroScopeContextTest.java @@ -116,7 +116,7 @@ void webSessionsCreate() { private void setupWebSessions() { - when(SecurityUtils.getSecurityManager()).thenReturn(mock(WebSecurityManager.class)); + secMock.when(SecurityUtils::getSecurityManager).thenReturn(mock(WebSecurityManager.class)); WebSecurityManager wsm = (WebSecurityManager) SecurityUtils.getSecurityManager(); when(wsm.isHttpSessionMode()).thenReturn(true); } diff --git a/support/jakarta-ee/src/test/java/org/apache/shiro/ee/filters/FormSupportTest.java b/support/jakarta-ee/src/test/java/org/apache/shiro/ee/filters/FormSupportTest.java index af26e86dcd..0ed7eb68e1 100644 --- a/support/jakarta-ee/src/test/java/org/apache/shiro/ee/filters/FormSupportTest.java +++ b/support/jakarta-ee/src/test/java/org/apache/shiro/ee/filters/FormSupportTest.java @@ -27,7 +27,6 @@ import java.util.Map; import jakarta.servlet.http.HttpServletRequest; -import static org.apache.shiro.ee.util.JakartaTransformer.jakartify; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; @@ -81,12 +80,12 @@ void dontSwitchToHttpsWhenCustomPortNoTrailingSlash() { void viewStatePattern() { String statefulFormData = "j_idt5%3Dj_idt5%26j_idt5%3Aj_idt7%3Daaa%26j_idt5%3Aj_idt9%3Dbbb%26j_idt5%3A" - + "j_idt11%3DSubmit+...%26" + jakartify("jakarta.faces.ViewState") + + "j_idt11%3DSubmit+...%26jakarta.faces.ViewState" + "%3D-8335355445345003673%3A-6008443334776649058"; assertThat(isJSFStatefulForm(decode(statefulFormData))).isTrue(); String statelessFormData = "j_idt5%3Dj_idt5%26j_idt5%3Aj_idt7%3Daaa%26j_idt5%3Aj_idt9%3Dbbb%26j_idt5%3A" - + "j_idt11%3DSubmit+...%26" + jakartify("jakarta.faces.ViewState") + "%3Dstateless"; + + "j_idt11%3DSubmit+...%26jakarta.faces.ViewState%3Dstateless"; assertThat(isJSFStatefulForm(statelessFormData)).isFalse(); assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> isJSFStatefulForm(null)); String nonJSFFormData @@ -100,49 +99,49 @@ void viewStatePattern() { void extractViewState() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> extractJSFNewViewState(null, null)); assertThat(extractJSFNewViewState("", "hello")).isEqualTo("hello"); - assertThat(extractJSFNewViewState("xxx", jakartify("jakarta.faces.ViewState=stateless&hello=bye"))) - .isEqualTo(jakartify("jakarta.faces.ViewState=stateless&hello=bye")); - assertThat(extractJSFNewViewState(jakartify(""), - jakartify("jakarta.faces.ViewState=stateless&hello=bye"))) - .isEqualTo(jakartify("jakarta.faces.ViewState=stateless&hello=bye")); - assertThat(extractJSFNewViewState(jakartify(""), - jakartify("aaa=bbb&jakarta.faces.ViewState=xxx:yyy&hello=bye"))) - .isEqualTo(jakartify("aaa=bbb&jakarta.faces.ViewState=xxx:yyy&hello=bye")); - assertThat(extractJSFNewViewState(jakartify(""), - jakartify("jakarta.faces.ViewState=987:654&hello=bye"))) - .isEqualTo(jakartify("jakarta.faces.ViewState=123:456&hello=bye")); - assertThat(extractJSFNewViewState(jakartify(""), - jakartify("jakarta.faces.ViewState=987:654&hello=bye"))) - .isEqualTo(jakartify("jakarta.faces.ViewState=-123:-456&hello=bye")); - assertThat(extractJSFNewViewState(jakartify(""), - jakartify("jakarta.faces.ViewState=-987:-654&hello=bye"))) - .isEqualTo(jakartify("jakarta.faces.ViewState=-123:-456&hello=bye")); - assertThat(extractJSFNewViewState(jakartify(""), - jakartify("aaa=bbb&jakarta.faces.ViewState=-987:-654&hello=bye"))) - .isEqualTo(jakartify("aaa=bbb&jakarta.faces.ViewState=-123:-456&hello=bye")); - assertThat(extractJSFNewViewState(jakartify(""), - jakartify("aaa=bbb&jakarta.faces.ViewState=-987:-654"))) - .isEqualTo(jakartify("aaa=bbb&jakarta.faces.ViewState=-123:-456")); + assertThat(extractJSFNewViewState("xxx", "jakarta.faces.ViewState=stateless&hello=bye")) + .isEqualTo("jakarta.faces.ViewState=stateless&hello=bye"); + assertThat(extractJSFNewViewState("", + "jakarta.faces.ViewState=stateless&hello=bye")) + .isEqualTo("jakarta.faces.ViewState=stateless&hello=bye"); + assertThat(extractJSFNewViewState("", + "aaa=bbb&jakarta.faces.ViewState=xxx:yyy&hello=bye")) + .isEqualTo("aaa=bbb&jakarta.faces.ViewState=xxx:yyy&hello=bye"); + assertThat(extractJSFNewViewState("", + "jakarta.faces.ViewState=987:654&hello=bye")) + .isEqualTo("jakarta.faces.ViewState=123:456&hello=bye"); + assertThat(extractJSFNewViewState("", + "jakarta.faces.ViewState=987:654&hello=bye")) + .isEqualTo("jakarta.faces.ViewState=-123:-456&hello=bye"); + assertThat(extractJSFNewViewState("", + "jakarta.faces.ViewState=-987:-654&hello=bye")) + .isEqualTo("jakarta.faces.ViewState=-123:-456&hello=bye"); + assertThat(extractJSFNewViewState("", + "aaa=bbb&jakarta.faces.ViewState=-987:-654&hello=bye")) + .isEqualTo("aaa=bbb&jakarta.faces.ViewState=-123:-456&hello=bye"); + assertThat(extractJSFNewViewState("", + "aaa=bbb&jakarta.faces.ViewState=-987:-654")) + .isEqualTo("aaa=bbb&jakarta.faces.ViewState=-123:-456"); } @Test void noAjaxRequests() { - assertThat(noJSFAjaxRequests(jakartify("aaa=bbb&jakarta.faces.ViewState=-123:-456") - + jakartify("&jakarta.faces.partial.ajax=true&hello=bye"), false)).isEqualTo(new PartialAjaxResult( - jakartify("aaa=bbb&jakarta.faces.ViewState=-123:-456&hello=bye"), - true, false)); + assertThat(noJSFAjaxRequests("aaa=bbb&jakarta.faces.ViewState=-123:-456" + + "&jakarta.faces.partial.ajax=true&hello=bye", false)).isEqualTo(new PartialAjaxResult( + "aaa=bbb&jakarta.faces.ViewState=-123:-456&hello=bye", + true, false)); assertThat(noJSFAjaxRequests("j_idt12=j_idt12&j_idt12:j_idt14=asdf&j_idt12:j_idt16=asdf" - + jakartify("&jakarta.faces.ViewState=7709788254588873136:-8052771455757429917") - + jakartify("&jakarta.faces.source=j_idt12:j_idt18") - + jakartify("&jakarta.faces.partial.event=click") - + jakartify("&jakarta.faces.partial.execute=j_idt12:j_idt18 j_idt12") - + jakartify("&jakarta.faces.partial.render=j_idt12") - + jakartify("&jakarta.faces.behavior.event=action") - + jakartify("&jakarta.faces.partial.ajax=false"), false)) - .isEqualTo(new PartialAjaxResult("j_idt12=j_idt12&j_idt12:j_idt14=asdf&j_idt12:j_idt16=asdf" - + jakartify("&jakarta.faces.ViewState=7709788254588873136:-8052771455757429917") - + jakartify("&jakarta.faces.source=j_idt12:j_idt18") - + jakartify("&jakarta.faces.behavior.event=action"), true, false)); + + "&jakarta.faces.ViewState=7709788254588873136:-8052771455757429917" + + "&jakarta.faces.source=j_idt12:j_idt18" + + "&jakarta.faces.partial.event=click" + + "&jakarta.faces.partial.execute=j_idt12:j_idt18 j_idt12" + + "&jakarta.faces.partial.render=j_idt12" + + "&jakarta.faces.behavior.event=action" + + "&jakarta.faces.partial.ajax=false", false)) + .isEqualTo(new PartialAjaxResult("j_idt12=j_idt12&j_idt12:j_idt14=asdf&j_idt12:j_idt16=asdf" + + "&jakarta.faces.ViewState=7709788254588873136:-8052771455757429917" + + "&jakarta.faces.source=j_idt12:j_idt18" + + "&jakarta.faces.behavior.event=action", true, false)); } @Test diff --git a/support/quartz/pom.xml b/support/quartz/pom.xml index 6d7558a87e..5e60e52948 100644 --- a/support/quartz/pom.xml +++ b/support/quartz/pom.xml @@ -72,7 +72,7 @@ org.apache.shiro.session.mgt.quartz*;version=${project.version} org.apache.shiro*;version="${shiro.osgi.importRange}", - org.quartz*;version="[1.7.2, 3)", + org.quartz*;version="[2.5.0, 3)", * <_removeheaders>Bnd-LastModified diff --git a/support/spring-boot/spring-boot-starter/src/test/resources/logback.xml b/support/spring-boot/spring-boot-starter/src/test/resources/logback.xml index 19d7e2461f..6d2f2cf57e 100644 --- a/support/spring-boot/spring-boot-starter/src/test/resources/logback.xml +++ b/support/spring-boot/spring-boot-starter/src/test/resources/logback.xml @@ -24,7 +24,7 @@ class="ch.qos.logback.core.ConsoleAppender"> - %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable + %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1}): %msg%n%throwable @@ -35,7 +35,7 @@ - + diff --git a/support/spring/src/main/java/org/apache/shiro/spring/LifecycleBeanPostProcessor.java b/support/spring/src/main/java/org/apache/shiro/spring/LifecycleBeanPostProcessor.java index df7640c7ff..d25296b92c 100644 --- a/support/spring/src/main/java/org/apache/shiro/spring/LifecycleBeanPostProcessor.java +++ b/support/spring/src/main/java/org/apache/shiro/spring/LifecycleBeanPostProcessor.java @@ -80,13 +80,13 @@ public LifecycleBeanPostProcessor(int order) { * @throws BeansException if any exception is thrown during initialization. */ public Object postProcessBeforeInitialization(Object object, String name) throws BeansException { - if (object instanceof Initializable) { + if (object instanceof Initializable initializable) { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Initializing bean [" + name + "]..."); } - ((Initializable) object).init(); + initializable.init(); } catch (Exception e) { throw new FatalBeanException("Error initializing bean [" + name + "]", e); } @@ -112,13 +112,13 @@ public Object postProcessAfterInitialization(Object object, String name) throws * @throws BeansException if any exception is thrown during initialization. */ public void postProcessBeforeDestruction(Object object, String name) throws BeansException { - if (object instanceof Destroyable) { + if (object instanceof Destroyable destroyable) { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Destroying bean [" + name + "]..."); } - ((Destroyable) object).destroy(); + destroyable.destroy(); } catch (Exception e) { throw new FatalBeanException("Error destroying bean [" + name + "]", e); } diff --git a/support/spring/src/main/java/org/apache/shiro/spring/ShiroEventBusBeanPostProcessor.java b/support/spring/src/main/java/org/apache/shiro/spring/ShiroEventBusBeanPostProcessor.java index fdbe833ed9..5f88f43634 100644 --- a/support/spring/src/main/java/org/apache/shiro/spring/ShiroEventBusBeanPostProcessor.java +++ b/support/spring/src/main/java/org/apache/shiro/spring/ShiroEventBusBeanPostProcessor.java @@ -56,8 +56,8 @@ public Object postProcessBeforeInitialization(Object bean, String beanName) thro @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - if (bean instanceof EventBusAware) { - ((EventBusAware) bean).setEventBus(eventBus); + if (bean instanceof EventBusAware aware) { + aware.setEventBus(eventBus); } else if (isEventSubscriber(bean)) { eventBus.register(bean); } diff --git a/support/spring/src/main/java/org/apache/shiro/spring/remoting/package-info.java b/support/spring/src/main/java/org/apache/shiro/spring/remoting/package-info.java deleted file mode 100644 index c6762a222c..0000000000 --- a/support/spring/src/main/java/org/apache/shiro/spring/remoting/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -/** - * Support to enable Spring-based remote method invocations to carry a Shiro session ID as part of the - * invocation payload, allowing remote clients to perform security operations. - */ -package org.apache.shiro.spring.remoting; diff --git a/support/spring/src/main/java/org/apache/shiro/spring/web/ShiroFilterFactoryBean.java b/support/spring/src/main/java/org/apache/shiro/spring/web/ShiroFilterFactoryBean.java index 6a4c6f62ba..ea9b11a872 100644 --- a/support/spring/src/main/java/org/apache/shiro/spring/web/ShiroFilterFactoryBean.java +++ b/support/spring/src/main/java/org/apache/shiro/spring/web/ShiroFilterFactoryBean.java @@ -83,7 +83,7 @@ * That ID can then be used in the filter chain definitions, for example: * *

- * <bean id="myCustomFilter" class="com.class.that.implements.javax.servlet.Filter"/>
+ * <bean id="myCustomFilter" class="com.class.that.implements.jakarta.servlet.Filter"/>
  * ...
  * <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  *    ...
@@ -303,7 +303,7 @@ public Map getFilters() {
      * 

* For example, just defining this bean in a web Spring XML application context: *

-     * <bean id="myFilter" class="com.class.that.implements.javax.servlet.Filter">
+     * <bean id="myFilter" class="com.class.that.implements.jakarta.servlet.Filter">
      * ...
      * </bean>
* Will automatically place that bean into this Filters map under the key 'myFilter'. @@ -422,8 +422,8 @@ protected FilterChainManager createFilterChainManager() { String name = entry.getKey(); Filter filter = entry.getValue(); applyGlobalPropertiesIfNecessary(filter); - if (filter instanceof Nameable) { - ((Nameable) filter).setName(name); + if (filter instanceof Nameable nameable) { + nameable.setName(name); } //'init' argument is false, since Spring-configured filters should be initialized //in Spring (i.e. 'init-method=blah') or implement InitializingBean: @@ -501,8 +501,7 @@ protected AbstractShiroFilter createInstance() throws Exception { private void applyLoginUrlIfNecessary(Filter filter) { String loginUrl = getLoginUrl(); - if (StringUtils.hasText(loginUrl) && (filter instanceof AccessControlFilter)) { - AccessControlFilter acFilter = (AccessControlFilter) filter; + if (StringUtils.hasText(loginUrl) && (filter instanceof AccessControlFilter acFilter)) { //only apply the login url if they haven't explicitly configured one already: String existingLoginUrl = acFilter.getLoginUrl(); if (AccessControlFilter.DEFAULT_LOGIN_URL.equals(existingLoginUrl)) { @@ -513,8 +512,7 @@ private void applyLoginUrlIfNecessary(Filter filter) { private void applySuccessUrlIfNecessary(Filter filter) { String successUrl = getSuccessUrl(); - if (StringUtils.hasText(successUrl) && (filter instanceof AuthenticationFilter)) { - AuthenticationFilter authcFilter = (AuthenticationFilter) filter; + if (StringUtils.hasText(successUrl) && (filter instanceof AuthenticationFilter authcFilter)) { //only apply the successUrl if they haven't explicitly configured one already: String existingSuccessUrl = authcFilter.getSuccessUrl(); if (AuthenticationFilter.DEFAULT_SUCCESS_URL.equals(existingSuccessUrl)) { @@ -525,8 +523,7 @@ private void applySuccessUrlIfNecessary(Filter filter) { private void applyUnauthorizedUrlIfNecessary(Filter filter) { String unauthorizedUrl = getUnauthorizedUrl(); - if (StringUtils.hasText(unauthorizedUrl) && (filter instanceof AuthorizationFilter)) { - AuthorizationFilter authzFilter = (AuthorizationFilter) filter; + if (StringUtils.hasText(unauthorizedUrl) && (filter instanceof AuthorizationFilter authzFilter)) { //only apply the unauthorizedUrl if they haven't explicitly configured one already: String existingUnauthorizedUrl = authzFilter.getUnauthorizedUrl(); if (existingUnauthorizedUrl == null) { @@ -540,8 +537,8 @@ private void applyGlobalPropertiesIfNecessary(Filter filter) { applySuccessUrlIfNecessary(filter); applyUnauthorizedUrlIfNecessary(filter); - if (filter instanceof OncePerRequestFilter) { - ((OncePerRequestFilter) filter).setFilterOncePerRequest(filterConfiguration.isFilterOncePerRequest()); + if (filter instanceof OncePerRequestFilter requestFilter) { + requestFilter.setFilterOncePerRequest(filterConfiguration.isFilterOncePerRequest()); } } @@ -551,9 +548,8 @@ private void applyGlobalPropertiesIfNecessary(Filter filter) { * later during filter chain construction. */ public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - if (bean instanceof Filter) { + if (bean instanceof Filter filter) { LOGGER.debug("Found filter chain candidate filter '{}'", beanName); - Filter filter = (Filter) bean; applyGlobalPropertiesIfNecessary(filter); getFilters().put(beanName, filter); } else { diff --git a/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroBeanConfigurationTest.groovy b/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroBeanConfigurationTest.groovy index cd21cf1402..af840bfc35 100644 --- a/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroBeanConfigurationTest.groovy +++ b/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroBeanConfigurationTest.groovy @@ -23,15 +23,15 @@ import org.apache.shiro.spring.testconfig.EventBusConsumersTestConfiguration import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit.jupiter.SpringExtension +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig import static org.junit.jupiter.api.Assertions.* /** * @since 1.4.0 */ -@ContextConfiguration(classes = [ShiroBeanConfiguration, EventBusConsumersTestConfiguration]) +@SpringJUnitConfig(classes = [ShiroBeanConfiguration, EventBusConsumersTestConfiguration]) @ExtendWith(SpringExtension.class) public class ShiroBeanConfigurationTest { diff --git a/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroConfigurationTest.groovy b/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroConfigurationTest.groovy index 2137df7c7a..d3e09c419f 100644 --- a/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroConfigurationTest.groovy +++ b/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroConfigurationTest.groovy @@ -29,8 +29,8 @@ import org.apache.shiro.subject.Subject import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit.jupiter.SpringExtension +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests import static org.hamcrest.MatcherAssert.assertThat @@ -40,7 +40,7 @@ import static org.junit.jupiter.api.Assertions.* /** * @since 1.4.0 */ -@ContextConfiguration(classes = [RealmTestConfiguration, ShiroConfiguration]) +@SpringJUnitConfig(classes = [RealmTestConfiguration, ShiroConfiguration]) @ExtendWith(SpringExtension.class) class ShiroConfigurationTest extends AbstractJUnit4SpringContextTests { diff --git a/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroConfigurationWithOptionalComponentsTest.groovy b/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroConfigurationWithOptionalComponentsTest.groovy index c242d2be13..e9ecb35cdc 100644 --- a/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroConfigurationWithOptionalComponentsTest.groovy +++ b/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroConfigurationWithOptionalComponentsTest.groovy @@ -30,8 +30,8 @@ import org.apache.shiro.subject.Subject import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit.jupiter.SpringExtension +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests import static org.junit.jupiter.api.Assertions.* @@ -41,7 +41,7 @@ import static org.hamcrest.MatcherAssert.* /** * @since 1.4.0 */ -@ContextConfiguration(classes = [RealmTestConfiguration, OptionalComponentsTestConfiguration, ShiroConfiguration, ShiroAnnotationProcessorConfiguration]) +@SpringJUnitConfig(classes = [RealmTestConfiguration, OptionalComponentsTestConfiguration, ShiroConfiguration, ShiroAnnotationProcessorConfiguration]) @ExtendWith(SpringExtension.class) class ShiroConfigurationWithOptionalComponentsTest extends AbstractJUnit4SpringContextTests { diff --git a/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroWebConfigurationTest.groovy b/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroWebConfigurationTest.groovy index 3382b0e038..d33ceb250e 100644 --- a/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroWebConfigurationTest.groovy +++ b/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroWebConfigurationTest.groovy @@ -32,8 +32,8 @@ import org.apache.shiro.subject.Subject import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit.jupiter.SpringExtension +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests import static org.hamcrest.MatcherAssert.assertThat @@ -43,7 +43,7 @@ import static org.junit.jupiter.api.Assertions.* /** * @since 1.4.0 */ -@ContextConfiguration(classes = [RealmTestConfiguration, ShiroConfiguration, ShiroWebConfiguration, ShiroWebFilterConfiguration]) +@SpringJUnitConfig(classes = [RealmTestConfiguration, ShiroConfiguration, ShiroWebConfiguration, ShiroWebFilterConfiguration]) @ExtendWith(SpringExtension.class) class ShiroWebConfigurationTest extends AbstractJUnit4SpringContextTests { diff --git a/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroWebFilterConfigurationTest.groovy b/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroWebFilterConfigurationTest.groovy index a43d3f38e7..f277eb179e 100644 --- a/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroWebFilterConfigurationTest.groovy +++ b/support/spring/src/test/groovy/org/apache/shiro/spring/config/ShiroWebFilterConfigurationTest.groovy @@ -31,8 +31,8 @@ import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration -import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit.jupiter.SpringExtension +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests import org.springframework.test.context.web.WebAppConfiguration @@ -52,7 +52,7 @@ import static org.hamcrest.MatcherAssert.assertThat * Test ShiroWebFilterConfiguration creates a ShiroFilterFactoryBean that contains Servlet filters that are available for injection. */ @WebAppConfiguration -@ContextConfiguration(classes = [RealmTestConfiguration, FilterConfiguration, ShiroConfiguration, ShiroWebFilterConfiguration]) +@SpringJUnitConfig(classes = [RealmTestConfiguration, FilterConfiguration, ShiroConfiguration, ShiroWebFilterConfiguration]) @ExtendWith(SpringExtension.class) class ShiroWebFilterConfigurationTest extends AbstractJUnit4SpringContextTests { diff --git a/support/spring/src/test/groovy/org/apache/shiro/spring/web/config/ShiroWebConfigurationTest.groovy b/support/spring/src/test/groovy/org/apache/shiro/spring/web/config/ShiroWebConfigurationTest.groovy index d5565fb029..68a4fb55f6 100644 --- a/support/spring/src/test/groovy/org/apache/shiro/spring/web/config/ShiroWebConfigurationTest.groovy +++ b/support/spring/src/test/groovy/org/apache/shiro/spring/web/config/ShiroWebConfigurationTest.groovy @@ -37,8 +37,8 @@ import org.springframework.beans.factory.annotation.Qualifier import org.springframework.expression.Expression import org.springframework.expression.ExpressionParser import org.springframework.expression.spel.standard.SpelExpressionParser -import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit.jupiter.SpringExtension +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig import static org.hamcrest.MatcherAssert.assertThat import static org.hamcrest.Matchers.* @@ -47,7 +47,7 @@ import static org.junit.jupiter.api.Assertions.* /** * @since 1.4.0 */ -@ContextConfiguration(classes = [EventBusTestConfiguration, RealmTestConfiguration, ShiroWebConfiguration]) +@SpringJUnitConfig(classes = [EventBusTestConfiguration, RealmTestConfiguration, ShiroWebConfiguration]) @ExtendWith(SpringExtension.class) public class ShiroWebConfigurationTest { diff --git a/support/spring/src/test/groovy/org/apache/shiro/spring/web/config/ShiroWebConfigurationWithCacheTest.groovy b/support/spring/src/test/groovy/org/apache/shiro/spring/web/config/ShiroWebConfigurationWithCacheTest.groovy index 72d86cd6e9..31c5033e2a 100644 --- a/support/spring/src/test/groovy/org/apache/shiro/spring/web/config/ShiroWebConfigurationWithCacheTest.groovy +++ b/support/spring/src/test/groovy/org/apache/shiro/spring/web/config/ShiroWebConfigurationWithCacheTest.groovy @@ -27,8 +27,8 @@ import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit.jupiter.SpringExtension +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig import static org.hamcrest.MatcherAssert.assertThat import static org.hamcrest.Matchers.* @@ -37,7 +37,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull /** * @since 1.4.0 */ -@ContextConfiguration(classes = [EventBusTestConfiguration, RealmTestConfiguration, CacheManagerConfiguration, ShiroWebConfiguration]) +@SpringJUnitConfig(classes = [EventBusTestConfiguration, RealmTestConfiguration, CacheManagerConfiguration, ShiroWebConfiguration]) @ExtendWith(SpringExtension.class) class ShiroWebConfigurationWithCacheTest { diff --git a/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/AbstractAuthorizationAnnotationTest.java b/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/AbstractAuthorizationAnnotationTest.java index f026dc3515..9f34b5d358 100644 --- a/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/AbstractAuthorizationAnnotationTest.java +++ b/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/AbstractAuthorizationAnnotationTest.java @@ -27,10 +27,8 @@ import org.apache.shiro.util.ThreadState; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; @@ -41,8 +39,7 @@ * * @since 1.1 */ -@ExtendWith(SpringExtension.class) -@ContextConfiguration +@SpringJUnitConfig public abstract class AbstractAuthorizationAnnotationTest { @Autowired diff --git a/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/DapcAuthorizationAnnotationTest.java b/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/DapcAuthorizationAnnotationTest.java index 4dc41aaa73..5c2274ee8c 100644 --- a/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/DapcAuthorizationAnnotationTest.java +++ b/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/DapcAuthorizationAnnotationTest.java @@ -20,9 +20,7 @@ import org.apache.shiro.authz.UnauthenticatedException; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; @@ -35,8 +33,7 @@ * * @since 1.1 */ -@ExtendWith(SpringExtension.class) -@ContextConfiguration +@SpringJUnitConfig public class DapcAuthorizationAnnotationTest extends AbstractAuthorizationAnnotationTest { @Test diff --git a/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/SchemaAuthorizationAnnotationTest.java b/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/SchemaAuthorizationAnnotationTest.java index f4eb521a78..f6a4cc1e49 100644 --- a/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/SchemaAuthorizationAnnotationTest.java +++ b/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/SchemaAuthorizationAnnotationTest.java @@ -18,9 +18,7 @@ */ package org.apache.shiro.spring.security.interceptor; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * All the tests in the parent class are run. This class exists to ensure that Shiro @@ -31,7 +29,6 @@ * * @since 1.1 */ -@ExtendWith(SpringExtension.class) -@ContextConfiguration +@SpringJUnitConfig public class SchemaAuthorizationAnnotationTest extends AbstractAuthorizationAnnotationTest { } diff --git a/support/spring/src/test/java/org/apache/shiro/spring/web/config/ShiroWebConfigurationTestSameSiteStrict.java b/support/spring/src/test/java/org/apache/shiro/spring/web/config/ShiroWebConfigurationTestSameSiteStrict.java index 588044f371..1fc716fe53 100644 --- a/support/spring/src/test/java/org/apache/shiro/spring/web/config/ShiroWebConfigurationTestSameSiteStrict.java +++ b/support/spring/src/test/java/org/apache/shiro/spring/web/config/ShiroWebConfigurationTestSameSiteStrict.java @@ -23,16 +23,13 @@ import org.apache.shiro.spring.testconfig.RealmTestConfiguration; import org.apache.shiro.web.servlet.Cookie; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import static org.assertj.core.api.Assertions.assertThat; -@ExtendWith(SpringExtension.class) -@ContextConfiguration(classes = {EventBusTestConfiguration.class, RealmTestConfiguration.class, ShiroWebConfiguration.class}) +@SpringJUnitConfig(classes = {EventBusTestConfiguration.class, RealmTestConfiguration.class, ShiroWebConfiguration.class}) @TestPropertySource public class ShiroWebConfigurationTestSameSiteStrict { diff --git a/support/spring/src/test/resources/log4j2-test.xml b/support/spring/src/test/resources/log4j2-test.xml index 37c9bc4aec..65044c0ae5 100644 --- a/support/spring/src/test/resources/log4j2-test.xml +++ b/support/spring/src/test/resources/log4j2-test.xml @@ -49,7 +49,7 @@ - + diff --git a/tools/hasher/pom.xml b/tools/hasher/pom.xml index 3bf6d50333..1d5545584b 100644 --- a/tools/hasher/pom.xml +++ b/tools/hasher/pom.xml @@ -93,7 +93,7 @@ org.springframework.boot spring-boot-maven-plugin - 2.7.18 + ${spring-boot.version} diff --git a/web/pom.xml b/web/pom.xml index 8da8dcd17e..45bc99bcb7 100644 --- a/web/pom.xml +++ b/web/pom.xml @@ -109,10 +109,10 @@ org.apache.shiro.web org.apache.shiro.web*;version=${project.version} - + org.apache.shiro*;version="${shiro.osgi.importRange}", - javax.servlet.jsp*;resolution:=optional, + jakarta.servlet.jsp*;resolution:=optional, * <_removeheaders>Bnd-LastModified diff --git a/web/src/main/java/org/apache/shiro/web/config/IniFilterChainResolverFactory.java b/web/src/main/java/org/apache/shiro/web/config/IniFilterChainResolverFactory.java index 79e5104c7a..6f19bee8e8 100644 --- a/web/src/main/java/org/apache/shiro/web/config/IniFilterChainResolverFactory.java +++ b/web/src/main/java/org/apache/shiro/web/config/IniFilterChainResolverFactory.java @@ -92,8 +92,7 @@ public void setGlobalFilters(List globalFilters) { protected FilterChainResolver createInstance(Ini ini) { FilterChainResolver filterChainResolver = createDefaultInstance(); - if (filterChainResolver instanceof PathMatchingFilterChainResolver) { - PathMatchingFilterChainResolver resolver = (PathMatchingFilterChainResolver) filterChainResolver; + if (filterChainResolver instanceof PathMatchingFilterChainResolver resolver) { FilterChainManager manager = resolver.getFilterChainManager(); buildChains(manager, ini); } @@ -193,8 +192,8 @@ private Map extractFilters(Map objects) { for (Map.Entry entry : objects.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); - if (value instanceof Filter) { - filterMap.put(key, (Filter) value); + if (value instanceof Filter filter) { + filterMap.put(key, filter); } } return filterMap; diff --git a/web/src/main/java/org/apache/shiro/web/env/EnvironmentLoader.java b/web/src/main/java/org/apache/shiro/web/env/EnvironmentLoader.java index 70097afb04..b36d810548 100644 --- a/web/src/main/java/org/apache/shiro/web/env/EnvironmentLoader.java +++ b/web/src/main/java/org/apache/shiro/web/env/EnvironmentLoader.java @@ -312,8 +312,8 @@ protected WebEnvironment createEnvironment(ServletContext sc) { environment.setServletContext(sc); - if (configSpecified && (environment instanceof ResourceConfigurable)) { - ((ResourceConfigurable) environment).setConfigLocations(configLocations); + if (configSpecified && (environment instanceof ResourceConfigurable configurable)) { + configurable.setConfigLocations(configLocations); } customizeEnvironment(environment); @@ -341,8 +341,8 @@ public void destroyEnvironment(ServletContext servletContext) { servletContext.log("Cleaning up Shiro Environment"); try { Object environment = servletContext.getAttribute(ENVIRONMENT_ATTRIBUTE_KEY); - if (environment instanceof WebEnvironment) { - finalizeEnvironment((WebEnvironment) environment); + if (environment instanceof WebEnvironment webEnvironment) { + finalizeEnvironment(webEnvironment); } LifecycleUtils.destroy(environment); } finally { diff --git a/web/src/main/java/org/apache/shiro/web/env/IniWebEnvironment.java b/web/src/main/java/org/apache/shiro/web/env/IniWebEnvironment.java index b0ea0a818e..1910699422 100644 --- a/web/src/main/java/org/apache/shiro/web/env/IniWebEnvironment.java +++ b/web/src/main/java/org/apache/shiro/web/env/IniWebEnvironment.java @@ -290,8 +290,7 @@ protected FilterChainResolver createFilterChainResolver() { if (!CollectionUtils.isEmpty(ini)) { @SuppressWarnings("unchecked") Factory factory = (Factory) this.objects.get(FILTER_CHAIN_RESOLVER_NAME); - if (factory instanceof IniFactorySupport) { - var iniFactory = (IniFactorySupport) factory; + if (factory instanceof IniFactorySupport iniFactory) { iniFactory.setIni(ini); iniFactory.setDefaults(this.objects); } diff --git a/web/src/main/java/org/apache/shiro/web/filter/PathMatchingFilter.java b/web/src/main/java/org/apache/shiro/web/filter/PathMatchingFilter.java index a948e4f6ab..6bcdfeac8c 100644 --- a/web/src/main/java/org/apache/shiro/web/filter/PathMatchingFilter.java +++ b/web/src/main/java/org/apache/shiro/web/filter/PathMatchingFilter.java @@ -255,12 +255,12 @@ protected boolean onPreHandle(ServletRequest request, ServletResponse response, @SuppressWarnings("UnusedParameters") /** * Path-matching version of the parent class's - * {@link #isEnabled(javax.servlet.ServletRequest, javax.servlet.ServletResponse)} method, but additionally allows + * {@link #isEnabled(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse)} method, but additionally allows * for inspection of any path-specific configuration values corresponding to the specified request. Subclasses * may wish to inspect this additional mapped configuration to determine if the filter is enabled or not. *

* This method's default implementation ignores the {@code path} and {@code mappedValue} arguments and merely - * returns the value from a call to {@link #isEnabled(javax.servlet.ServletRequest, javax.servlet.ServletResponse)}. + * returns the value from a call to {@link #isEnabled(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse)}. * It is expected that subclasses override this method if they need to perform enable/disable logic for a specific * request based on any path-specific config for the filter instance. * diff --git a/web/src/main/java/org/apache/shiro/web/filter/authc/package-info.java b/web/src/main/java/org/apache/shiro/web/filter/authc/package-info.java index f94395d6b5..f10f33ef01 100644 --- a/web/src/main/java/org/apache/shiro/web/filter/authc/package-info.java +++ b/web/src/main/java/org/apache/shiro/web/filter/authc/package-info.java @@ -17,7 +17,7 @@ * under the License. */ /** - * Servlet {@link javax.servlet.Filter Filter} implementations specific to controlling access based on a + * Servlet {@link jakarta.servlet.Filter Filter} implementations specific to controlling access based on a * subject's authentication status, or those that can execute authentications (log-ins) directly. */ package org.apache.shiro.web.filter.authc; diff --git a/web/src/main/java/org/apache/shiro/web/filter/authz/package-info.java b/web/src/main/java/org/apache/shiro/web/filter/authz/package-info.java index 580671a038..13630f1306 100644 --- a/web/src/main/java/org/apache/shiro/web/filter/authz/package-info.java +++ b/web/src/main/java/org/apache/shiro/web/filter/authz/package-info.java @@ -17,7 +17,7 @@ * under the License. */ /** - * Servlet {@link javax.servlet.Filter Filter} implementations that perform authorization (access control) + * Servlet {@link jakarta.servlet.Filter Filter} implementations that perform authorization (access control) * checks based on the Subject's abilities (for example, role or permission checks). */ package org.apache.shiro.web.filter.authz; diff --git a/web/src/main/java/org/apache/shiro/web/filter/mgt/DefaultFilterChainManager.java b/web/src/main/java/org/apache/shiro/web/filter/mgt/DefaultFilterChainManager.java index 1e962b4044..cdc16e2066 100644 --- a/web/src/main/java/org/apache/shiro/web/filter/mgt/DefaultFilterChainManager.java +++ b/web/src/main/java/org/apache/shiro/web/filter/mgt/DefaultFilterChainManager.java @@ -274,8 +274,8 @@ protected String[] toNameConfigPair(String token) throws ConfigurationException protected void addFilter(String name, Filter filter, boolean init, boolean overwrite) { Filter existing = getFilter(name); if (existing == null || overwrite) { - if (filter instanceof Nameable) { - ((Nameable) filter).setName(name); + if (filter instanceof Nameable nameable) { + nameable.setName(name); } if (init) { initFilter(filter); @@ -325,8 +325,8 @@ protected void applyChainConfig(String chainName, Filter filter, String chainSpe LOGGER.debug("Attempting to apply path [" + chainName + "] to filter [" + filter + "] " + "with config [" + chainSpecificFilterConfig + "]"); } - if (filter instanceof PathConfigProcessor) { - ((PathConfigProcessor) filter).processPathConfig(chainName, chainSpecificFilterConfig); + if (filter instanceof PathConfigProcessor processor) { + processor.processPathConfig(chainName, chainSpecificFilterConfig); } else { if (StringUtils.hasText(chainSpecificFilterConfig)) { //they specified a filter configuration, but the Filter doesn't implement PathConfigProcessor diff --git a/web/src/main/java/org/apache/shiro/web/filter/package-info.java b/web/src/main/java/org/apache/shiro/web/filter/package-info.java index 47e713446e..447441d65a 100644 --- a/web/src/main/java/org/apache/shiro/web/filter/package-info.java +++ b/web/src/main/java/org/apache/shiro/web/filter/package-info.java @@ -17,7 +17,7 @@ * under the License. */ /** - * Base package supporting all Servlet {@link javax.servlet.Filter Filter} implementations used to control + * Base package supporting all Servlet {@link jakarta.servlet.Filter Filter} implementations used to control * access to web pages and URL resources. */ package org.apache.shiro.web.filter; diff --git a/web/src/main/java/org/apache/shiro/web/mgt/DefaultWebSecurityManager.java b/web/src/main/java/org/apache/shiro/web/mgt/DefaultWebSecurityManager.java index 8ef1043409..1478fe5a31 100644 --- a/web/src/main/java/org/apache/shiro/web/mgt/DefaultWebSecurityManager.java +++ b/web/src/main/java/org/apache/shiro/web/mgt/DefaultWebSecurityManager.java @@ -127,18 +127,18 @@ protected void afterSessionManagerSet() { //since 1.2.1 for fixing SHIRO-350: private void applySessionManagerToSessionStorageEvaluatorIfPossible() { SubjectDAO subjectDAO = getSubjectDAO(); - if (subjectDAO instanceof DefaultSubjectDAO) { - SessionStorageEvaluator evaluator = ((DefaultSubjectDAO) subjectDAO).getSessionStorageEvaluator(); - if (evaluator instanceof DefaultWebSessionStorageEvaluator) { - ((DefaultWebSessionStorageEvaluator) evaluator).setSessionManager(getSessionManager()); + if (subjectDAO instanceof DefaultSubjectDAO defaultSubjectDAO) { + SessionStorageEvaluator evaluator = defaultSubjectDAO.getSessionStorageEvaluator(); + if (evaluator instanceof DefaultWebSessionStorageEvaluator storageEvaluator) { + storageEvaluator.setSessionManager(getSessionManager()); } } } @Override protected SubjectContext copy(SubjectContext subjectContext) { - if (subjectContext instanceof WebSubjectContext) { - return new DefaultWebSubjectContext((WebSubjectContext) subjectContext); + if (subjectContext instanceof WebSubjectContext context) { + return new DefaultWebSubjectContext(context); } return super.copy(subjectContext); } @@ -206,7 +206,7 @@ private void setInternalSessionManager(SessionManager sessionManager) { */ public boolean isHttpSessionMode() { SessionManager sessionManager = getSessionManager(); - return sessionManager instanceof WebSessionManager && ((WebSessionManager) sessionManager).isServletContainerSessions(); + return sessionManager instanceof WebSessionManager wsm && wsm.isServletContainerSessions(); } protected SessionManager createSessionManager(String sessionMode) { @@ -222,8 +222,7 @@ protected SessionManager createSessionManager(String sessionMode) { @Override protected SessionContext createSessionContext(SubjectContext subjectContext) { SessionContext sessionContext = super.createSessionContext(subjectContext); - if (subjectContext instanceof WebSubjectContext) { - WebSubjectContext wsc = (WebSubjectContext) subjectContext; + if (subjectContext instanceof WebSubjectContext wsc) { ServletRequest request = wsc.resolveServletRequest(); ServletResponse response = wsc.resolveServletResponse(); DefaultWebSessionContext webSessionContext = new DefaultWebSessionContext(sessionContext); @@ -259,8 +258,7 @@ protected void beforeLogout(Subject subject) { } protected void removeRequestIdentity(Subject subject) { - if (subject instanceof WebSubject) { - WebSubject webSubject = (WebSubject) subject; + if (subject instanceof WebSubject webSubject) { ServletRequest request = webSubject.getServletRequest(); if (request != null) { request.setAttribute(ShiroHttpServletRequest.IDENTITY_REMOVED_KEY, Boolean.TRUE); diff --git a/web/src/main/java/org/apache/shiro/web/servlet/AbstractFilter.java b/web/src/main/java/org/apache/shiro/web/servlet/AbstractFilter.java index 0ea86b16a6..a197e3682a 100644 --- a/web/src/main/java/org/apache/shiro/web/servlet/AbstractFilter.java +++ b/web/src/main/java/org/apache/shiro/web/servlet/AbstractFilter.java @@ -96,8 +96,8 @@ public final void init(FilterConfig filterConfig) throws ServletException { try { onFilterConfigSet(); } catch (Exception e) { - if (e instanceof ServletException) { - throw (ServletException) e; + if (e instanceof ServletException exception) { + throw exception; } else { if (LOGGER.isErrorEnabled()) { LOGGER.error("Unable to start Filter: [" + e.getMessage() + "].", e); diff --git a/web/src/main/java/org/apache/shiro/web/servlet/AbstractShiroFilter.java b/web/src/main/java/org/apache/shiro/web/servlet/AbstractShiroFilter.java index 7c5045c595..975f81a697 100644 --- a/web/src/main/java/org/apache/shiro/web/servlet/AbstractShiroFilter.java +++ b/web/src/main/java/org/apache/shiro/web/servlet/AbstractShiroFilter.java @@ -242,8 +242,7 @@ protected ServletRequest wrapServletRequest(HttpServletRequest orig) { @SuppressWarnings({"UnusedDeclaration"}) protected ServletRequest prepareServletRequest(ServletRequest request, ServletResponse response, FilterChain chain) { ServletRequest toUse = request; - if (request instanceof HttpServletRequest) { - HttpServletRequest http = (HttpServletRequest) request; + if (request instanceof HttpServletRequest http) { toUse = wrapServletRequest(http); } return toUse; @@ -284,11 +283,11 @@ protected ServletResponse wrapServletResponse(HttpServletResponse orig, ShiroHtt @SuppressWarnings({"UnusedDeclaration"}) protected ServletResponse prepareServletResponse(ServletRequest request, ServletResponse response, FilterChain chain) { ServletResponse toUse = response; - if (!isHttpSessions() && (request instanceof ShiroHttpServletRequest) - && (response instanceof HttpServletResponse)) { + if (!isHttpSessions() && (request instanceof ShiroHttpServletRequest servletRequest) + && (response instanceof HttpServletResponse servletResponse)) { //the ShiroHttpServletResponse exists to support URL rewriting for session ids. This is only needed if //using Shiro sessions (i.e. not simple HttpSession based sessions): - toUse = wrapServletResponse((HttpServletResponse) response, (ShiroHttpServletRequest) request); + toUse = wrapServletResponse(servletResponse, servletRequest); } return toUse; } @@ -385,11 +384,11 @@ protected void doFilterInternal(ServletRequest servletRequest, ServletResponse s } if (t != null) { - if (t instanceof ServletException) { - throw (ServletException) t; + if (t instanceof ServletException exception) { + throw exception; } - if (t instanceof IOException) { - throw (IOException) t; + if (t instanceof IOException exception) { + throw exception; } //otherwise it's not one of the two exceptions expected by the filter method signature - wrap it in one: String msg = "Filtered request failed."; @@ -440,10 +439,12 @@ protected FilterChain getExecutionChain(ServletRequest request, ServletResponse * Executes a {@link FilterChain} for the given request. *

* This implementation first delegates to - * {@link #getExecutionChain(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, - * jakarta.servlet.FilterChain) getExecutionChain} to allow the application's Shiro configuration to determine exactly - * how the chain should execute. The resulting value from that call is then executed directly by calling the returned - * {@code FilterChain}'s {@link FilterChain#doFilter doFilter} method. That is: + * + * {@link #getExecutionChain(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, jakarta.servlet.FilterChain) + * getExecutionChain} + * to allow the application's Shiro configuration to determine exactly how the chain should execute. The resulting + * value from that call is then executed directly by calling the returned {@code FilterChain}'s + * {@link FilterChain#doFilter doFilter} method. That is: *

      * FilterChain chain = {@link #getExecutionChain}(request, response, origChain);
      * chain.{@link FilterChain#doFilter doFilter}(request,response);
diff --git a/web/src/main/java/org/apache/shiro/web/servlet/AdviceFilter.java b/web/src/main/java/org/apache/shiro/web/servlet/AdviceFilter.java index 1d00d73dda..3622120680 100644 --- a/web/src/main/java/org/apache/shiro/web/servlet/AdviceFilter.java +++ b/web/src/main/java/org/apache/shiro/web/servlet/AdviceFilter.java @@ -184,10 +184,10 @@ protected void cleanup(ServletRequest request, ServletResponse response, Excepti } } if (exception != null) { - if (exception instanceof ServletException) { - throw (ServletException) exception; - } else if (exception instanceof IOException) { - throw (IOException) exception; + if (exception instanceof ServletException servletException) { + throw servletException; + } else if (exception instanceof IOException oException) { + throw oException; } else { if (LOGGER.isDebugEnabled()) { String msg = "Filter execution resulted in an unexpected Exception " diff --git a/web/src/main/java/org/apache/shiro/web/servlet/ShiroHttpServletRequest.java b/web/src/main/java/org/apache/shiro/web/servlet/ShiroHttpServletRequest.java index 9239a91c00..521f78fa8e 100644 --- a/web/src/main/java/org/apache/shiro/web/servlet/ShiroHttpServletRequest.java +++ b/web/src/main/java/org/apache/shiro/web/servlet/ShiroHttpServletRequest.java @@ -77,10 +77,10 @@ public String getRemoteUser() { String remoteUser; Object scPrincipal = getSubjectPrincipal(); if (scPrincipal != null) { - if (scPrincipal instanceof String) { - return (String) scPrincipal; - } else if (scPrincipal instanceof Principal) { - remoteUser = ((Principal) scPrincipal).getName(); + if (scPrincipal instanceof String string) { + return string; + } else if (scPrincipal instanceof Principal principal) { + remoteUser = principal.getName(); } else { remoteUser = scPrincipal.toString(); } @@ -116,8 +116,8 @@ public Principal getUserPrincipal() { Principal userPrincipal; Object scPrincipal = getSubjectPrincipal(); if (scPrincipal != null) { - if (scPrincipal instanceof Principal) { - userPrincipal = (Principal) scPrincipal; + if (scPrincipal instanceof Principal principal) { + userPrincipal = principal; } else { userPrincipal = new ObjectPrincipal(scPrincipal); } @@ -247,8 +247,7 @@ public int hashCode() { } public boolean equals(Object o) { - if (o instanceof ObjectPrincipal) { - ObjectPrincipal op = (ObjectPrincipal) o; + if (o instanceof ObjectPrincipal op) { return getObject().equals(op.getObject()); } return false; diff --git a/web/src/main/java/org/apache/shiro/web/servlet/SimpleCookie.java b/web/src/main/java/org/apache/shiro/web/servlet/SimpleCookie.java index fa663e772a..c86ea5736b 100644 --- a/web/src/main/java/org/apache/shiro/web/servlet/SimpleCookie.java +++ b/web/src/main/java/org/apache/shiro/web/servlet/SimpleCookie.java @@ -35,7 +35,7 @@ /** * Default {@link Cookie Cookie} implementation. 'HttpOnly' is supported out of the box, even on * Servlet {@code 2.4} and {@code 2.5} container implementations, using raw header writing logic and not - * {@link jakarta.servlet.http.Cookie javax.servlet.http.Cookie} objects (which only has 'HttpOnly' support in Servlet + * {@link jakarta.servlet.http.Cookie jakarta.servlet.http.Cookie} objects (which only has 'HttpOnly' support in Servlet * {@code 2.6} specifications and above). * * @since 1.0 diff --git a/web/src/main/java/org/apache/shiro/web/util/RedirectView.java b/web/src/main/java/org/apache/shiro/web/util/RedirectView.java index 9f0469e654..bbb494e630 100644 --- a/web/src/main/java/org/apache/shiro/web/util/RedirectView.java +++ b/web/src/main/java/org/apache/shiro/web/util/RedirectView.java @@ -262,6 +262,7 @@ protected void appendQueryProperties(StringBuilder targetUrl, Map model, String * @param encodingScheme the encoding scheme * @return the encoded output String * @throws UnsupportedEncodingException if thrown by the JDK URLEncoder + * @see java.net.URLEncoder#encode(String, java.nio.charset.Charset) * @see java.net.URLEncoder#encode(String, String) * @see java.net.URLEncoder#encode(String) */ diff --git a/web/src/main/java/org/apache/shiro/web/util/WebUtils.java b/web/src/main/java/org/apache/shiro/web/util/WebUtils.java index 8960e5c1ab..4cb1a0b54b 100644 --- a/web/src/main/java/org/apache/shiro/web/util/WebUtils.java +++ b/web/src/main/java/org/apache/shiro/web/util/WebUtils.java @@ -30,6 +30,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; @@ -38,6 +39,7 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.util.Map; /** @@ -68,22 +70,22 @@ public final class WebUtils { *

If included via a RequestDispatcher, the current resource will see the * originating request. Its own URI and paths are exposed as request attributes. */ - public static final String INCLUDE_REQUEST_URI_ATTRIBUTE = "javax.servlet.include.request_uri"; - public static final String INCLUDE_CONTEXT_PATH_ATTRIBUTE = "javax.servlet.include.context_path"; - public static final String INCLUDE_SERVLET_PATH_ATTRIBUTE = "javax.servlet.include.servlet_path"; - public static final String INCLUDE_PATH_INFO_ATTRIBUTE = "javax.servlet.include.path_info"; - public static final String INCLUDE_QUERY_STRING_ATTRIBUTE = "javax.servlet.include.query_string"; + public static final String INCLUDE_REQUEST_URI_ATTRIBUTE = RequestDispatcher.INCLUDE_REQUEST_URI; + public static final String INCLUDE_CONTEXT_PATH_ATTRIBUTE = RequestDispatcher.INCLUDE_CONTEXT_PATH; + public static final String INCLUDE_SERVLET_PATH_ATTRIBUTE = RequestDispatcher.INCLUDE_SERVLET_PATH; + public static final String INCLUDE_PATH_INFO_ATTRIBUTE = RequestDispatcher.INCLUDE_PATH_INFO; + public static final String INCLUDE_QUERY_STRING_ATTRIBUTE = RequestDispatcher.INCLUDE_QUERY_STRING; /** * Standard Servlet 2.4+ spec request attributes for forward URI and paths. *

If forwarded to via a RequestDispatcher, the current resource will see its * own URI and paths. The originating URI and paths are exposed as request attributes. */ - public static final String FORWARD_REQUEST_URI_ATTRIBUTE = "javax.servlet.forward.request_uri"; - public static final String FORWARD_CONTEXT_PATH_ATTRIBUTE = "javax.servlet.forward.context_path"; - public static final String FORWARD_SERVLET_PATH_ATTRIBUTE = "javax.servlet.forward.servlet_path"; - public static final String FORWARD_PATH_INFO_ATTRIBUTE = "javax.servlet.forward.path_info"; - public static final String FORWARD_QUERY_STRING_ATTRIBUTE = "javax.servlet.forward.query_string"; + public static final String FORWARD_REQUEST_URI_ATTRIBUTE = RequestDispatcher.FORWARD_REQUEST_URI; + public static final String FORWARD_CONTEXT_PATH_ATTRIBUTE = RequestDispatcher.FORWARD_CONTEXT_PATH; + public static final String FORWARD_SERVLET_PATH_ATTRIBUTE = RequestDispatcher.FORWARD_SERVLET_PATH; + public static final String FORWARD_PATH_INFO_ATTRIBUTE = RequestDispatcher.FORWARD_PATH_INFO; + public static final String FORWARD_QUERY_STRING_ATTRIBUTE = RequestDispatcher.FORWARD_QUERY_STRING; /** * Default character encoding to use when request.getCharacterEncoding @@ -367,6 +369,7 @@ public static WebEnvironment getWebEnvironment(ServletContext sc, String attrNam * @return the decoded String * @see #DEFAULT_CHARACTER_ENCODING * @see jakarta.servlet.ServletRequest#getCharacterEncoding + * @see java.net.URLDecoder#decode(String, java.nio.charset.Charset) * @see java.net.URLDecoder#decode(String, String) * @see java.net.URLDecoder#decode(String) */ @@ -381,7 +384,7 @@ public static String decodeRequestString(HttpServletRequest request, String sour + "] with encoding '" + Encode.forHtml(enc) + "': falling back to platform default encoding; exception message: " + ex.getMessage()); } - return URLDecoder.decode(source); + return URLDecoder.decode(source, StandardCharsets.UTF_8); } } diff --git a/web/src/test/groovy/org/apache/shiro/web/filter/InvalidRequestFilterTest.groovy b/web/src/test/groovy/org/apache/shiro/web/filter/InvalidRequestFilterTest.groovy index ac5942186e..0252e3e57b 100644 --- a/web/src/test/groovy/org/apache/shiro/web/filter/InvalidRequestFilterTest.groovy +++ b/web/src/test/groovy/org/apache/shiro/web/filter/InvalidRequestFilterTest.groovy @@ -23,6 +23,7 @@ import org.apache.shiro.web.RestoreSystemProperties import org.junit.jupiter.api.Test import org.junit.jupiter.api.parallel.Isolated +import jakarta.servlet.RequestDispatcher import jakarta.servlet.http.HttpServletRequest import static org.easymock.EasyMock.expect @@ -245,8 +246,8 @@ class InvalidRequestFilterTest { expect(request.getRequestURI()).andReturn(requestUri) expect(request.getServletPath()).andReturn(servletPath).anyTimes() expect(request.getPathInfo()).andReturn(pathInfo).anyTimes() - expect(request.getAttribute("javax.servlet.include.servlet_path")).andReturn(servletPath) - expect(request.getAttribute("javax.servlet.include.path_info")).andReturn(pathInfo) + expect(request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH)).andReturn(servletPath) + expect(request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO)).andReturn(pathInfo) replay(request) return request } diff --git a/web/src/test/resources/log4j2-test.xml b/web/src/test/resources/log4j2-test.xml index 41b566dc6b..c809ee880c 100644 --- a/web/src/test/resources/log4j2-test.xml +++ b/web/src/test/resources/log4j2-test.xml @@ -49,7 +49,7 @@ - +