diff --git a/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java b/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java index ed452c6a46..eaf121023c 100644 --- a/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java +++ b/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java @@ -25,7 +25,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.Vector; import javax.sql.DataSource; @@ -51,7 +50,6 @@ import org.springframework.security.acls.sid.PrincipalSid; import org.springframework.security.acls.sid.Sid; import org.springframework.security.util.FieldUtils; import org.springframework.util.Assert; -import org.springframework.util.StringUtils; /** @@ -100,30 +98,30 @@ public final class BasicLookupStrategy implements LookupStrategy { private static String computeRepeatingSql(String repeatingSql, int requiredRepetitions) { Assert.isTrue(requiredRepetitions >= 1, "Must be => 1"); - String startSql = "select acl_object_identity.object_id_identity, " - + "acl_entry.ace_order, " - + "acl_object_identity.id as acl_id, " - + "acl_object_identity.parent_object, " - + "acl_object_identity.entries_inheriting, " - + "acl_entry.id as ace_id, " - + "acl_entry.mask, " - + "acl_entry.granting, " - + "acl_entry.audit_success, " - + "acl_entry.audit_failure, " - + "acl_sid.principal as ace_principal, " - + "acl_sid.sid as ace_sid, " - + "acli_sid.principal as acl_principal, " - + "acli_sid.sid as acl_sid, " - + "acl_class.class " - + "from acl_object_identity " - + "left join acl_sid acli_sid on acli_sid.id = acl_object_identity.owner_sid " - + "left join acl_class on acl_class.id = acl_object_identity.object_id_class " - + "left join acl_entry on acl_object_identity.id = acl_entry.acl_object_identity " - + "left join acl_sid on acl_entry.sid = acl_sid.id " - + "where ( "; + String startSql = "select acl_object_identity.object_id_identity, " + + "acl_entry.ace_order, " + + "acl_object_identity.id as acl_id, " + + "acl_object_identity.parent_object, " + + "acl_object_identity.entries_inheriting, " + + "acl_entry.id as ace_id, " + + "acl_entry.mask, " + + "acl_entry.granting, " + + "acl_entry.audit_success, " + + "acl_entry.audit_failure, " + + "acl_sid.principal as ace_principal, " + + "acl_sid.sid as ace_sid, " + + "acli_sid.principal as acl_principal, " + + "acli_sid.sid as acl_sid, " + + "acl_class.class " + + "from acl_object_identity " + + "left join acl_sid acli_sid on acli_sid.id = acl_object_identity.owner_sid " + + "left join acl_class on acl_class.id = acl_object_identity.object_id_class " + + "left join acl_entry on acl_object_identity.id = acl_entry.acl_object_identity " + + "left join acl_sid on acl_entry.sid = acl_sid.id " + + "where ( "; - String endSql = ") order by acl_object_identity.object_id_identity" - + " asc, acl_entry.ace_order asc"; + String endSql = ") order by acl_object_identity.object_id_identity" + + " asc, acl_entry.ace_order asc"; StringBuffer sqlStringBuffer = new StringBuffer(); sqlStringBuffer.append(startSql); @@ -148,11 +146,8 @@ public final class BasicLookupStrategy implements LookupStrategy { * @param inputMap the unconverted AclImpls * @param currentIdentity the currentAcl that we wish to convert (this may be * - * @return - * - * @throws IllegalStateException DOCUMENT ME! */ - private AclImpl convert(Map inputMap, Long currentIdentity) { + private AclImpl convert(Map inputMap, Long currentIdentity) { Assert.notEmpty(inputMap, "InputMap required"); Assert.notNull(currentIdentity, "CurrentIdentity required"); @@ -177,31 +172,31 @@ public final class BasicLookupStrategy implements LookupStrategy { // Copy the "aces" from the input to the destination Field fieldAces = FieldUtils.getField(AclImpl.class, "aces"); Field fieldAcl = FieldUtils.getField(AccessControlEntryImpl.class, "acl"); - + try { - fieldAces.setAccessible(true); + fieldAces.setAccessible(true); fieldAcl.setAccessible(true); // Obtain the "aces" from the input ACL Iterator i = ((List) fieldAces.get(inputAcl)).iterator(); // Create a list in which to store the "aces" for the "result" AclImpl instance - List acesNew = new ArrayList(); + List acesNew = new ArrayList(); // Iterate over the "aces" input and replace each nested AccessControlEntryImpl.getAcl() with the new "result" AclImpl instance // This ensures StubAclParent instances are removed, as per SEC-951 while(i.hasNext()) { - AccessControlEntryImpl ace = (AccessControlEntryImpl) i.next(); - fieldAcl.set(ace, result); - acesNew.add(ace); + AccessControlEntryImpl ace = (AccessControlEntryImpl) i.next(); + fieldAcl.set(ace, result); + acesNew.add(ace); } - + // Finally, now that the "aces" have been converted to have the "result" AclImpl instance, modify the "result" AclImpl instance fieldAces.set(result, acesNew); } catch (IllegalAccessException ex) { throw new IllegalStateException("Could not obtain or set AclImpl or AccessControlEntryImpl fields"); } - + return result; } @@ -214,10 +209,8 @@ public final class BasicLookupStrategy implements LookupStrategy { * @param rs the ResultSet focused on a current row * * @throws SQLException if something goes wrong converting values - * @throws IllegalStateException DOCUMENT ME! */ - private void convertCurrentResultIntoObject(Map acls, ResultSet rs) - throws SQLException { + private void convertCurrentResultIntoObject(Map acls, ResultSet rs) throws SQLException { Long id = new Long(rs.getLong("acl_id")); // If we already have an ACL for this ID, just create the ACE @@ -262,7 +255,7 @@ public final class BasicLookupStrategy implements LookupStrategy { } int mask = rs.getInt("mask"); - Permission permission = convertMaskIntoPermission(mask); + Permission permission = convertMaskIntoPermission(mask); boolean granting = rs.getBoolean("granting"); boolean auditSuccess = rs.getBoolean("audit_success"); boolean auditFailure = rs.getBoolean("audit_failure"); @@ -271,11 +264,11 @@ public final class BasicLookupStrategy implements LookupStrategy { auditSuccess, auditFailure); Field acesField = FieldUtils.getField(AclImpl.class, "aces"); - List aces; + List aces; try { acesField.setAccessible(true); - aces = (List) acesField.get(acl); + aces = (List) acesField.get(acl); } catch (IllegalAccessException ex) { throw new IllegalStateException("Could not obtain AclImpl.ace field: cause[" + ex.getMessage() + "]"); } @@ -287,23 +280,20 @@ public final class BasicLookupStrategy implements LookupStrategy { } } - protected Permission convertMaskIntoPermission(int mask) { - return BasePermission.buildFromMask(mask); - } + protected Permission convertMaskIntoPermission(int mask) { + return BasePermission.buildFromMask(mask); + } /** * Looks up a batch of ObjectIdentitys directly from the database.

The caller is responsible * for optimization issues, such as selecting the identities to lookup, ensuring the cache doesn't contain them * already, and adding the returned elements to the cache etc.

- *

This subclass is required to return fully valid Acls, including properly-configured + *

+ * This subclass is required to return fully valid Acls, including properly-configured * parent ACLs.

* - * @param objectIdentities DOCUMENT ME! - * @param sids DOCUMENT ME! - * - * @return DOCUMENT ME! */ - private Map lookupObjectIdentities(final ObjectIdentity[] objectIdentities, Sid[] sids) { + private Map lookupObjectIdentities(final ObjectIdentity[] objectIdentities, Sid[] sids) { Assert.notEmpty(objectIdentities, "Must provide identities to lookup"); final Map acls = new HashMap(); // contains Acls with StubAclParents @@ -331,14 +321,14 @@ public final class BasicLookupStrategy implements LookupStrategy { } } }, new ProcessResultSet(acls, sids)); - + // Lookup the parents, now that our JdbcTemplate has released the database connection (SEC-547) if (parentsToLookup.size() > 0) { - lookupPrimaryKeys(acls, parentsToLookup, sids); + lookupPrimaryKeys(acls, parentsToLookup, sids); } // Finally, convert our "acls" containing StubAclParents into true Acls - Map resultMap = new HashMap(); + Map resultMap = new HashMap(); Iterator iter = acls.values().iterator(); while (iter.hasNext()) { @@ -380,10 +370,10 @@ public final class BasicLookupStrategy implements LookupStrategy { } } }, new ProcessResultSet(acls, sids)); - + // Lookup the parents, now that our JdbcTemplate has released the database connection (SEC-547) if (parentsToLookup.size() > 0) { - lookupPrimaryKeys(acls, parentsToLookup, sids); + lookupPrimaryKeys(acls, parentsToLookup, sids); } } @@ -400,29 +390,29 @@ public final class BasicLookupStrategy implements LookupStrategy { * @return a Map where keys represent the {@link ObjectIdentity} of the located {@link Acl} and values * are the located {@link Acl} (never null although some entries may be missing; this method * should not throw {@link NotFoundException}, as a chain of {@link LookupStrategy}s may be used - * to automatically create entries if required) + * to automatically create entries if required) */ - public Map readAclsById(ObjectIdentity[] objects, Sid[] sids) { + public Map readAclsById(ObjectIdentity[] objects, Sid[] sids) { Assert.isTrue(batchSize >= 1, "BatchSize must be >= 1"); Assert.notEmpty(objects, "Objects to lookup required"); // Map - Map result = new HashMap(); // contains FULLY loaded Acl objects + Map result = new HashMap(); // contains FULLY loaded Acl objects - Set currentBatchToLoad = new HashSet(); // contains ObjectIdentitys + Set currentBatchToLoad = new HashSet(); // contains ObjectIdentitys for (int i = 0; i < objects.length; i++) { - boolean aclFound = false; + boolean aclFound = false; - // Check we don't already have this ACL in the results + // Check we don't already have this ACL in the results if (result.containsKey(objects[i])) { aclFound = true; } // Check cache for the present ACL entry if (!aclFound) { - Acl acl = aclCache.getFromCache(objects[i]); - + Acl acl = aclCache.getFromCache(objects[i]); + // Ensure any cached element supports all the requested SIDs // (they should always, as our base impl doesn't filter on SID) if (acl != null) { @@ -436,7 +426,7 @@ public final class BasicLookupStrategy implements LookupStrategy { } } } - + // Load the ACL from the database if (!aclFound) { currentBatchToLoad.add(objects[i]); @@ -444,21 +434,21 @@ public final class BasicLookupStrategy implements LookupStrategy { // Is it time to load from JDBC the currentBatchToLoad? if ((currentBatchToLoad.size() == this.batchSize) || ((i + 1) == objects.length)) { - if (currentBatchToLoad.size() > 0) { - Map loadedBatch = lookupObjectIdentities((ObjectIdentity[]) currentBatchToLoad.toArray(new ObjectIdentity[] {}), sids); + if (currentBatchToLoad.size() > 0) { + Map loadedBatch = lookupObjectIdentities(currentBatchToLoad.toArray(new ObjectIdentity[] {}), sids); - // Add loaded batch (all elements 100% initialized) to results - result.putAll(loadedBatch); - - // Add the loaded batch to the cache - Iterator loadedAclIterator = loadedBatch.values().iterator(); - - while (loadedAclIterator.hasNext()) { - aclCache.putInCache((AclImpl) loadedAclIterator.next()); - } - - currentBatchToLoad.clear(); - } + // Add loaded batch (all elements 100% initialized) to results + result.putAll(loadedBatch); + + // Add the loaded batch to the cache + Iterator loadedAclIterator = loadedBatch.values().iterator(); + + while (loadedAclIterator.hasNext()) { + aclCache.putInCache((AclImpl) loadedAclIterator.next()); + } + + currentBatchToLoad.clear(); + } } } @@ -493,7 +483,7 @@ public final class BasicLookupStrategy implements LookupStrategy { * @throws DataAccessException */ public Object extractData(ResultSet rs) throws SQLException, DataAccessException { - Set parentIdsToLookup = new HashSet(); // Set of parent_id Longs + Set parentIdsToLookup = new HashSet(); // Set of parent_id Longs while (rs.next()) { // Convert current row into an Acl (albeit with a StubAclParent) diff --git a/acl/src/main/java/org/springframework/security/acls/jdbc/LookupStrategy.java b/acl/src/main/java/org/springframework/security/acls/jdbc/LookupStrategy.java index 9d5fb8d150..2794d83bd8 100644 --- a/acl/src/main/java/org/springframework/security/acls/jdbc/LookupStrategy.java +++ b/acl/src/main/java/org/springframework/security/acls/jdbc/LookupStrategy.java @@ -14,6 +14,7 @@ */ package org.springframework.security.acls.jdbc; +import org.springframework.security.acls.Acl; import org.springframework.security.acls.NotFoundException; import org.springframework.security.acls.objectidentity.ObjectIdentity; import org.springframework.security.acls.sid.Sid; @@ -23,7 +24,7 @@ import java.util.Map; /** * Performs lookups for {@link org.springframework.security.acls.AclService}. - * + * * @author Ben Alex * @version $Id$ */ @@ -40,7 +41,7 @@ public interface LookupStrategy { * @return a Map where keys represent the {@link ObjectIdentity} of the located {@link Acl} and values * are the located {@link Acl} (never null although some entries may be missing; this method * should not throw {@link NotFoundException}, as a chain of {@link LookupStrategy}s may be used - * to automatically create entries if required) + * to automatically create entries if required) */ - Map readAclsById(ObjectIdentity[] objects, Sid[] sids); + Map readAclsById(ObjectIdentity[] objects, Sid[] sids); } diff --git a/acl/src/main/java/org/springframework/security/afterinvocation/AbstractAclProvider.java b/acl/src/main/java/org/springframework/security/afterinvocation/AbstractAclProvider.java index f83981c803..e487d0d14b 100644 --- a/acl/src/main/java/org/springframework/security/afterinvocation/AbstractAclProvider.java +++ b/acl/src/main/java/org/springframework/security/afterinvocation/AbstractAclProvider.java @@ -120,7 +120,7 @@ public abstract class AbstractAclProvider implements AfterInvocationProvider { * * @return always true */ - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { return true; } } diff --git a/cas/src/main/java/org/springframework/security/providers/cas/CasAuthenticationProvider.java b/cas/src/main/java/org/springframework/security/providers/cas/CasAuthenticationProvider.java index baa0b93d7a..ed2c6b2f02 100644 --- a/cas/src/main/java/org/springframework/security/providers/cas/CasAuthenticationProvider.java +++ b/cas/src/main/java/org/springframework/security/providers/cas/CasAuthenticationProvider.java @@ -202,7 +202,7 @@ public class CasAuthenticationProvider implements AuthenticationProvider, Initia this.ticketValidator = ticketValidator; } - public boolean supports(final Class authentication) { + public boolean supports(final Class authentication) { if (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)) { return true; } else if (CasAuthenticationToken.class.isAssignableFrom(authentication)) { diff --git a/core/src/main/java/org/springframework/security/AuthenticationTrustResolverImpl.java b/core/src/main/java/org/springframework/security/AuthenticationTrustResolverImpl.java index bdf4ec95ac..f8c68e3f53 100644 --- a/core/src/main/java/org/springframework/security/AuthenticationTrustResolverImpl.java +++ b/core/src/main/java/org/springframework/security/AuthenticationTrustResolverImpl.java @@ -20,10 +20,12 @@ import org.springframework.security.providers.rememberme.RememberMeAuthenticatio /** - * Basic implementation of {@link AuthenticationTrustResolver}.

Makes trust decisions based on whether the passed - * Authentication is an instance of a defined class.

- *

If {@link #anonymousClass} or {@link #rememberMeClass} is null, the corresponding method will - * always return false.

+ * Basic implementation of {@link AuthenticationTrustResolver}. + *

+ * Makes trust decisions based on whether the passed Authentication is an instance of a defined class. + *

+ * If {@link #anonymousClass} or {@link #rememberMeClass} is null, the corresponding method will + * always return false. * * @author Ben Alex * @version $Id$ @@ -31,16 +33,16 @@ import org.springframework.security.providers.rememberme.RememberMeAuthenticatio public class AuthenticationTrustResolverImpl implements AuthenticationTrustResolver { //~ Instance fields ================================================================================================ - private Class anonymousClass = AnonymousAuthenticationToken.class; - private Class rememberMeClass = RememberMeAuthenticationToken.class; + private Class anonymousClass = AnonymousAuthenticationToken.class; + private Class rememberMeClass = RememberMeAuthenticationToken.class; //~ Methods ======================================================================================================== - public Class getAnonymousClass() { + Class getAnonymousClass() { return anonymousClass; } - public Class getRememberMeClass() { + Class getRememberMeClass() { return rememberMeClass; } @@ -60,11 +62,11 @@ public class AuthenticationTrustResolverImpl implements AuthenticationTrustResol return rememberMeClass.isAssignableFrom(authentication.getClass()); } - public void setAnonymousClass(Class anonymousClass) { + public void setAnonymousClass(Class anonymousClass) { this.anonymousClass = anonymousClass; } - public void setRememberMeClass(Class rememberMeClass) { + public void setRememberMeClass(Class rememberMeClass) { this.rememberMeClass = rememberMeClass; } } diff --git a/core/src/main/java/org/springframework/security/ConfigAttributeDefinition.java b/core/src/main/java/org/springframework/security/ConfigAttributeDefinition.java index b92f5c4710..47121fba48 100644 --- a/core/src/main/java/org/springframework/security/ConfigAttributeDefinition.java +++ b/core/src/main/java/org/springframework/security/ConfigAttributeDefinition.java @@ -38,6 +38,7 @@ import org.springframework.util.Assert; * @author Ben Alex * @version $Id$ */ +@SuppressWarnings("all") public class ConfigAttributeDefinition implements Serializable { public static final ConfigAttributeDefinition NO_ATTRIBUTES = new ConfigAttributeDefinition(); diff --git a/core/src/main/java/org/springframework/security/afterinvocation/AfterInvocationProvider.java b/core/src/main/java/org/springframework/security/afterinvocation/AfterInvocationProvider.java index fcd7ccf663..38d93db50b 100644 --- a/core/src/main/java/org/springframework/security/afterinvocation/AfterInvocationProvider.java +++ b/core/src/main/java/org/springframework/security/afterinvocation/AfterInvocationProvider.java @@ -56,5 +56,5 @@ public interface AfterInvocationProvider { * * @return true if the implementation can process the indicated class */ - boolean supports(Class clazz); + boolean supports(Class clazz); } diff --git a/core/src/main/java/org/springframework/security/afterinvocation/BasicAclEntryAfterInvocationCollectionFilteringProvider.java b/core/src/main/java/org/springframework/security/afterinvocation/BasicAclEntryAfterInvocationCollectionFilteringProvider.java index ca5c1e2621..bffed3b5c0 100644 --- a/core/src/main/java/org/springframework/security/afterinvocation/BasicAclEntryAfterInvocationCollectionFilteringProvider.java +++ b/core/src/main/java/org/springframework/security/afterinvocation/BasicAclEntryAfterInvocationCollectionFilteringProvider.java @@ -226,7 +226,7 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProvider implements * * @return always true */ - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { return true; } } diff --git a/core/src/main/java/org/springframework/security/afterinvocation/BasicAclEntryAfterInvocationProvider.java b/core/src/main/java/org/springframework/security/afterinvocation/BasicAclEntryAfterInvocationProvider.java index 8aceb21a4c..cd00f0b075 100644 --- a/core/src/main/java/org/springframework/security/afterinvocation/BasicAclEntryAfterInvocationProvider.java +++ b/core/src/main/java/org/springframework/security/afterinvocation/BasicAclEntryAfterInvocationProvider.java @@ -210,7 +210,7 @@ public class BasicAclEntryAfterInvocationProvider implements AfterInvocationProv * * @return always true */ - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { return true; } } diff --git a/core/src/main/java/org/springframework/security/annotation/Jsr250Voter.java b/core/src/main/java/org/springframework/security/annotation/Jsr250Voter.java index 56bf9c95e8..65c09e43ba 100644 --- a/core/src/main/java/org/springframework/security/annotation/Jsr250Voter.java +++ b/core/src/main/java/org/springframework/security/annotation/Jsr250Voter.java @@ -32,7 +32,7 @@ public class Jsr250Voter implements AccessDecisionVoter { * @param clazz the class. * @return true */ - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { return true; } diff --git a/core/src/main/java/org/springframework/security/concurrent/SessionRegistryImpl.java b/core/src/main/java/org/springframework/security/concurrent/SessionRegistryImpl.java index 57fec416ab..fb29f5a867 100644 --- a/core/src/main/java/org/springframework/security/concurrent/SessionRegistryImpl.java +++ b/core/src/main/java/org/springframework/security/concurrent/SessionRegistryImpl.java @@ -15,27 +15,24 @@ package org.springframework.security.concurrent; -import org.springframework.security.ui.session.HttpSessionDestroyedEvent; - -import org.springframework.context.ApplicationEvent; -import org.springframework.context.ApplicationListener; - -import org.springframework.util.Assert; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpSession; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.context.ApplicationEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.security.ui.session.HttpSessionDestroyedEvent; +import org.springframework.util.Assert; + /** * Base implementation of {@link org.springframework.security.concurrent.SessionRegistry} * which also listens for {@link org.springframework.security.ui.session.HttpSessionDestroyedEvent}s @@ -56,95 +53,96 @@ public class SessionRegistryImpl implements SessionRegistry, ApplicationListener // ~ Instance fields =============================================================================================== - private Map principals = Collections.synchronizedMap(new HashMap()); // - private Map sessionIds = Collections.synchronizedMap(new HashMap()); // + /** */ + private Map> principals = Collections.synchronizedMap(new HashMap>()); + /** */ + private Map sessionIds = Collections.synchronizedMap(new HashMap()); - // ~ Methods ======================================================================================================= + // ~ Methods ======================================================================================================= - public Object[] getAllPrincipals() { - return principals.keySet().toArray(); - } + public Object[] getAllPrincipals() { + return principals.keySet().toArray(); + } - public SessionInformation[] getAllSessions(Object principal, boolean includeExpiredSessions) { - Set sessionsUsedByPrincipal = (Set) principals.get(principal); + public SessionInformation[] getAllSessions(Object principal, boolean includeExpiredSessions) { + Set sessionsUsedByPrincipal = principals.get(principal); if (sessionsUsedByPrincipal == null) { - return null; - } + return null; + } - List list = new ArrayList(); + List list = new ArrayList(); synchronized (sessionsUsedByPrincipal) { - for (Iterator iter = sessionsUsedByPrincipal.iterator(); iter.hasNext();) { - String sessionId = (String) iter.next(); - SessionInformation sessionInformation = getSessionInformation(sessionId); + for (String sessionId : sessionsUsedByPrincipal) { + SessionInformation sessionInformation = getSessionInformation(sessionId); if (sessionInformation == null) { continue; } if (includeExpiredSessions || !sessionInformation.isExpired()) { - list.add(sessionInformation); - } - } - } + list.add(sessionInformation); + } + } + } - return (SessionInformation[]) list.toArray(new SessionInformation[] {}); - } + return (SessionInformation[]) list.toArray(new SessionInformation[0]); + } - public SessionInformation getSessionInformation(String sessionId) { - Assert.hasText(sessionId, "SessionId required as per interface contract"); + public SessionInformation getSessionInformation(String sessionId) { + Assert.hasText(sessionId, "SessionId required as per interface contract"); - return (SessionInformation) sessionIds.get(sessionId); - } + return (SessionInformation) sessionIds.get(sessionId); + } - public void onApplicationEvent(ApplicationEvent event) { - if (event instanceof HttpSessionDestroyedEvent) { - String sessionId = ((HttpSession) event.getSource()).getId(); - removeSessionInformation(sessionId); - } - } + public void onApplicationEvent(ApplicationEvent event) { + if (event instanceof HttpSessionDestroyedEvent) { + String sessionId = ((HttpSession) event.getSource()).getId(); + removeSessionInformation(sessionId); + } + } - public void refreshLastRequest(String sessionId) { - Assert.hasText(sessionId, "SessionId required as per interface contract"); + public void refreshLastRequest(String sessionId) { + Assert.hasText(sessionId, "SessionId required as per interface contract"); - SessionInformation info = getSessionInformation(sessionId); + SessionInformation info = getSessionInformation(sessionId); - if (info != null) { - info.refreshLastRequest(); - } - } + if (info != null) { + info.refreshLastRequest(); + } + } - public synchronized void registerNewSession(String sessionId, Object principal) { - Assert.hasText(sessionId, "SessionId required as per interface contract"); - Assert.notNull(principal, "Principal required as per interface contract"); + public synchronized void registerNewSession(String sessionId, Object principal) { + Assert.hasText(sessionId, "SessionId required as per interface contract"); + Assert.notNull(principal, "Principal required as per interface contract"); if (logger.isDebugEnabled()) { logger.debug("Registering session " + sessionId +", for principal " + principal); } if (getSessionInformation(sessionId) != null) { - removeSessionInformation(sessionId); - } + removeSessionInformation(sessionId); + } sessionIds.put(sessionId, new SessionInformation(principal, sessionId, new Date())); - Set sessionsUsedByPrincipal = (Set) principals.get(principal); + Set sessionsUsedByPrincipal = principals.get(principal); - if (sessionsUsedByPrincipal == null) { - sessionsUsedByPrincipal = Collections.synchronizedSet(new HashSet(4)); + if (sessionsUsedByPrincipal == null) { + sessionsUsedByPrincipal = Collections.synchronizedSet(new HashSet(4)); principals.put(principal, sessionsUsedByPrincipal); } - sessionsUsedByPrincipal.add(sessionId); - } + sessionsUsedByPrincipal.add(sessionId); + } - public void removeSessionInformation(String sessionId) { - Assert.hasText(sessionId, "SessionId required as per interface contract"); + public void removeSessionInformation(String sessionId) { + Assert.hasText(sessionId, "SessionId required as per interface contract"); - SessionInformation info = getSessionInformation(sessionId); + SessionInformation info = getSessionInformation(sessionId); - if (info == null) { + if (info == null) { return; } @@ -154,7 +152,7 @@ public class SessionRegistryImpl implements SessionRegistry, ApplicationListener sessionIds.remove(sessionId); - Set sessionsUsedByPrincipal = (Set) principals.get(info.getPrincipal()); + Set sessionsUsedByPrincipal = principals.get(info.getPrincipal()); if (sessionsUsedByPrincipal == null) { return; @@ -163,7 +161,7 @@ public class SessionRegistryImpl implements SessionRegistry, ApplicationListener if (logger.isDebugEnabled()) { logger.debug("Removing session " + sessionId + " from principal's set of registered sessions"); } - + synchronized (sessionsUsedByPrincipal) { sessionsUsedByPrincipal.remove(sessionId); @@ -175,5 +173,5 @@ public class SessionRegistryImpl implements SessionRegistry, ApplicationListener principals.remove(info.getPrincipal()); } } - } + } } diff --git a/core/src/main/java/org/springframework/security/config/NamespaceAuthenticationManager.java b/core/src/main/java/org/springframework/security/config/NamespaceAuthenticationManager.java index 0ff39b7ea2..25434070b7 100644 --- a/core/src/main/java/org/springframework/security/config/NamespaceAuthenticationManager.java +++ b/core/src/main/java/org/springframework/security/config/NamespaceAuthenticationManager.java @@ -6,54 +6,56 @@ import java.util.List; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.security.providers.AuthenticationProvider; import org.springframework.security.providers.ProviderManager; import org.springframework.util.Assert; /** * Extended version of {@link ProviderManager the default authentication manager} which lazily initializes - * the list of {@link AuthenticationProvider}s. This prevents some of the issues that have occurred with + * the list of {@link AuthenticationProvider}s. This prevents some of the issues that have occurred with * namespace configuration where early instantiation of a security interceptor has caused the AuthenticationManager - * and thus dependent beans (typically UserDetailsService implementations or DAOs) to be initialized too early. - * + * and thus dependent beans (typically UserDetailsService implementations or DAOs) to be initialized too early. + * * @author Luke Taylor * @since 2.0.4 */ public class NamespaceAuthenticationManager extends ProviderManager implements BeanFactoryAware { - BeanFactory beanFactory; - List providerBeanNames; - - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = beanFactory; - } + BeanFactory beanFactory; + List providerBeanNames; - public void afterPropertiesSet() throws Exception { - Assert.notNull(providerBeanNames, "provideBeanNames has not been set"); - Assert.notEmpty(providerBeanNames, "No authentication providers were found in the application context"); - - super.afterPropertiesSet(); - } + public void setBeanFactory(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + } - /** - * Overridden to lazily-initialize the list of providers on first use. - */ - public List getProviders() { - // We use the names array to determine whether the list has been set yet. - if (providerBeanNames != null) { - List providers = new ArrayList(); - Iterator beanNames = providerBeanNames.iterator(); - - while (beanNames.hasNext()) { - providers.add(beanFactory.getBean((String) beanNames.next())); - } - providerBeanNames = null; - - setProviders(providers); - } - - return super.getProviders(); - } + public void afterPropertiesSet() throws Exception { + Assert.notNull(providerBeanNames, "provideBeanNames has not been set"); + Assert.notEmpty(providerBeanNames, "No authentication providers were found in the application context"); - public void setProviderBeanNames(List provideBeanNames) { - this.providerBeanNames = provideBeanNames; - } + super.afterPropertiesSet(); + } + + /** + * Overridden to lazily-initialize the list of providers on first use. + */ + public List getProviders() { + // We use the names array to determine whether the list has been set yet. + if (providerBeanNames != null) { + ArrayList providers = new ArrayList(); + Iterator beanNames = providerBeanNames.iterator(); + + while (beanNames.hasNext()) { + providers.add((AuthenticationProvider) beanFactory.getBean(beanNames.next())); + } + providerBeanNames = null; + providers.trimToSize(); + + setProviders(providers); + } + + return super.getProviders(); + } + + public void setProviderBeanNames(List provideBeanNames) { + this.providerBeanNames = provideBeanNames; + } } diff --git a/core/src/main/java/org/springframework/security/context/HttpSessionContextIntegrationFilter.java b/core/src/main/java/org/springframework/security/context/HttpSessionContextIntegrationFilter.java index cad6a63bc4..79021e0912 100644 --- a/core/src/main/java/org/springframework/security/context/HttpSessionContextIntegrationFilter.java +++ b/core/src/main/java/org/springframework/security/context/HttpSessionContextIntegrationFilter.java @@ -106,7 +106,7 @@ public class HttpSessionContextIntegrationFilter extends SpringSecurityFilter im //~ Instance fields ================================================================================================ - private Class contextClass = SecurityContextImpl.class; + private Class contextClass = SecurityContextImpl.class; private Object contextObject; @@ -152,8 +152,8 @@ public class HttpSessionContextIntegrationFilter extends SpringSecurityFilter im * method. */ private boolean cloneFromHttpSession = false; - - private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl(); + + private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl(); public boolean isCloneFromHttpSession() { return cloneFromHttpSession; @@ -180,7 +180,7 @@ public class HttpSessionContextIntegrationFilter extends SpringSecurityFilter im throw new IllegalArgumentException( "If using forceEagerSessionCreation, you must set allowSessionCreation to also be true"); } - + contextObject = generateNewContext(); } @@ -327,7 +327,7 @@ public class HttpSessionContextIntegrationFilter extends SpringSecurityFilter im /** * Stores the supplied security context in the session (if available) and if it has changed since it was * set at the start of the request. If the AuthenticationTrustResolver identifies the current user as - * anonymous, then the context will not be stored. + * anonymous, then the context will not be stored. * * @param securityContext the context object obtained from the SecurityContextHolder after the request has * been processed by the filter chain. SecurityContextHolder.getContext() cannot be used to obtain @@ -363,13 +363,13 @@ public class HttpSessionContextIntegrationFilter extends SpringSecurityFilter im + "(because the allowSessionCreation property is false) - SecurityContext thus not " + "stored for next request"); } - } else if (!contextObject.equals(securityContext)) { + } else if (!contextObject.equals(securityContext)) { if (logger.isDebugEnabled()) { logger.debug("HttpSession being created as SecurityContextHolder contents are non-default"); } httpSession = safeGetSession(request, true); - + } else { if (logger.isDebugEnabled()) { logger.debug("HttpSession is null, but SecurityContextHolder has not changed from default: ' " @@ -383,28 +383,28 @@ public class HttpSessionContextIntegrationFilter extends SpringSecurityFilter im // If HttpSession exists, store current SecurityContextHolder contents but only if // the SecurityContext has actually changed (see JIRA SEC-37) if (httpSession != null && securityContext.hashCode() != contextHashBeforeChainExecution) { - // See SEC-766 - if (authenticationTrustResolver.isAnonymous(securityContext.getAuthentication())) { + // See SEC-766 + if (authenticationTrustResolver.isAnonymous(securityContext.getAuthentication())) { if (logger.isDebugEnabled()) { logger.debug("SecurityContext contents are anonymous - context will not be stored in HttpSession. "); } - } else { - httpSession.setAttribute(SPRING_SECURITY_CONTEXT_KEY, securityContext); - - if (logger.isDebugEnabled()) { - logger.debug("SecurityContext stored to HttpSession: '" + securityContext + "'"); - } - } + } else { + httpSession.setAttribute(SPRING_SECURITY_CONTEXT_KEY, securityContext); + + if (logger.isDebugEnabled()) { + logger.debug("SecurityContext stored to HttpSession: '" + securityContext + "'"); + } + } } } - + private HttpSession safeGetSession(HttpServletRequest request, boolean allowCreate) { try { return request.getSession(allowCreate); } catch (IllegalStateException ignored) { return null; - } + } } public SecurityContext generateNewContext() throws ServletException { @@ -427,10 +427,11 @@ public class HttpSessionContextIntegrationFilter extends SpringSecurityFilter im this.allowSessionCreation = allowSessionCreation; } - protected Class getContextClass() { + protected Class getContextClass() { return contextClass; } + @SuppressWarnings("unchecked") public void setContextClass(Class secureContext) { this.contextClass = secureContext; } diff --git a/core/src/main/java/org/springframework/security/context/InheritableThreadLocalSecurityContextHolderStrategy.java b/core/src/main/java/org/springframework/security/context/InheritableThreadLocalSecurityContextHolderStrategy.java index 039668c17e..6cf50d7acb 100644 --- a/core/src/main/java/org/springframework/security/context/InheritableThreadLocalSecurityContextHolderStrategy.java +++ b/core/src/main/java/org/springframework/security/context/InheritableThreadLocalSecurityContextHolderStrategy.java @@ -31,7 +31,7 @@ import org.springframework.util.Assert; public class InheritableThreadLocalSecurityContextHolderStrategy implements SecurityContextHolderStrategy { //~ Static fields/initializers ===================================================================================== - private static ThreadLocal contextHolder = new InheritableThreadLocal(); + private static ThreadLocal contextHolder = new InheritableThreadLocal(); //~ Methods ======================================================================================================== @@ -44,7 +44,7 @@ public class InheritableThreadLocalSecurityContextHolderStrategy implements Secu contextHolder.set(new SecurityContextImpl()); } - return (SecurityContext) contextHolder.get(); + return contextHolder.get(); } public void setContext(SecurityContext context) { diff --git a/core/src/main/java/org/springframework/security/context/ThreadLocalSecurityContextHolderStrategy.java b/core/src/main/java/org/springframework/security/context/ThreadLocalSecurityContextHolderStrategy.java index c54d47fab4..a4ef580798 100644 --- a/core/src/main/java/org/springframework/security/context/ThreadLocalSecurityContextHolderStrategy.java +++ b/core/src/main/java/org/springframework/security/context/ThreadLocalSecurityContextHolderStrategy.java @@ -31,7 +31,7 @@ import org.springframework.util.Assert; public class ThreadLocalSecurityContextHolderStrategy implements SecurityContextHolderStrategy { //~ Static fields/initializers ===================================================================================== - private static ThreadLocal contextHolder = new ThreadLocal(); + private static ThreadLocal contextHolder = new ThreadLocal(); //~ Methods ======================================================================================================== @@ -44,7 +44,7 @@ public class ThreadLocalSecurityContextHolderStrategy implements SecurityContext contextHolder.set(new SecurityContextImpl()); } - return (SecurityContext) contextHolder.get(); + return contextHolder.get(); } public void setContext(SecurityContext context) { diff --git a/core/src/main/java/org/springframework/security/expression/DefaultSecurityExpressionHandler.java b/core/src/main/java/org/springframework/security/expression/DefaultSecurityExpressionHandler.java index 8665d89691..36e74779c3 100644 --- a/core/src/main/java/org/springframework/security/expression/DefaultSecurityExpressionHandler.java +++ b/core/src/main/java/org/springframework/security/expression/DefaultSecurityExpressionHandler.java @@ -1,9 +1,9 @@ package org.springframework.security.expression; import java.lang.reflect.Array; +import java.util.ArrayList; import java.util.Collection; -import java.util.HashSet; -import java.util.Set; +import java.util.List; import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; @@ -49,9 +49,10 @@ public class DefaultSecurityExpressionHandler implements SecurityExpressionHandl return ctx; } + @SuppressWarnings("unchecked") public Object filter(Object filterTarget, Expression filterExpression, EvaluationContext ctx) { SecurityExpressionRoot rootObject = (SecurityExpressionRoot) ctx.getRootContextObject(); - Set removeList = new HashSet(); + List retainList; if (logger.isDebugEnabled()) { logger.debug("Filtering with expression: " + filterExpression.getExpressionString()); @@ -59,6 +60,7 @@ public class DefaultSecurityExpressionHandler implements SecurityExpressionHandl if (filterTarget instanceof Collection) { Collection collection = (Collection)filterTarget; + retainList = new ArrayList(collection.size()); if (logger.isDebugEnabled()) { logger.debug("Filtering collection with " + collection.size() + " elements"); @@ -66,24 +68,24 @@ public class DefaultSecurityExpressionHandler implements SecurityExpressionHandl for (Object filterObject : (Collection)filterTarget) { rootObject.setFilterObject(filterObject); - if (!ExpressionUtils.evaluateAsBoolean(filterExpression, ctx)) { - removeList.add(filterObject); + if (ExpressionUtils.evaluateAsBoolean(filterExpression, ctx)) { + retainList.add(filterObject); } } if (logger.isDebugEnabled()) { - logger.debug("Removing elements: " + removeList); + logger.debug("Retaining elements: " + retainList); } - for(Object toRemove : removeList) { - ((Collection)filterTarget).remove(toRemove); - } + collection.clear(); + collection.addAll(retainList); return filterTarget; } if (filterTarget.getClass().isArray()) { Object[] array = (Object[])filterTarget; + retainList = new ArrayList(array.length); if (logger.isDebugEnabled()) { logger.debug("Filtering collection with " + array.length + " elements"); @@ -92,21 +94,19 @@ public class DefaultSecurityExpressionHandler implements SecurityExpressionHandl for (int i = 0; i < array.length; i++) { rootObject.setFilterObject(array[i]); - if (!ExpressionUtils.evaluateAsBoolean(filterExpression, ctx)) { - removeList.add(array[i]); + if (ExpressionUtils.evaluateAsBoolean(filterExpression, ctx)) { + retainList.add(array[i]); } } if (logger.isDebugEnabled()) { - logger.debug("Removing elements: " + removeList); + logger.debug("Retaining elements: " + retainList); } Object[] filtered = (Object[]) Array.newInstance(filterTarget.getClass().getComponentType(), - array.length - removeList.size()); - for (int i = 0, j = 0; i < array.length; i++) { - if (!removeList.contains(array[i])) { - filtered[j++] = array[i]; - } + retainList.size()); + for (int i = 0; i < retainList.size(); i++) { + filtered[i] = retainList.get(i); } return filtered; diff --git a/core/src/main/java/org/springframework/security/expression/support/MethodExpressionAfterInvocationProvider.java b/core/src/main/java/org/springframework/security/expression/support/MethodExpressionAfterInvocationProvider.java index a3533fad03..bf1d829495 100644 --- a/core/src/main/java/org/springframework/security/expression/support/MethodExpressionAfterInvocationProvider.java +++ b/core/src/main/java/org/springframework/security/expression/support/MethodExpressionAfterInvocationProvider.java @@ -86,7 +86,7 @@ public class MethodExpressionAfterInvocationProvider implements AfterInvocationP return attribute instanceof PostInvocationExpressionAttribute; } - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { return clazz.isAssignableFrom(MethodInvocation.class); } diff --git a/core/src/main/java/org/springframework/security/expression/support/MethodExpressionVoter.java b/core/src/main/java/org/springframework/security/expression/support/MethodExpressionVoter.java index 0ce4648d25..30a1585702 100644 --- a/core/src/main/java/org/springframework/security/expression/support/MethodExpressionVoter.java +++ b/core/src/main/java/org/springframework/security/expression/support/MethodExpressionVoter.java @@ -35,7 +35,7 @@ public class MethodExpressionVoter implements AccessDecisionVoter { return attribute instanceof AbstractExpressionBasedMethodConfigAttribute; } - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { return clazz.isAssignableFrom(MethodInvocation.class); } diff --git a/core/src/main/java/org/springframework/security/expression/support/WebExpressionVoter.java b/core/src/main/java/org/springframework/security/expression/support/WebExpressionVoter.java index 79e8966cff..757a225154 100644 --- a/core/src/main/java/org/springframework/security/expression/support/WebExpressionVoter.java +++ b/core/src/main/java/org/springframework/security/expression/support/WebExpressionVoter.java @@ -13,7 +13,7 @@ public class WebExpressionVoter implements AccessDecisionVoter { return false; } - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { return clazz.isAssignableFrom(FilterInvocation.class); } diff --git a/core/src/main/java/org/springframework/security/intercept/AbstractSecurityInterceptor.java b/core/src/main/java/org/springframework/security/intercept/AbstractSecurityInterceptor.java index 711051bb6c..0c7cc12e48 100644 --- a/core/src/main/java/org/springframework/security/intercept/AbstractSecurityInterceptor.java +++ b/core/src/main/java/org/springframework/security/intercept/AbstractSecurityInterceptor.java @@ -359,7 +359,7 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A * * @return the type of secure object the subclass provides services for */ - public abstract Class getSecureObjectClass(); + public abstract Class getSecureObjectClass(); public boolean isAlwaysReauthenticate() { return alwaysReauthenticate; diff --git a/core/src/main/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptor.java b/core/src/main/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptor.java index a32e89b839..eca9b52bcb 100644 --- a/core/src/main/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptor.java +++ b/core/src/main/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptor.java @@ -45,7 +45,7 @@ public class MethodSecurityInterceptor extends AbstractSecurityInterceptor imple return this.objectDefinitionSource; } - public Class getSecureObjectClass() { + public Class getSecureObjectClass() { return MethodInvocation.class; } diff --git a/core/src/main/java/org/springframework/security/intercept/method/aspectj/AspectJAnnotationSecurityInterceptor.java b/core/src/main/java/org/springframework/security/intercept/method/aspectj/AspectJAnnotationSecurityInterceptor.java index 2d044b0330..84f34dc7e9 100644 --- a/core/src/main/java/org/springframework/security/intercept/method/aspectj/AspectJAnnotationSecurityInterceptor.java +++ b/core/src/main/java/org/springframework/security/intercept/method/aspectj/AspectJAnnotationSecurityInterceptor.java @@ -24,7 +24,7 @@ public class AspectJAnnotationSecurityInterceptor extends AbstractSecurityInterc return this.objectDefinitionSource; } - public Class getSecureObjectClass() { + public Class getSecureObjectClass() { return JoinPoint.class; } diff --git a/core/src/main/java/org/springframework/security/intercept/method/aspectj/AspectJSecurityInterceptor.java b/core/src/main/java/org/springframework/security/intercept/method/aspectj/AspectJSecurityInterceptor.java index 1004234fde..e850a07ed8 100644 --- a/core/src/main/java/org/springframework/security/intercept/method/aspectj/AspectJSecurityInterceptor.java +++ b/core/src/main/java/org/springframework/security/intercept/method/aspectj/AspectJSecurityInterceptor.java @@ -46,7 +46,7 @@ public class AspectJSecurityInterceptor extends AbstractSecurityInterceptor { return this.objectDefinitionSource; } - public Class getSecureObjectClass() { + public Class getSecureObjectClass() { return JoinPoint.class; } diff --git a/core/src/main/java/org/springframework/security/intercept/web/DefaultFilterInvocationDefinitionSource.java b/core/src/main/java/org/springframework/security/intercept/web/DefaultFilterInvocationDefinitionSource.java index a5d01b2c1b..4bd55efc30 100644 --- a/core/src/main/java/org/springframework/security/intercept/web/DefaultFilterInvocationDefinitionSource.java +++ b/core/src/main/java/org/springframework/security/intercept/web/DefaultFilterInvocationDefinitionSource.java @@ -54,7 +54,7 @@ import org.springframework.security.util.UrlMatcher; */ public class DefaultFilterInvocationDefinitionSource implements FilterInvocationDefinitionSource { - private static final Set HTTP_METHODS = new HashSet(Arrays.asList(new String[]{ "DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT", "TRACE" })); + private static final Set HTTP_METHODS = new HashSet(Arrays.asList("DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT", "TRACE")); protected final Log logger = LogFactory.getLog(getClass()); @@ -62,9 +62,10 @@ public class DefaultFilterInvocationDefinitionSource implements FilterInvocation * Non method-specific map of URL patterns to Lists * TODO: Store in the httpMethod map with null key. */ - private Map requestMap = new LinkedHashMap(); + private Map> requestMap = new LinkedHashMap>(); /** Stores request maps keyed by specific HTTP methods */ - private Map httpMethodMap = new HashMap(); + private Map>> httpMethodMap = + new HashMap>>(); private UrlMatcher urlMatcher; @@ -108,7 +109,7 @@ public class DefaultFilterInvocationDefinitionSource implements FilterInvocation * a match for a particular URL. */ void addSecureUrl(String pattern, String method, List attr) { - Map mapToUse = getRequestMapForHttpMethod(method); + Map> mapToUse = getRequestMapForHttpMethod(method); mapToUse.put(urlMatcher.compile(pattern), attr); @@ -123,7 +124,7 @@ public class DefaultFilterInvocationDefinitionSource implements FilterInvocation * @param method GET, POST etc * @return map of URL patterns to ConfigAttributes for this method. */ - private Map getRequestMapForHttpMethod(String method) { + private Map> getRequestMapForHttpMethod(String method) { if (method == null) { return requestMap; } @@ -131,10 +132,10 @@ public class DefaultFilterInvocationDefinitionSource implements FilterInvocation throw new IllegalArgumentException("Unrecognised HTTP method: '" + method + "'"); } - Map methodRequestmap = (Map) httpMethodMap.get(method); + Map> methodRequestmap = httpMethodMap.get(method); if (methodRequestmap == null) { - methodRequestmap = new LinkedHashMap(); + methodRequestmap = new LinkedHashMap>(); httpMethodMap.put(method, methodRequestmap); } @@ -195,7 +196,7 @@ public class DefaultFilterInvocationDefinitionSource implements FilterInvocation List attributes = null; - Map methodSpecificMap = (Map) httpMethodMap.get(method); + Map> methodSpecificMap = httpMethodMap.get(method); if (methodSpecificMap != null) { attributes = lookupUrlInMap(methodSpecificMap, url); @@ -208,10 +209,9 @@ public class DefaultFilterInvocationDefinitionSource implements FilterInvocation return attributes; } - private List lookupUrlInMap(Map> requestMap, - String url) { + private List lookupUrlInMap(Map> requestMap, String url) { - for (Map.Entry> entry : requestMap.entrySet()) { + for (Map.Entry> entry : requestMap.entrySet()) { Object p = entry.getKey(); boolean matched = urlMatcher.pathMatchesUrl(entry.getKey(), url); @@ -235,7 +235,7 @@ public class DefaultFilterInvocationDefinitionSource implements FilterInvocation return this.requestMap.size(); } - Map getRequestMap() { + /*Map>*/ Map getRequestMap() { return requestMap; } diff --git a/core/src/main/java/org/springframework/security/intercept/web/FIDSToFilterChainMapConverter.java b/core/src/main/java/org/springframework/security/intercept/web/FIDSToFilterChainMapConverter.java index b31414a062..311b52d675 100644 --- a/core/src/main/java/org/springframework/security/intercept/web/FIDSToFilterChainMapConverter.java +++ b/core/src/main/java/org/springframework/security/intercept/web/FIDSToFilterChainMapConverter.java @@ -23,7 +23,7 @@ import java.util.regex.Pattern; */ public class FIDSToFilterChainMapConverter { - private LinkedHashMap filterChainMap = new LinkedHashMap(); + private LinkedHashMap> filterChainMap = new LinkedHashMap>(); private UrlMatcher matcher; public FIDSToFilterChainMapConverter(DefaultFilterInvocationDefinitionSource fids, ApplicationContext appContext) { @@ -31,15 +31,12 @@ public class FIDSToFilterChainMapConverter { Assert.notNull(fids.getAllConfigAttributes(), "FilterChainProxy requires the " + "FilterInvocationDefinitionSource to return a non-null response to getAllConfigAttributes()"); matcher = fids.getUrlMatcher(); - Map requestMap = fids.getRequestMap(); - Iterator paths = requestMap.keySet().iterator(); + Map> requestMap = fids.getRequestMap(); - while (paths.hasNext()) { - Object entry = paths.next(); + for(Object entry : requestMap.keySet()) { String path = entry instanceof Pattern ? ((Pattern)entry).pattern() : (String)entry; - List configAttributeDefinition = (List) requestMap.get(entry); - - List filters = new ArrayList(); + List configAttributeDefinition = requestMap.get(entry); + List filters = new ArrayList(); for(ConfigAttribute attr : configAttributeDefinition) { String filterName = attr.getAttribute(); @@ -48,7 +45,7 @@ public class FIDSToFilterChainMapConverter { "method, which is invalid when used with FilterChainProxy"); if (!filterName.equals(FilterChainProxy.TOKEN_NONE)) { - filters.add(appContext.getBean(filterName, Filter.class)); + filters.add((Filter) appContext.getBean(filterName, Filter.class)); } } @@ -56,7 +53,7 @@ public class FIDSToFilterChainMapConverter { } } - public Map getFilterChainMap() { + public Map> getFilterChainMap() { return filterChainMap; } diff --git a/core/src/main/java/org/springframework/security/intercept/web/FilterSecurityInterceptor.java b/core/src/main/java/org/springframework/security/intercept/web/FilterSecurityInterceptor.java index 92545023dc..1a3466921d 100644 --- a/core/src/main/java/org/springframework/security/intercept/web/FilterSecurityInterceptor.java +++ b/core/src/main/java/org/springframework/security/intercept/web/FilterSecurityInterceptor.java @@ -87,7 +87,7 @@ public class FilterSecurityInterceptor extends AbstractSecurityInterceptor imple return this.objectDefinitionSource; } - public Class getSecureObjectClass() { + public Class getSecureObjectClass() { return FilterInvocation.class; } diff --git a/core/src/main/java/org/springframework/security/ldap/DefaultSpringSecurityContextSource.java b/core/src/main/java/org/springframework/security/ldap/DefaultSpringSecurityContextSource.java index 4a77927035..cafa48e98b 100644 --- a/core/src/main/java/org/springframework/security/ldap/DefaultSpringSecurityContextSource.java +++ b/core/src/main/java/org/springframework/security/ldap/DefaultSpringSecurityContextSource.java @@ -44,7 +44,7 @@ public class DefaultSpringSecurityContextSource extends LdapContextSource implem StringTokenizer st = new StringTokenizer(providerUrl); - ArrayList urls = new ArrayList(); + ArrayList urls = new ArrayList(); // Work out rootDn from the first URL and check that the other URLs (if any) match while (st.hasMoreTokens()) { @@ -62,10 +62,11 @@ public class DefaultSpringSecurityContextSource extends LdapContextSource implem } } - super.setUrls((String[]) urls.toArray(new String[urls.size()])); + super.setUrls(urls.toArray(new String[urls.size()])); super.setBase(rootDn); } + @SuppressWarnings("unchecked") public DirContext getReadWriteContext(String userDn, Object credentials) { Hashtable env = new Hashtable(getAnonymousEnv()); diff --git a/core/src/main/java/org/springframework/security/providers/AuthenticationProvider.java b/core/src/main/java/org/springframework/security/providers/AuthenticationProvider.java index 6b4c8f6cab..04ed348132 100644 --- a/core/src/main/java/org/springframework/security/providers/AuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/providers/AuthenticationProvider.java @@ -63,5 +63,5 @@ public interface AuthenticationProvider { * @return true if the implementation can more closely evaluate the Authentication class * presented */ - boolean supports(Class authentication); + boolean supports(Class authentication); } diff --git a/core/src/main/java/org/springframework/security/providers/ProviderManager.java b/core/src/main/java/org/springframework/security/providers/ProviderManager.java index 33ee07d093..847be00327 100644 --- a/core/src/main/java/org/springframework/security/providers/ProviderManager.java +++ b/core/src/main/java/org/springframework/security/providers/ProviderManager.java @@ -15,9 +15,23 @@ package org.springframework.security.providers; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.List; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.ApplicationEvent; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.ApplicationEventPublisherAware; +import org.springframework.context.MessageSource; +import org.springframework.context.MessageSourceAware; +import org.springframework.context.support.MessageSourceAccessor; import org.springframework.security.AbstractAuthenticationManager; import org.springframework.security.AccountExpiredException; -import org.springframework.security.SpringSecurityMessageSource; +import org.springframework.security.AccountStatusException; import org.springframework.security.Authentication; import org.springframework.security.AuthenticationException; import org.springframework.security.AuthenticationServiceException; @@ -25,7 +39,7 @@ import org.springframework.security.BadCredentialsException; import org.springframework.security.CredentialsExpiredException; import org.springframework.security.DisabledException; import org.springframework.security.LockedException; -import org.springframework.security.AccountStatusException; +import org.springframework.security.SpringSecurityMessageSource; import org.springframework.security.concurrent.ConcurrentLoginException; import org.springframework.security.concurrent.ConcurrentSessionController; import org.springframework.security.concurrent.NullConcurrentSessionController; @@ -41,26 +55,8 @@ import org.springframework.security.event.authentication.AuthenticationFailurePr import org.springframework.security.event.authentication.AuthenticationFailureServiceExceptionEvent; import org.springframework.security.event.authentication.AuthenticationSuccessEvent; import org.springframework.security.userdetails.UsernameNotFoundException; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.context.ApplicationEvent; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.context.ApplicationEventPublisherAware; -import org.springframework.context.MessageSource; -import org.springframework.context.MessageSourceAware; -import org.springframework.context.support.MessageSourceAccessor; import org.springframework.util.Assert; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -import java.util.Iterator; -import java.util.List; -import java.util.Properties; - /** * Iterates an {@link Authentication} request through a list of {@link AuthenticationProvider}s. @@ -109,7 +105,7 @@ public class ProviderManager extends AbstractAuthenticationManager implements In private ApplicationEventPublisher applicationEventPublisher; private ConcurrentSessionController sessionController = new NullConcurrentSessionController(); - private List providers; + private List providers; protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); private Properties exceptionMappings = new Properties(); private Properties additionalExceptionMappings = new Properties(); @@ -167,15 +163,10 @@ public class ProviderManager extends AbstractAuthenticationManager implements In * @throws AuthenticationException if authentication fails. */ public Authentication doAuthentication(Authentication authentication) throws AuthenticationException { - Iterator iter = getProviders().iterator(); - - Class toTest = authentication.getClass(); - + Class toTest = authentication.getClass(); AuthenticationException lastException = null; - while (iter.hasNext()) { - AuthenticationProvider provider = (AuthenticationProvider) iter.next(); - + for (AuthenticationProvider provider : getProviders()) { if (!provider.supports(toTest)) { continue; } @@ -265,7 +256,7 @@ public class ProviderManager extends AbstractAuthenticationManager implements In } } - public List getProviders() { + public List getProviders() { if (providers == null || providers.size() == 0) { throw new IllegalArgumentException("A list of AuthenticationProviders is required"); } @@ -299,22 +290,20 @@ public class ProviderManager extends AbstractAuthenticationManager implements In * @throws IllegalArgumentException if the list is empty or null, or any of the elements in the list is not an * AuthenticationProvider instance. */ + @SuppressWarnings("unchecked") public void setProviders(List providers) { - Assert.notEmpty(providers, "A list of AuthenticationProviders is required"); - Iterator iter = providers.iterator(); + Assert.notEmpty(providers, "A list of AuthenticationProviders is required"); - while (iter.hasNext()) { - Object currentObject = iter.next(); - Assert.isInstanceOf(AuthenticationProvider.class, currentObject, - "Can only provide AuthenticationProvider instances"); + for(Object currentObject : providers) { + Assert.isInstanceOf(AuthenticationProvider.class, currentObject, "Can only provide AuthenticationProvider instances"); } this.providers = providers; } /** - * Set the {@link ConcurrentSessionController} to be used for limiting users' sessions. The {@link - * NullConcurrentSessionController} is used by default. + * Set the {@link ConcurrentSessionController} to be used for limiting users' sessions. + * The {@link NullConcurrentSessionController} is used by default. * * @param sessionController {@link ConcurrentSessionController} */ diff --git a/core/src/main/java/org/springframework/security/providers/TestingAuthenticationProvider.java b/core/src/main/java/org/springframework/security/providers/TestingAuthenticationProvider.java index 7425d09973..091f446712 100644 --- a/core/src/main/java/org/springframework/security/providers/TestingAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/providers/TestingAuthenticationProvider.java @@ -37,7 +37,7 @@ public class TestingAuthenticationProvider implements AuthenticationProvider { return authentication; } - public boolean supports(Class authentication) { + public boolean supports(Class authentication) { return TestingAuthenticationToken.class.isAssignableFrom(authentication); } } diff --git a/core/src/main/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationProvider.java b/core/src/main/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationProvider.java index a7e93eb3ef..2ae0cd6dc5 100644 --- a/core/src/main/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationProvider.java @@ -76,7 +76,7 @@ public class AnonymousAuthenticationProvider implements AuthenticationProvider, this.messages = new MessageSourceAccessor(messageSource); } - public boolean supports(Class authentication) { + public boolean supports(Class authentication) { return (AnonymousAuthenticationToken.class.isAssignableFrom(authentication)); } } diff --git a/core/src/main/java/org/springframework/security/providers/dao/AbstractUserDetailsAuthenticationProvider.java b/core/src/main/java/org/springframework/security/providers/dao/AbstractUserDetailsAuthenticationProvider.java index daf81d5f60..2a4f90bdd8 100644 --- a/core/src/main/java/org/springframework/security/providers/dao/AbstractUserDetailsAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/providers/dao/AbstractUserDetailsAuthenticationProvider.java @@ -259,7 +259,7 @@ public abstract class AbstractUserDetailsAuthenticationProvider implements Authe this.userCache = userCache; } - public boolean supports(Class authentication) { + public boolean supports(Class authentication) { return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)); } diff --git a/core/src/main/java/org/springframework/security/providers/jaas/JaasAuthenticationProvider.java b/core/src/main/java/org/springframework/security/providers/jaas/JaasAuthenticationProvider.java index f05d309b03..7396e2261a 100644 --- a/core/src/main/java/org/springframework/security/providers/jaas/JaasAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/providers/jaas/JaasAuthenticationProvider.java @@ -431,7 +431,7 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli this.loginExceptionResolver = loginExceptionResolver; } - public boolean supports(Class aClass) { + public boolean supports(Class aClass) { return UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass); } diff --git a/core/src/main/java/org/springframework/security/providers/ldap/LdapAuthenticationProvider.java b/core/src/main/java/org/springframework/security/providers/ldap/LdapAuthenticationProvider.java index abfccb1241..9c24724b33 100644 --- a/core/src/main/java/org/springframework/security/providers/ldap/LdapAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/providers/ldap/LdapAuthenticationProvider.java @@ -253,7 +253,7 @@ public class LdapAuthenticationProvider implements AuthenticationProvider { return new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities()); } - public boolean supports(Class authentication) { + public boolean supports(Class authentication) { return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)); } diff --git a/core/src/main/java/org/springframework/security/providers/ldap/authenticator/AbstractLdapAuthenticator.java b/core/src/main/java/org/springframework/security/providers/ldap/authenticator/AbstractLdapAuthenticator.java index 82788e454f..6fb025e824 100644 --- a/core/src/main/java/org/springframework/security/providers/ldap/authenticator/AbstractLdapAuthenticator.java +++ b/core/src/main/java/org/springframework/security/providers/ldap/authenticator/AbstractLdapAuthenticator.java @@ -87,12 +87,12 @@ public abstract class AbstractLdapAuthenticator implements LdapAuthenticator, In * * @return the list of possible DN matches, empty if userDnPatterns wasn't set. */ - protected List getUserDns(String username) { + protected List getUserDns(String username) { if (userDnFormat == null) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } - List userDns = new ArrayList(userDnFormat.length); + List userDns = new ArrayList(userDnFormat.length); String[] args = new String[] {username}; synchronized (userDnFormat) { diff --git a/core/src/main/java/org/springframework/security/providers/preauth/PreAuthenticatedAuthenticationProvider.java b/core/src/main/java/org/springframework/security/providers/preauth/PreAuthenticatedAuthenticationProvider.java index 75f9edf732..37e61e430a 100644 --- a/core/src/main/java/org/springframework/security/providers/preauth/PreAuthenticatedAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/providers/preauth/PreAuthenticatedAuthenticationProvider.java @@ -97,7 +97,7 @@ public class PreAuthenticatedAuthenticationProvider implements AuthenticationPro /** * Indicate that this provider only supports PreAuthenticatedAuthenticationToken (sub)classes. */ - public boolean supports(Class authentication) { + public boolean supports(Class authentication) { return PreAuthenticatedAuthenticationToken.class.isAssignableFrom(authentication); } diff --git a/core/src/main/java/org/springframework/security/providers/rcp/RemoteAuthenticationProvider.java b/core/src/main/java/org/springframework/security/providers/rcp/RemoteAuthenticationProvider.java index 13a38fe7ed..6b1c83239b 100644 --- a/core/src/main/java/org/springframework/security/providers/rcp/RemoteAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/providers/rcp/RemoteAuthenticationProvider.java @@ -71,7 +71,7 @@ public class RemoteAuthenticationProvider implements AuthenticationProvider, Ini this.remoteAuthenticationManager = remoteAuthenticationManager; } - public boolean supports(Class authentication) { + public boolean supports(Class authentication) { return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)); } } diff --git a/core/src/main/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationProvider.java b/core/src/main/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationProvider.java index 9497035874..cc7295f85e 100644 --- a/core/src/main/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationProvider.java @@ -83,7 +83,7 @@ public class RememberMeAuthenticationProvider implements AuthenticationProvider, this.messages = new MessageSourceAccessor(messageSource); } - public boolean supports(Class authentication) { + public boolean supports(Class authentication) { return (RememberMeAuthenticationToken.class.isAssignableFrom(authentication)); } } diff --git a/core/src/main/java/org/springframework/security/runas/RunAsImplAuthenticationProvider.java b/core/src/main/java/org/springframework/security/runas/RunAsImplAuthenticationProvider.java index 0edacd14bd..25e233361e 100644 --- a/core/src/main/java/org/springframework/security/runas/RunAsImplAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/runas/RunAsImplAuthenticationProvider.java @@ -74,7 +74,7 @@ public class RunAsImplAuthenticationProvider implements InitializingBean, Authen this.messages = new MessageSourceAccessor(messageSource); } - public boolean supports(Class authentication) { + public boolean supports(Class authentication) { if (RunAsUserToken.class.isAssignableFrom(authentication)) { return true; } else { diff --git a/core/src/main/java/org/springframework/security/ui/FilterChainOrder.java b/core/src/main/java/org/springframework/security/ui/FilterChainOrder.java index 960a56d724..beeb2533f3 100644 --- a/core/src/main/java/org/springframework/security/ui/FilterChainOrder.java +++ b/core/src/main/java/org/springframework/security/ui/FilterChainOrder.java @@ -22,13 +22,13 @@ public abstract class FilterChainOrder { public static final int CHANNEL_FILTER = FILTER_CHAIN_FIRST; public static final int CONCURRENT_SESSION_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; - public static final int HTTP_SESSION_CONTEXT_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; + public static final int HTTP_SESSION_CONTEXT_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; public static final int LOGOUT_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; public static final int X509_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; public static final int PRE_AUTH_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; public static final int CAS_PROCESSING_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; public static final int AUTHENTICATION_PROCESSING_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; - public static final int OPENID_PROCESSING_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; + public static final int OPENID_PROCESSING_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; public static final int LOGIN_PAGE_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; public static final int BASIC_PROCESSING_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; public static final int SERVLET_API_SUPPORT_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; @@ -36,11 +36,11 @@ public abstract class FilterChainOrder { public static final int ANONYMOUS_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; public static final int EXCEPTION_TRANSLATION_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; public static final int NTLM_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; - public static final int SESSION_FIXATION_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; + public static final int SESSION_FIXATION_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; public static final int FILTER_SECURITY_INTERCEPTOR = FILTER_CHAIN_FIRST + INTERVAL * i++; public static final int SWITCH_USER_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++; - private static final Map filterNameToOrder = new LinkedHashMap(); + private static final Map filterNameToOrder = new LinkedHashMap(); static { filterNameToOrder.put("FIRST", new Integer(Integer.MIN_VALUE)); @@ -58,7 +58,7 @@ public abstract class FilterChainOrder { filterNameToOrder.put("ANONYMOUS_FILTER", new Integer(ANONYMOUS_FILTER)); filterNameToOrder.put("EXCEPTION_TRANSLATION_FILTER", new Integer(EXCEPTION_TRANSLATION_FILTER)); filterNameToOrder.put("NTLM_FILTER", new Integer(NTLM_FILTER)); - filterNameToOrder.put("SESSION_CONTEXT_INTEGRATION_FILTER", new Integer(HTTP_SESSION_CONTEXT_FILTER)); + filterNameToOrder.put("SESSION_CONTEXT_INTEGRATION_FILTER", new Integer(HTTP_SESSION_CONTEXT_FILTER)); filterNameToOrder.put("FILTER_SECURITY_INTERCEPTOR", new Integer(FILTER_SECURITY_INTERCEPTOR)); filterNameToOrder.put("SWITCH_USER_FILTER", new Integer(SWITCH_USER_FILTER)); filterNameToOrder.put("LAST", new Integer(Integer.MAX_VALUE)); @@ -66,7 +66,7 @@ public abstract class FilterChainOrder { /** Allows filters to be used by name in the XSD file without explicit reference to Java constants */ public static int getOrder(String filterName) { - Integer order = (Integer) filterNameToOrder.get(filterName); + Integer order = filterNameToOrder.get(filterName); Assert.notNull(order, "Unable to match filter name " + filterName); diff --git a/core/src/main/java/org/springframework/security/ui/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.java b/core/src/main/java/org/springframework/security/ui/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.java index e1bbea276a..d511ea7189 100755 --- a/core/src/main/java/org/springframework/security/ui/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.java +++ b/core/src/main/java/org/springframework/security/ui/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.java @@ -37,7 +37,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource extends Abs * @return GrantedAuthority[] mapped from the user's J2EE roles. */ protected Collection getUserRoles(Object context, String[] mappableRoles) { - ArrayList j2eeUserRolesList = new ArrayList(); + ArrayList j2eeUserRolesList = new ArrayList(); for (int i = 0; i < mappableRoles.length; i++) { if (((HttpServletRequest)context).isUserInRole(mappableRoles[i])) { diff --git a/core/src/main/java/org/springframework/security/ui/savedrequest/Enumerator.java b/core/src/main/java/org/springframework/security/ui/savedrequest/Enumerator.java index 2c259f6f2a..e3ea12f3d5 100644 --- a/core/src/main/java/org/springframework/security/ui/savedrequest/Enumerator.java +++ b/core/src/main/java/org/springframework/security/ui/savedrequest/Enumerator.java @@ -33,6 +33,7 @@ import java.util.NoSuchElementException; * @author Andrey Grebnev * @version $Id$ */ +@SuppressWarnings("unchecked") public class Enumerator implements Enumeration { //~ Instance fields ================================================================================================ @@ -73,7 +74,7 @@ public class Enumerator implements Enumeration { this.iterator = iterator; } -/** + /** * Return an Enumeration over the values returned by the specified * Iterator. * @@ -81,7 +82,6 @@ public class Enumerator implements Enumeration { * @param clone true to clone iterator */ public Enumerator(Iterator iterator, boolean clone) { - super(); if (!clone) { this.iterator = iterator; @@ -96,7 +96,7 @@ public class Enumerator implements Enumeration { } } -/** + /** * Return an Enumeration over the values of the specified Map. * * @param map Map whose values should be enumerated diff --git a/core/src/main/java/org/springframework/security/ui/savedrequest/SavedRequest.java b/core/src/main/java/org/springframework/security/ui/savedrequest/SavedRequest.java index 0011a75e21..c359b559a4 100644 --- a/core/src/main/java/org/springframework/security/ui/savedrequest/SavedRequest.java +++ b/core/src/main/java/org/springframework/security/ui/savedrequest/SavedRequest.java @@ -46,6 +46,7 @@ import java.util.TreeMap; * @author Ben Alex * @version $Id$ */ +@SuppressWarnings("unchecked") public class SavedRequest implements java.io.Serializable { //~ Static fields/initializers ===================================================================================== diff --git a/core/src/main/java/org/springframework/security/userdetails/jdbc/JdbcDaoImpl.java b/core/src/main/java/org/springframework/security/userdetails/jdbc/JdbcDaoImpl.java index ecbf82286f..89b510142a 100644 --- a/core/src/main/java/org/springframework/security/userdetails/jdbc/JdbcDaoImpl.java +++ b/core/src/main/java/org/springframework/security/userdetails/jdbc/JdbcDaoImpl.java @@ -23,6 +23,7 @@ import org.springframework.security.userdetails.User; import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetailsService; import org.springframework.security.userdetails.UsernameNotFoundException; +import org.springframework.security.util.AuthorityUtils; import org.springframework.context.ApplicationContextException; import org.springframework.context.support.MessageSourceAccessor; @@ -47,23 +48,23 @@ import javax.sql.DataSource; /** - * UserDetailsServiceRetrieves implementation which retrieves the user details + * UserDetailsServiceRetrieves implementation which retrieves the user details * (username, password, enabled flag, and authorities) from a database using JDBC queries. - * - *

Default Schema

+ * + *

Default Schema

* A default database schema is assumed, with two tables "users" and "authorities". - * + * *

The Users table

- * + * * This table contains the login name, password and enabled status of the user. - * + * * * * * * *
Column
username
password
enabled
- * + * *

The Authorities Table

* * @@ -73,7 +74,7 @@ import javax.sql.DataSource; *
* * If you are using an existing schema you will have to set the queries usersByUsernameQuery and - * authoritiesByUsernameQuery to match your database setup + * authoritiesByUsernameQuery to match your database setup * (see {@link #DEF_USERS_BY_USERNAME_QUERY} and {@link #DEF_AUTHORITIES_BY_USERNAME_QUERY}). * *

@@ -81,7 +82,7 @@ import javax.sql.DataSource; * accounts or the expiration of user credentials. However, it does recognise and honour the user enabled/disabled * column. This should map to a boolean type in the result set (the SQL type will depend on the * database you are using). All the other columns map to Strings. - * + * *

Group Support

* Support for group-based authorities can be enabled by setting the enableGroups property to true * (you may also then wish to set enableAuthorities to false to disable loading of authorities @@ -151,7 +152,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService { * @param authorities the current granted authorities, as populated from the authoritiesByUsername * mapping */ - protected void addCustomAuthorities(String username, List authorities) {} + protected void addCustomAuthorities(String username, List authorities) {} public String getUsersByUsernameQuery() { return usersByUsernameQuery; @@ -172,7 +173,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService { } public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { - List users = loadUsersByUsername(username); + List users = loadUsersByUsername(username); if (users.size() == 0) { throw new UsernameNotFoundException( @@ -181,7 +182,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService { UserDetails user = (UserDetails) users.get(0); // contains no GrantedAuthority[] - Set dbAuthsSet = new HashSet(); + Set dbAuthsSet = new HashSet(); if (enableAuthorities) { dbAuthsSet.addAll(loadUserAuthorities(user.getUsername())); @@ -191,7 +192,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService { dbAuthsSet.addAll(loadGroupAuthorities(user.getUsername())); } - List dbAuths = new ArrayList(dbAuthsSet); + List dbAuths = new ArrayList(dbAuthsSet); addCustomAuthorities(user.getUsername(), dbAuths); @@ -201,49 +202,47 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService { new Object[] {username}, "User {0} has no GrantedAuthority"), username); } - GrantedAuthority[] arrayAuths = (GrantedAuthority[]) dbAuths.toArray(new GrantedAuthority[dbAuths.size()]); - - return createUserDetails(username, user, arrayAuths); + return createUserDetails(username, user, dbAuths); } - - /** - * Executes the usersByUsernameQuery and returns a list of UserDetails objects (there should normally - * only be one matching user). + + /** + * Executes the usersByUsernameQuery and returns a list of UserDetails objects (there should normally + * only be one matching user). */ - protected List loadUsersByUsername(String username) { + protected List loadUsersByUsername(String username) { return usersByUsernameMapping.execute(username); } - + /** * Loads authorities by executing the authoritiesByUsernameQuery. - * + * * @return a list of GrantedAuthority objects for the user */ - protected List loadUserAuthorities(String username) { + protected List loadUserAuthorities(String username) { return authoritiesByUsernameMapping.execute(username); } - - protected List loadGroupAuthorities(String username) { + + protected List loadGroupAuthorities(String username) { return groupAuthoritiesByUsernameMapping.execute(username); } - + /** * Can be overridden to customize the creation of the final UserDetailsObject returnd from loadUserByUsername. - * + * * @param username the name originally passed to loadUserByUsername - * @param userFromUserQuery the object returned from the execution of the + * @param userFromUserQuery the object returned from the execution of the * @param combinedAuthorities the combined array of authorities from all the authority loading queries. * @return the final UserDetails which should be used in the system. */ - protected UserDetails createUserDetails(String username, UserDetails userFromUserQuery, - GrantedAuthority[] combinedAuthorities) { + protected UserDetails createUserDetails(String username, UserDetails userFromUserQuery, + List combinedAuthorities) { String returnUsername = userFromUserQuery.getUsername(); if (!usernameBasedPrimaryKey) { returnUsername = username; } - return new User(returnUsername, userFromUserQuery.getPassword(), userFromUserQuery.isEnabled(), + return new User(returnUsername, userFromUserQuery.getPassword(), userFromUserQuery.isEnabled(), true, true, true, combinedAuthorities); } @@ -395,8 +394,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService { String username = rs.getString(1); String password = rs.getString(2); boolean enabled = rs.getBoolean(3); - UserDetails user = new User(username, password, enabled, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("HOLDER")}); + UserDetails user = new User(username, password, enabled, true, true, true, AuthorityUtils.NO_AUTHORITIES); return user; } diff --git a/core/src/main/java/org/springframework/security/userdetails/ldap/Person.java b/core/src/main/java/org/springframework/security/userdetails/ldap/Person.java index b56c74dfc9..aaadec18bd 100644 --- a/core/src/main/java/org/springframework/security/userdetails/ldap/Person.java +++ b/core/src/main/java/org/springframework/security/userdetails/ldap/Person.java @@ -37,7 +37,7 @@ public class Person extends LdapUserDetailsImpl { private String sn; private String description; private String telephoneNumber; - private List cn = new ArrayList(); + private List cn = new ArrayList(); protected Person() { } @@ -47,18 +47,18 @@ public class Person extends LdapUserDetailsImpl { } public String[] getCn() { - return (String[]) cn.toArray(new String[cn.size()]); + return cn.toArray(new String[cn.size()]); } - + public String getDescription() { - return description; - } + return description; + } - public String getTelephoneNumber() { - return telephoneNumber; - } + public String getTelephoneNumber() { + return telephoneNumber; + } - protected void populateContext(DirContextAdapter adapter) { + protected void populateContext(DirContextAdapter adapter) { adapter.setAttributeValue("sn", sn); adapter.setAttributeValues("cn", getCn()); adapter.setAttributeValue("description", getDescription()); @@ -89,12 +89,12 @@ public class Person extends LdapUserDetailsImpl { } } - public Essence(Person copyMe) { + public Essence(Person copyMe) { super(copyMe); setSn(copyMe.sn); setDescription(copyMe.getDescription()); setTelephoneNumber(copyMe.getTelephoneNumber()); - ((Person) instance).cn = new ArrayList(copyMe.cn); + ((Person) instance).cn = new ArrayList(copyMe.cn); } protected LdapUserDetailsImpl createTarget() { @@ -112,14 +112,14 @@ public class Person extends LdapUserDetailsImpl { public void addCn(String value) { ((Person) instance).cn.add(value); } - - public void setTelephoneNumber(String tel) { - ((Person) instance).telephoneNumber = tel; - } - public void setDescription(String desc) { - ((Person) instance).description = desc; - } + public void setTelephoneNumber(String tel) { + ((Person) instance).telephoneNumber = tel; + } + + public void setDescription(String desc) { + ((Person) instance).description = desc; + } public LdapUserDetails createUserDetails() { Person p = (Person) super.createUserDetails(); diff --git a/core/src/main/java/org/springframework/security/util/FilterToBeanProxy.java b/core/src/main/java/org/springframework/security/util/FilterToBeanProxy.java index 2c853043ea..7b621a55ad 100644 --- a/core/src/main/java/org/springframework/security/util/FilterToBeanProxy.java +++ b/core/src/main/java/org/springframework/security/util/FilterToBeanProxy.java @@ -74,6 +74,7 @@ import javax.servlet.ServletResponse; * @author Ben Alex * @version $Id$ */ +@SuppressWarnings("unchecked") public class FilterToBeanProxy implements Filter { //~ Instance fields ================================================================================================ diff --git a/core/src/main/java/org/springframework/security/util/PortMapperImpl.java b/core/src/main/java/org/springframework/security/util/PortMapperImpl.java index b992d00400..eb64f19273 100644 --- a/core/src/main/java/org/springframework/security/util/PortMapperImpl.java +++ b/core/src/main/java/org/springframework/security/util/PortMapperImpl.java @@ -35,12 +35,12 @@ import java.util.Map; public class PortMapperImpl implements PortMapper { //~ Instance fields ================================================================================================ - private Map httpsPortMappings; + private Map httpsPortMappings; //~ Constructors =================================================================================================== public PortMapperImpl() { - httpsPortMappings = new HashMap(); + httpsPortMappings = new HashMap(); httpsPortMappings.put(new Integer(80), new Integer(443)); httpsPortMappings.put(new Integer(8080), new Integer(8443)); } @@ -50,18 +50,16 @@ public class PortMapperImpl implements PortMapper { /** * Returns the translated (Integer -> Integer) version of the original port mapping specified via * setHttpsPortMapping() - * - * @return DOCUMENT ME! */ - public Map getTranslatedPortMappings() { + public Map getTranslatedPortMappings() { return httpsPortMappings; } public Integer lookupHttpPort(Integer httpsPort) { - Iterator iter = httpsPortMappings.keySet().iterator(); + Iterator iter = httpsPortMappings.keySet().iterator(); while (iter.hasNext()) { - Integer httpPort = (Integer) iter.next(); + Integer httpPort = iter.next(); if (httpsPortMappings.get(httpPort).equals(httpsPort)) { return httpPort; @@ -72,7 +70,7 @@ public class PortMapperImpl implements PortMapper { } public Integer lookupHttpsPort(Integer httpPort) { - return (Integer) httpsPortMappings.get(httpPort); + return httpsPortMappings.get(httpPort); } /** @@ -93,17 +91,14 @@ public class PortMapperImpl implements PortMapper { * @throws IllegalArgumentException if input map does not consist of String keys and values, each representing an * integer port number in the range 1-65535 for that mapping. */ - public void setPortMappings(Map newMappings) { + public void setPortMappings(Map newMappings) { Assert.notNull(newMappings, "A valid list of HTTPS port mappings must be provided"); httpsPortMappings.clear(); - Iterator it = newMappings.entrySet().iterator(); - - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - Integer httpPort = new Integer((String) entry.getKey()); - Integer httpsPort = new Integer((String) entry.getValue()); + for (Map.Entry entry : newMappings.entrySet()) { + Integer httpPort = new Integer(entry.getKey()); + Integer httpsPort = new Integer(entry.getValue()); if ((httpPort.intValue() < 1) || (httpPort.intValue() > 65535) || (httpsPort.intValue() < 1) || (httpsPort.intValue() > 65535)) { diff --git a/core/src/main/java/org/springframework/security/util/StringSplitUtils.java b/core/src/main/java/org/springframework/security/util/StringSplitUtils.java index 883ac8ce0e..7d3f41e183 100644 --- a/core/src/main/java/org/springframework/security/util/StringSplitUtils.java +++ b/core/src/main/java/org/springframework/security/util/StringSplitUtils.java @@ -84,12 +84,12 @@ public final class StringSplitUtils { * @return a Map representing the array contents, or null if the array to process was * null or empty */ - public static Map splitEachArrayElementAndCreateMap(String[] array, String delimiter, String removeCharacters) { + public static Map splitEachArrayElementAndCreateMap(String[] array, String delimiter, String removeCharacters) { if ((array == null) || (array.length == 0)) { return null; } - Map map = new HashMap(); + Map map = new HashMap(); for (int i = 0; i < array.length; i++) { String postRemove; @@ -155,7 +155,7 @@ public final class StringSplitUtils { return EMPTY_STRING_ARRAY; } - List list = new ArrayList(); + List list = new ArrayList(); int i = 0; int start = 0; boolean match = false; @@ -188,7 +188,7 @@ public final class StringSplitUtils { list.add(str.substring(start, i)); } - return (String[]) list.toArray(new String[list.size()]); + return list.toArray(new String[list.size()]); } } diff --git a/core/src/main/java/org/springframework/security/vote/AbstractAccessDecisionManager.java b/core/src/main/java/org/springframework/security/vote/AbstractAccessDecisionManager.java index 0026f7c159..e59ec40a11 100644 --- a/core/src/main/java/org/springframework/security/vote/AbstractAccessDecisionManager.java +++ b/core/src/main/java/org/springframework/security/vote/AbstractAccessDecisionManager.java @@ -40,7 +40,7 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan MessageSourceAware { //~ Instance fields ================================================================================================ - private List decisionVoters; + private List decisionVoters; protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); @@ -72,10 +72,10 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan this.allowIfAllAbstainDecisions = allowIfAllAbstainDecisions; } - public void setDecisionVoters(List newList) { + public void setDecisionVoters(List newList) { Assert.notEmpty(newList); - Iterator iter = newList.iterator(); + Iterator iter = newList.iterator(); while (iter.hasNext()) { Object currentObject = iter.next(); @@ -91,10 +91,10 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan } public boolean supports(ConfigAttribute attribute) { - Iterator iter = this.decisionVoters.iterator(); + Iterator iter = this.decisionVoters.iterator(); while (iter.hasNext()) { - AccessDecisionVoter voter = (AccessDecisionVoter) iter.next(); + AccessDecisionVoter voter = iter.next(); if (voter.supports(attribute)) { return true; @@ -114,10 +114,10 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan * @return true if this type is supported */ public boolean supports(Class clazz) { - Iterator iter = this.decisionVoters.iterator(); + Iterator iter = this.decisionVoters.iterator(); while (iter.hasNext()) { - AccessDecisionVoter voter = (AccessDecisionVoter) iter.next(); + AccessDecisionVoter voter = iter.next(); if (!voter.supports(clazz)) { return false; diff --git a/core/src/main/java/org/springframework/security/vote/AbstractAclVoter.java b/core/src/main/java/org/springframework/security/vote/AbstractAclVoter.java index 3006b18f30..4a2a2bdcec 100644 --- a/core/src/main/java/org/springframework/security/vote/AbstractAclVoter.java +++ b/core/src/main/java/org/springframework/security/vote/AbstractAclVoter.java @@ -78,7 +78,7 @@ public abstract class AbstractAclVoter implements AccessDecisionVoter { * * @return true if the secure object is MethodInvocation, false otherwise */ - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { if (MethodInvocation.class.isAssignableFrom(clazz)) { return true; } else if (JoinPoint.class.isAssignableFrom(clazz)) { diff --git a/core/src/main/java/org/springframework/security/vote/AccessDecisionVoter.java b/core/src/main/java/org/springframework/security/vote/AccessDecisionVoter.java index ade4b459d9..5e002b59bf 100644 --- a/core/src/main/java/org/springframework/security/vote/AccessDecisionVoter.java +++ b/core/src/main/java/org/springframework/security/vote/AccessDecisionVoter.java @@ -63,7 +63,7 @@ public interface AccessDecisionVoter { * * @return true if the implementation can process the indicated class */ - boolean supports(Class clazz); + boolean supports(Class clazz); /** * Indicates whether or not access is granted. diff --git a/core/src/main/java/org/springframework/security/vote/AuthenticatedVoter.java b/core/src/main/java/org/springframework/security/vote/AuthenticatedVoter.java index e8bb2824fa..004c2f5c45 100644 --- a/core/src/main/java/org/springframework/security/vote/AuthenticatedVoter.java +++ b/core/src/main/java/org/springframework/security/vote/AuthenticatedVoter.java @@ -83,17 +83,14 @@ public class AuthenticatedVoter implements AccessDecisionVoter { * * @return always true */ - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { return true; } public int vote(Authentication authentication, Object object, List attributes) { int result = ACCESS_ABSTAIN; - Iterator iter = attributes.iterator(); - - while (iter.hasNext()) { - ConfigAttribute attribute = (ConfigAttribute) iter.next(); + for (ConfigAttribute attribute : attributes) { if (this.supports(attribute)) { result = ACCESS_DENIED; diff --git a/core/src/main/java/org/springframework/security/vote/RoleVoter.java b/core/src/main/java/org/springframework/security/vote/RoleVoter.java index 2fddcc4276..81fb54f777 100644 --- a/core/src/main/java/org/springframework/security/vote/RoleVoter.java +++ b/core/src/main/java/org/springframework/security/vote/RoleVoter.java @@ -88,7 +88,7 @@ public class RoleVoter implements AccessDecisionVoter { * * @return always true */ - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { return true; } diff --git a/core/src/test/java/org/springframework/security/AuthenticationTrustResolverImplTests.java b/core/src/test/java/org/springframework/security/AuthenticationTrustResolverImplTests.java index ea4ceb09a1..24284faac4 100644 --- a/core/src/test/java/org/springframework/security/AuthenticationTrustResolverImplTests.java +++ b/core/src/test/java/org/springframework/security/AuthenticationTrustResolverImplTests.java @@ -29,22 +29,9 @@ import org.springframework.security.providers.rememberme.RememberMeAuthenticatio * @version $Id$ */ public class AuthenticationTrustResolverImplTests extends TestCase { - //~ Constructors =================================================================================================== - - public AuthenticationTrustResolverImplTests() { - super(); - } - - public AuthenticationTrustResolverImplTests(String arg0) { - super(arg0); - } //~ Methods ======================================================================================================== - public static void main(String[] args) { - junit.textui.TestRunner.run(AuthenticationTrustResolverImplTests.class); - } - public void testCorrectOperationIsAnonymous() { AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl(); assertTrue(trustResolver.isAnonymous( @@ -69,11 +56,11 @@ public class AuthenticationTrustResolverImplTests extends TestCase { AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl(); assertEquals(AnonymousAuthenticationToken.class, trustResolver.getAnonymousClass()); - trustResolver.setAnonymousClass(String.class); - assertEquals(String.class, trustResolver.getAnonymousClass()); + trustResolver.setAnonymousClass(TestingAuthenticationToken.class); + assertEquals(TestingAuthenticationToken.class, trustResolver.getAnonymousClass()); assertEquals(RememberMeAuthenticationToken.class, trustResolver.getRememberMeClass()); - trustResolver.setRememberMeClass(String.class); - assertEquals(String.class, trustResolver.getRememberMeClass()); + trustResolver.setRememberMeClass(TestingAuthenticationToken.class); + assertEquals(TestingAuthenticationToken.class, trustResolver.getRememberMeClass()); } } diff --git a/core/src/test/java/org/springframework/security/afterinvocation/AfterInvocationProviderManagerTests.java b/core/src/test/java/org/springframework/security/afterinvocation/AfterInvocationProviderManagerTests.java index efdca4d41a..2a3c4fa85b 100644 --- a/core/src/test/java/org/springframework/security/afterinvocation/AfterInvocationProviderManagerTests.java +++ b/core/src/test/java/org/springframework/security/afterinvocation/AfterInvocationProviderManagerTests.java @@ -35,16 +35,8 @@ import org.springframework.security.util.SimpleMethodInvocation; * @author Ben Alex * @version $Id$ */ +@SuppressWarnings("unchecked") public class AfterInvocationProviderManagerTests extends TestCase { - //~ Constructors =================================================================================================== - - public AfterInvocationProviderManagerTests() { - super(); - } - - public AfterInvocationProviderManagerTests(String arg0) { - super(arg0); - } //~ Methods ======================================================================================================== @@ -167,7 +159,7 @@ public class AfterInvocationProviderManagerTests extends TestCase { return returnedObject; } - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { return secureObject.isAssignableFrom(clazz); } diff --git a/core/src/test/java/org/springframework/security/annotation/BusinessService.java b/core/src/test/java/org/springframework/security/annotation/BusinessService.java index af2ecb2541..cbe3629353 100644 --- a/core/src/test/java/org/springframework/security/annotation/BusinessService.java +++ b/core/src/test/java/org/springframework/security/annotation/BusinessService.java @@ -51,10 +51,10 @@ public interface BusinessService { public int someOther(int input); - public List methodReturningAList(List someList); + public List methodReturningAList(List someList); public Object[] methodReturningAnArray(Object[] someArray); - public List methodReturningAList(String userName, String extraParam); + public List methodReturningAList(String userName, String extraParam); } diff --git a/core/src/test/java/org/springframework/security/annotation/BusinessServiceImpl.java b/core/src/test/java/org/springframework/security/annotation/BusinessServiceImpl.java index 9d79e5a8b3..4234fc77b6 100644 --- a/core/src/test/java/org/springframework/security/annotation/BusinessServiceImpl.java +++ b/core/src/test/java/org/springframework/security/annotation/BusinessServiceImpl.java @@ -37,12 +37,12 @@ public class BusinessServiceImpl implements BusinessService { return input; } - public List methodReturningAList(List someList) { + public List methodReturningAList(List someList) { return someList; } - public List methodReturningAList(String userName, String arg2) { - return new ArrayList(); + public List methodReturningAList(String userName, String arg2) { + return new ArrayList(); } public Object[] methodReturningAnArray(Object[] someArray) { diff --git a/core/src/test/java/org/springframework/security/annotation/ExpressionProtectedBusinessServiceImpl.java b/core/src/test/java/org/springframework/security/annotation/ExpressionProtectedBusinessServiceImpl.java index d5ad568e65..f9ee029f87 100644 --- a/core/src/test/java/org/springframework/security/annotation/ExpressionProtectedBusinessServiceImpl.java +++ b/core/src/test/java/org/springframework/security/annotation/ExpressionProtectedBusinessServiceImpl.java @@ -30,12 +30,12 @@ public class ExpressionProtectedBusinessServiceImpl implements BusinessService { @PreFilter(filterTarget="someList", value="filterObject == authentication.name or filterObject == 'sam'") @PostFilter("filterObject == 'bob'") - public List methodReturningAList(List someList) { + public List methodReturningAList(List someList) { return someList; } - public List methodReturningAList(String userName, String arg2) { - return new ArrayList(); + public List methodReturningAList(String userName, String arg2) { + return new ArrayList(); } @PostFilter("filterObject == 'bob'") diff --git a/core/src/test/java/org/springframework/security/annotation/Jsr250BusinessServiceImpl.java b/core/src/test/java/org/springframework/security/annotation/Jsr250BusinessServiceImpl.java index d79a77ffc4..51c9bba6c7 100644 --- a/core/src/test/java/org/springframework/security/annotation/Jsr250BusinessServiceImpl.java +++ b/core/src/test/java/org/springframework/security/annotation/Jsr250BusinessServiceImpl.java @@ -38,11 +38,11 @@ public class Jsr250BusinessServiceImpl implements BusinessService { return input; } - public List methodReturningAList(List someList) { + public List methodReturningAList(List someList) { return someList; } - public List methodReturningAList(String userName, String arg2) { + public List methodReturningAList(String userName, String arg2) { return new ArrayList(); } diff --git a/core/src/test/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParserTests.java b/core/src/test/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParserTests.java index 8428e303cd..7195ae5512 100644 --- a/core/src/test/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParserTests.java +++ b/core/src/test/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParserTests.java @@ -1,7 +1,7 @@ package org.springframework.security.config; import static org.junit.Assert.*; -import static org.springframework.security.config.ConfigTestUtils.*; +import static org.springframework.security.config.ConfigTestUtils.AUTH_PROVIDER_XML; import java.util.ArrayList; import java.util.List; @@ -11,16 +11,19 @@ import org.junit.Test; import org.springframework.beans.factory.parsing.BeanDefinitionParsingException; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.security.AccessDeniedException; -import org.springframework.security.Authentication; import org.springframework.security.AuthenticationCredentialsNotFoundException; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; +import org.springframework.security.afterinvocation.AfterInvocationProviderManager; import org.springframework.security.annotation.BusinessService; import org.springframework.security.context.SecurityContextHolder; +import org.springframework.security.expression.support.MethodExpressionAfterInvocationProvider; +import org.springframework.security.expression.support.MethodExpressionVoter; import org.springframework.security.providers.TestingAuthenticationToken; import org.springframework.security.providers.UsernamePasswordAuthenticationToken; import org.springframework.security.userdetails.UserDetailsService; +import org.springframework.security.util.AuthorityUtils; +import org.springframework.security.util.FieldUtils; import org.springframework.security.util.InMemoryXmlApplicationContext; +import org.springframework.security.vote.AffirmativeBased; /** * @author Ben Alex @@ -107,7 +110,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests { UserDetailsService service = (UserDetailsService) appContext.getBean("myUserService"); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_SOMEOTHERROLE")}); + AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE")); SecurityContextHolder.getContext().setAuthentication(token); service.loadUserByUsername("notused"); @@ -180,12 +183,25 @@ public class GlobalMethodSecurityBeanDefinitionParserTests { ); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_SOMEOTHERROLE")}); + AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE")); SecurityContextHolder.getContext().setAuthentication(token); target = (BusinessService) appContext.getBean("businessService"); target.someUserMethod1(); } + // Expression configuration tests + + @Test + public void expressionVoterAndAfterInvocationProviderUseSameExpressionHandlerInstance() throws Exception { + setContext("" + AUTH_PROVIDER_XML); + AffirmativeBased adm = (AffirmativeBased) appContext.getBean(GlobalMethodSecurityBeanDefinitionParser.ACCESS_MANAGER_ID); + List voters = (List) FieldUtils.getFieldValue(adm, "decisionVoters"); + MethodExpressionVoter mev = (MethodExpressionVoter) voters.get(0); + AfterInvocationProviderManager pm = (AfterInvocationProviderManager) appContext.getBean(BeanIds.AFTER_INVOCATION_MANAGER); + MethodExpressionAfterInvocationProvider aip = (MethodExpressionAfterInvocationProvider) pm.getProviders().get(0); + assertTrue(FieldUtils.getFieldValue(mev, "expressionHandler") == FieldUtils.getFieldValue(aip, "expressionHandler")); + } + @Test(expected=AccessDeniedException.class) public void accessIsDeniedForHasRoleExpression() { setContext( diff --git a/core/src/test/java/org/springframework/security/config/MockAfterInvocationProvider.java b/core/src/test/java/org/springframework/security/config/MockAfterInvocationProvider.java index c4987294be..87d4ad9224 100644 --- a/core/src/test/java/org/springframework/security/config/MockAfterInvocationProvider.java +++ b/core/src/test/java/org/springframework/security/config/MockAfterInvocationProvider.java @@ -18,7 +18,7 @@ public class MockAfterInvocationProvider implements AfterInvocationProvider { return true; } - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { return true; } diff --git a/core/src/test/java/org/springframework/security/expression/support/MethodExpressionVoterTests.java b/core/src/test/java/org/springframework/security/expression/support/MethodExpressionVoterTests.java index 8bb2fcd8f1..a4099db637 100644 --- a/core/src/test/java/org/springframework/security/expression/support/MethodExpressionVoterTests.java +++ b/core/src/test/java/org/springframework/security/expression/support/MethodExpressionVoterTests.java @@ -9,34 +9,17 @@ import java.util.Collection; import java.util.List; import org.aopalliance.intercept.MethodInvocation; -import org.junit.Before; import org.junit.Test; import org.springframework.security.ConfigAttribute; -import org.springframework.security.annotation.ExpressionProtectedBusinessServiceImpl; import org.springframework.security.providers.TestingAuthenticationToken; import org.springframework.security.util.SimpleMethodInvocation; import org.springframework.security.vote.AccessDecisionVoter; +@SuppressWarnings("unchecked") public class MethodExpressionVoterTests { private TestingAuthenticationToken joe = new TestingAuthenticationToken("joe", "joespass", "blah"); - private MethodInvocation miListArg; - private MethodInvocation miArrayArg; - private List listArg; - private Object[] arrayArg; private MethodExpressionVoter am = new MethodExpressionVoter(); - @Before - public void setUp() throws Exception { - Method m = ExpressionProtectedBusinessServiceImpl.class.getMethod("methodReturningAList", - String.class, String.class); - m = ExpressionProtectedBusinessServiceImpl.class.getMethod("methodReturningAList", List.class); - listArg = new ArrayList(Arrays.asList("joe", "bob", "sam")); - miListArg = new SimpleMethodInvocation(new Object(), m, new Object[] {listArg}); - m = ExpressionProtectedBusinessServiceImpl.class.getMethod("methodReturningAnArray", Object[].class); - arrayArg = new Object[] {"joe", "bob", "sam"}; - miArrayArg = new SimpleMethodInvocation(new Object(), m, new Object[] {arrayArg}); - } - @Test public void hasRoleExpressionAllowsUserWithRole() throws Exception { MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAnArray()); diff --git a/core/src/test/java/org/springframework/security/intercept/AbstractSecurityInterceptorTests.java b/core/src/test/java/org/springframework/security/intercept/AbstractSecurityInterceptorTests.java index 901ee85bec..779ba1afd8 100644 --- a/core/src/test/java/org/springframework/security/intercept/AbstractSecurityInterceptorTests.java +++ b/core/src/test/java/org/springframework/security/intercept/AbstractSecurityInterceptorTests.java @@ -90,7 +90,7 @@ public class AbstractSecurityInterceptorTests extends TestCase { private class MockSecurityInterceptorReturnsNull extends AbstractSecurityInterceptor { private ObjectDefinitionSource objectDefinitionSource; - public Class getSecureObjectClass() { + public Class getSecureObjectClass() { return null; } @@ -106,7 +106,7 @@ public class AbstractSecurityInterceptorTests extends TestCase { private class MockSecurityInterceptorWhichOnlySupportsStrings extends AbstractSecurityInterceptor { private ObjectDefinitionSource objectDefinitionSource; - public Class getSecureObjectClass() { + public Class getSecureObjectClass() { return String.class; } diff --git a/core/src/test/java/org/springframework/security/providers/ProviderManagerTests.java b/core/src/test/java/org/springframework/security/providers/ProviderManagerTests.java index bfb8cfd06b..6daa334558 100644 --- a/core/src/test/java/org/springframework/security/providers/ProviderManagerTests.java +++ b/core/src/test/java/org/springframework/security/providers/ProviderManagerTests.java @@ -15,25 +15,26 @@ package org.springframework.security.providers; -import org.springframework.security.Authentication; -import org.springframework.security.AuthenticationException; -import org.springframework.security.AuthenticationServiceException; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; -import org.springframework.security.MockApplicationEventPublisher; -import org.springframework.security.AccountStatusException; -import org.springframework.security.concurrent.ConcurrentSessionControllerImpl; -import org.springframework.security.concurrent.NullConcurrentSessionController; -import org.springframework.security.concurrent.ConcurrentLoginException; -import org.springframework.security.util.AuthorityUtils; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.Vector; import org.junit.Test; -import static org.junit.Assert.*; +import org.springframework.security.AccountStatusException; +import org.springframework.security.Authentication; +import org.springframework.security.AuthenticationException; +import org.springframework.security.AuthenticationServiceException; +import org.springframework.security.GrantedAuthority; +import org.springframework.security.MockApplicationEventPublisher; +import org.springframework.security.concurrent.ConcurrentLoginException; +import org.springframework.security.concurrent.ConcurrentSessionControllerImpl; +import org.springframework.security.concurrent.NullConcurrentSessionController; +import org.springframework.security.util.AuthorityUtils; /** * Tests {@link ProviderManager}. @@ -48,7 +49,7 @@ public class ProviderManagerTests { @Test(expected=ProviderNotFoundException.class) public void authenticationFailsWithUnsupportedToken() throws Exception { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); ProviderManager mgr = makeProviderManager(); mgr.setApplicationEventPublisher(new MockApplicationEventPublisher(true)); @@ -108,7 +109,7 @@ public class ProviderManagerTests { @Test(expected=IllegalArgumentException.class) public void startupFailsIfProviderListDoesNotContainProviders() throws Exception { - List providers = new Vector(); + List providers = new ArrayList(); providers.add("THIS_IS_NOT_A_PROVIDER"); ProviderManager mgr = new ProviderManager(); @@ -143,7 +144,7 @@ public class ProviderManagerTests { return authentication; } - public boolean supports(Class authentication) { + public boolean supports(Class authentication) { return true; } }; @@ -196,7 +197,7 @@ public class ProviderManagerTests { private ProviderManager makeProviderManager() throws Exception { MockProvider provider1 = new MockProvider(); - List providers = new Vector(); + List providers = new ArrayList(); providers.add(provider1); ProviderManager mgr = new ProviderManager(); @@ -210,7 +211,7 @@ public class ProviderManagerTests { private ProviderManager makeProviderManagerWithMockProviderWhichReturnsNullInList() { MockProviderWhichReturnsNull provider1 = new MockProviderWhichReturnsNull(); MockProvider provider2 = new MockProvider(); - List providers = new Vector(); + List providers = new ArrayList(); providers.add(provider1); providers.add(provider2); @@ -231,7 +232,7 @@ public class ProviderManagerTests { } } - public boolean supports(Class authentication) { + public boolean supports(Class authentication) { if (TestingAuthenticationToken.class.isAssignableFrom(authentication)) { return true; } else { @@ -249,7 +250,7 @@ public class ProviderManagerTests { } } - public boolean supports(Class authentication) { + public boolean supports(Class authentication) { if (TestingAuthenticationToken.class.isAssignableFrom(authentication)) { return true; } else { @@ -263,7 +264,7 @@ public class ProviderManagerTests { throw new AccountStatusException("xxx") {}; } - public boolean supports(Class authentication) { + public boolean supports(Class authentication) { return true; } } @@ -273,7 +274,7 @@ public class ProviderManagerTests { throw new ConcurrentLoginException("xxx") {}; } - public boolean supports(Class authentication) { + public boolean supports(Class authentication) { return true; } } diff --git a/core/src/test/java/org/springframework/security/securechannel/ChannelDecisionManagerImplTests.java b/core/src/test/java/org/springframework/security/securechannel/ChannelDecisionManagerImplTests.java index 3617c3ece5..d1be400bae 100644 --- a/core/src/test/java/org/springframework/security/securechannel/ChannelDecisionManagerImplTests.java +++ b/core/src/test/java/org/springframework/security/securechannel/ChannelDecisionManagerImplTests.java @@ -41,6 +41,7 @@ import javax.servlet.ServletException; * @author Ben Alex * @version $Id$ */ +@SuppressWarnings("unchecked") public class ChannelDecisionManagerImplTests extends TestCase { //~ Methods ======================================================================================================== diff --git a/core/src/test/java/org/springframework/security/ui/basicauth/BasicProcessingFilterTests.java b/core/src/test/java/org/springframework/security/ui/basicauth/BasicProcessingFilterTests.java index e13218e915..c82750f8a3 100644 --- a/core/src/test/java/org/springframework/security/ui/basicauth/BasicProcessingFilterTests.java +++ b/core/src/test/java/org/springframework/security/ui/basicauth/BasicProcessingFilterTests.java @@ -15,43 +15,39 @@ package org.springframework.security.ui.basicauth; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.springframework.security.matcher.AuthenticationMatcher.anAuthenticationWithUsernameAndPassword; +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; + +import org.apache.commons.codec.binary.Base64; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.springframework.security.MockAuthenticationEntryPoint; -import org.springframework.security.MockAuthenticationManager; -import org.springframework.security.MockFilterConfig; -import org.springframework.security.MockApplicationEventPublisher; - -import org.springframework.security.context.SecurityContextHolder; - -import org.springframework.security.providers.ProviderManager; -import org.springframework.security.providers.dao.DaoAuthenticationProvider; - -import org.springframework.security.userdetails.UserDetails; -import org.springframework.security.userdetails.memory.InMemoryDaoImpl; -import org.springframework.security.userdetails.memory.UserMap; -import org.springframework.security.userdetails.memory.UserMapEditor; - -import org.apache.commons.codec.binary.Base64; - import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpSession; - -import java.io.IOException; - -import java.util.Arrays; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; +import org.springframework.security.Authentication; +import org.springframework.security.AuthenticationManager; +import org.springframework.security.BadCredentialsException; +import org.springframework.security.MockAuthenticationEntryPoint; +import org.springframework.security.MockAuthenticationManager; +import org.springframework.security.MockFilterConfig; +import org.springframework.security.context.SecurityContextHolder; +import org.springframework.security.providers.TestingAuthenticationToken; /** @@ -64,6 +60,7 @@ public class BasicProcessingFilterTests { //~ Instance fields ================================================================================================ private BasicProcessingFilter filter; + private Mockery jmock = new JUnit4Mockery(); //~ Methods ======================================================================================================== @@ -89,19 +86,14 @@ public class BasicProcessingFilterTests { public void setUp() throws Exception { SecurityContextHolder.clearContext(); - // Create User Details Service, provider and authentication manager - InMemoryDaoImpl dao = new InMemoryDaoImpl(); - UserMapEditor editor = new UserMapEditor(); - editor.setAsText("rod=koala,ROLE_ONE,ROLE_TWO,enabled\r\n"); - dao.setUserMap((UserMap) editor.getValue()); - - DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); - provider.setUserDetailsService(dao); - - ProviderManager manager = new ProviderManager(); - manager.setProviders(Arrays.asList(new Object[] {provider})); - manager.setApplicationEventPublisher(new MockApplicationEventPublisher()); - manager.afterPropertiesSet(); + final AuthenticationManager manager = jmock.mock(AuthenticationManager.class); + final Authentication rod = new TestingAuthenticationToken("rod", "koala", "ROLE_1"); + jmock.checking(new Expectations() {{ + allowing(manager).authenticate(with(anAuthenticationWithUsernameAndPassword("rod", "koala"))); + will(returnValue(rod)); + allowing(manager).authenticate(with(any(Authentication.class))); + will(throwException(new BadCredentialsException(""))); + }}); filter = new BasicProcessingFilter(); filter.setAuthenticationManager(manager); @@ -164,8 +156,8 @@ public class BasicProcessingFilterTests { executeFilterInContainerSimulator(filter, request, true); assertNotNull(SecurityContextHolder.getContext().getAuthentication()); - assertEquals("rod", - ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()); + assertEquals("rod", SecurityContextHolder.getContext().getAuthentication().getName()); + } @Test @@ -193,16 +185,11 @@ public class BasicProcessingFilterTests { } } - @Test + @Test(expected=IllegalArgumentException.class) public void testStartupDetectsMissingAuthenticationManager() throws Exception { - try { - BasicProcessingFilter filter = new BasicProcessingFilter(); - filter.setAuthenticationEntryPoint(new MockAuthenticationEntryPoint("x")); - filter.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - assertEquals("An AuthenticationManager is required", expected.getMessage()); - } + BasicProcessingFilter filter = new BasicProcessingFilter(); + filter.setAuthenticationEntryPoint(new MockAuthenticationEntryPoint("x")); + filter.afterPropertiesSet(); } @Test @@ -218,8 +205,7 @@ public class BasicProcessingFilterTests { executeFilterInContainerSimulator(filter, request, true); assertNotNull(SecurityContextHolder.getContext().getAuthentication()); - assertEquals("rod", - ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()); + assertEquals("rod", SecurityContextHolder.getContext().getAuthentication().getName()); // NOW PERFORM FAILED AUTHENTICATION // Setup our HTTP request @@ -249,7 +235,7 @@ public class BasicProcessingFilterTests { assertTrue(filter.isIgnoreFailure()); // Test - the filter chain will be invoked, as we've set ignoreFailure = true - MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, true); + executeFilterInContainerSimulator(filter, request, true); assertNull(SecurityContextHolder.getContext().getAuthentication()); } diff --git a/core/src/test/java/org/springframework/security/vote/AbstractAccessDecisionManagerTests.java b/core/src/test/java/org/springframework/security/vote/AbstractAccessDecisionManagerTests.java index c6c211a820..174002a2c3 100644 --- a/core/src/test/java/org/springframework/security/vote/AbstractAccessDecisionManagerTests.java +++ b/core/src/test/java/org/springframework/security/vote/AbstractAccessDecisionManagerTests.java @@ -32,27 +32,11 @@ import java.util.Vector; * @author Ben Alex * @version $Id$ */ +@SuppressWarnings("unchecked") public class AbstractAccessDecisionManagerTests extends TestCase { - //~ Constructors =================================================================================================== - - public AbstractAccessDecisionManagerTests() { - super(); - } - - public AbstractAccessDecisionManagerTests(String arg0) { - super(arg0); - } //~ Methods ======================================================================================================== - public static void main(String[] args) { - junit.textui.TestRunner.run(AbstractAccessDecisionManagerTests.class); - } - - public final void setUp() throws Exception { - super.setUp(); - } - public void testAllowIfAccessDecisionManagerDefaults() throws Exception { MockDecisionManagerImpl mock = new MockDecisionManagerImpl(); @@ -168,7 +152,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase { } private class MockStringOnlyVoter implements AccessDecisionVoter { - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { if (String.class.isAssignableFrom(clazz)) { return true; } else { diff --git a/core/src/test/java/org/springframework/security/vote/AffirmativeBasedTests.java b/core/src/test/java/org/springframework/security/vote/AffirmativeBasedTests.java index 393fb647fe..e14732aca3 100644 --- a/core/src/test/java/org/springframework/security/vote/AffirmativeBasedTests.java +++ b/core/src/test/java/org/springframework/security/vote/AffirmativeBasedTests.java @@ -41,7 +41,7 @@ public class AffirmativeBasedTests { RoleVoter roleVoter = new RoleVoter(); DenyVoter denyForSureVoter = new DenyVoter(); DenyAgainVoter denyAgainForSureVoter = new DenyAgainVoter(); - List voters = new ArrayList(); + List voters = new ArrayList(); voters.add(roleVoter); voters.add(denyForSureVoter); voters.add(denyAgainForSureVoter); diff --git a/core/src/test/java/org/springframework/security/vote/DenyAgainVoter.java b/core/src/test/java/org/springframework/security/vote/DenyAgainVoter.java index 903b613465..3d0363e910 100644 --- a/core/src/test/java/org/springframework/security/vote/DenyAgainVoter.java +++ b/core/src/test/java/org/springframework/security/vote/DenyAgainVoter.java @@ -47,7 +47,7 @@ public class DenyAgainVoter implements AccessDecisionVoter { } } - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { return true; } diff --git a/core/src/test/java/org/springframework/security/vote/DenyVoter.java b/core/src/test/java/org/springframework/security/vote/DenyVoter.java index bbdfe24cfa..0c16046485 100644 --- a/core/src/test/java/org/springframework/security/vote/DenyVoter.java +++ b/core/src/test/java/org/springframework/security/vote/DenyVoter.java @@ -41,7 +41,7 @@ public class DenyVoter implements AccessDecisionVoter { } } - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { return true; } diff --git a/openid/src/main/java/org/springframework/security/providers/openid/OpenIDAuthenticationProvider.java b/openid/src/main/java/org/springframework/security/providers/openid/OpenIDAuthenticationProvider.java index d26894572b..675dc545ca 100644 --- a/openid/src/main/java/org/springframework/security/providers/openid/OpenIDAuthenticationProvider.java +++ b/openid/src/main/java/org/springframework/security/providers/openid/OpenIDAuthenticationProvider.java @@ -99,7 +99,7 @@ public class OpenIDAuthenticationProvider implements AuthenticationProvider, Ini /* (non-Javadoc) * @see org.springframework.security.providers.AuthenticationProvider#supports(java.lang.Class) */ - public boolean supports(Class authentication) { + public boolean supports(Class authentication) { return OpenIDAuthenticationToken.class.isAssignableFrom(authentication); } } diff --git a/samples/contacts/src/main/java/sample/contact/AddPermissionController.java b/samples/contacts/src/main/java/sample/contact/AddPermissionController.java index 25793ec3bb..1e63c4d61a 100644 --- a/samples/contacts/src/main/java/sample/contact/AddPermissionController.java +++ b/samples/contacts/src/main/java/sample/contact/AddPermissionController.java @@ -65,8 +65,7 @@ public class AddPermissionController extends SimpleFormController implements Ini return showForm(request, response, errors); } - protected Object formBackingObject(HttpServletRequest request) - throws Exception { + protected Object formBackingObject(HttpServletRequest request) throws Exception { int contactId = ServletRequestUtils.getRequiredIntParameter(request, "contactId"); Contact contact = contactManager.getById(new Long(contactId)); @@ -77,13 +76,12 @@ public class AddPermissionController extends SimpleFormController implements Ini return addPermission; } - protected ModelAndView handleInvalidSubmit(HttpServletRequest request, HttpServletResponse response) - throws Exception { + protected ModelAndView handleInvalidSubmit(HttpServletRequest request, HttpServletResponse response) throws Exception { return disallowDuplicateFormSubmission(request, response); } - private Map listPermissions(HttpServletRequest request) { - Map map = new LinkedHashMap(); + private Map listPermissions(HttpServletRequest request) { + Map map = new LinkedHashMap(); map.put(new Integer(BasePermission.ADMINISTRATION.getMask()), getApplicationContext().getMessage("select.administer", null, "Administer", request.getLocale())); map.put(new Integer(BasePermission.READ.getMask()), @@ -94,15 +92,12 @@ public class AddPermissionController extends SimpleFormController implements Ini return map; } - private Map listRecipients(HttpServletRequest request) { - Map map = new LinkedHashMap(); + private Map listRecipients(HttpServletRequest request) { + Map map = new LinkedHashMap(); map.put("", getApplicationContext().getMessage("select.pleaseSelect", null, "-- please select --", request.getLocale())); - Iterator recipientsIter = contactManager.getAllRecipients().iterator(); - - while (recipientsIter.hasNext()) { - String recipient = (String) recipientsIter.next(); + for (String recipient : contactManager.getAllRecipients()) { map.put(recipient, recipient); } @@ -128,9 +123,10 @@ public class AddPermissionController extends SimpleFormController implements Ini return new ModelAndView(new RedirectView(getSuccessView())); } - protected Map referenceData(HttpServletRequest request) - throws Exception { - Map model = new HashMap(); + @Override + @SuppressWarnings("unchecked") + protected Map referenceData(HttpServletRequest request) throws Exception { + Map model = new HashMap(2); model.put("recipients", listRecipients(request)); model.put("permissions", listPermissions(request)); diff --git a/samples/contacts/src/main/java/sample/contact/ContactDao.java b/samples/contacts/src/main/java/sample/contact/ContactDao.java index 9c05056bd7..7ffbea38d0 100644 --- a/samples/contacts/src/main/java/sample/contact/ContactDao.java +++ b/samples/contacts/src/main/java/sample/contact/ContactDao.java @@ -31,11 +31,11 @@ public interface ContactDao { public void delete(Long contactId); - public List findAll(); + public List findAll(); - public List findAllPrincipals(); + public List findAllPrincipals(); - public List findAllRoles(); + public List findAllRoles(); public Contact getById(Long id); diff --git a/samples/contacts/src/main/java/sample/contact/ContactDaoSpring.java b/samples/contacts/src/main/java/sample/contact/ContactDaoSpring.java index a97a963963..f528ceb2b2 100644 --- a/samples/contacts/src/main/java/sample/contact/ContactDaoSpring.java +++ b/samples/contacts/src/main/java/sample/contact/ContactDaoSpring.java @@ -57,15 +57,15 @@ public class ContactDaoSpring extends JdbcDaoSupport implements ContactDao { contactDelete.delete(contactId); } - public List findAll() { + public List findAll() { return contactsAllQuery.execute(); } - public List findAllPrincipals() { + public List findAllPrincipals() { return principalsAllQuery.execute(); } - public List findAllRoles() { + public List findAllRoles() { return rolesAllQuery.execute(); } diff --git a/samples/contacts/src/main/java/sample/contact/ContactManager.java b/samples/contacts/src/main/java/sample/contact/ContactManager.java index 97cdb37af8..4658696250 100644 --- a/samples/contacts/src/main/java/sample/contact/ContactManager.java +++ b/samples/contacts/src/main/java/sample/contact/ContactManager.java @@ -44,10 +44,10 @@ public interface ContactManager { @PreAuthorize("hasRole('ROLE_USER')") @PostFilter("hasPermission(filterObject, 'read') or hasPermission(filterObject, admin)") - public List getAll(); + public List getAll(); @PreAuthorize("hasRole('ROLE_USER')") - public List getAllRecipients(); + public List getAllRecipients(); @PreAuthorize( "hasPermission(#id, 'sample.contact.Contact', read) or " + diff --git a/samples/contacts/src/main/java/sample/contact/ContactManagerBackend.java b/samples/contacts/src/main/java/sample/contact/ContactManagerBackend.java index 28f160887a..ae27478b7f 100644 --- a/samples/contacts/src/main/java/sample/contact/ContactManagerBackend.java +++ b/samples/contacts/src/main/java/sample/contact/ContactManagerBackend.java @@ -127,7 +127,7 @@ public class ContactManagerBackend extends ApplicationObjectSupport implements C } @Transactional(readOnly=true) - public List getAll() { + public List getAll() { if (logger.isDebugEnabled()) { logger.debug("Returning all contacts"); } @@ -136,12 +136,12 @@ public class ContactManagerBackend extends ApplicationObjectSupport implements C } @Transactional(readOnly=true) - public List getAllRecipients() { + public List getAllRecipients() { if (logger.isDebugEnabled()) { logger.debug("Returning all recipients"); } - List list = contactDao.findAllPrincipals(); + List list = contactDao.findAllPrincipals(); return list; } @@ -158,7 +158,7 @@ public class ContactManagerBackend extends ApplicationObjectSupport implements C /** * This is a public method. */ - @Transactional(readOnly=true) + @Transactional(readOnly=true) public Contact getRandomContact() { if (logger.isDebugEnabled()) { logger.debug("Returning random contact"); diff --git a/samples/dms/src/main/java/sample/dms/AbstractElement.java b/samples/dms/src/main/java/sample/dms/AbstractElement.java index c45c0ec975..1ed8ba6c5f 100755 --- a/samples/dms/src/main/java/sample/dms/AbstractElement.java +++ b/samples/dms/src/main/java/sample/dms/AbstractElement.java @@ -12,10 +12,10 @@ import org.springframework.util.Assert; * */ public abstract class AbstractElement { - /** The name of this token (ie filename or directory segment name */ + /** The name of this token (a filename or directory segment name */ private String name; - /** The parent of this token (ie directory, or null if referring to root) */ + /** The parent of this token (a directory, or null if referring to root) */ private AbstractElement parent; /** The database identifier for this object (null if not persisted) */ @@ -63,7 +63,7 @@ public abstract class AbstractElement { * @return the fully-qualified name of this element, including any parents */ public String getFullName() { - List strings = new ArrayList(); + List strings = new ArrayList(); AbstractElement currentElement = this; while (currentElement != null) { strings.add(0, currentElement.getName()); @@ -72,8 +72,8 @@ public abstract class AbstractElement { StringBuffer sb = new StringBuffer(); String lastCharacter = null; - for (Iterator i = strings.iterator(); i.hasNext();) { - String token = (String) i.next(); + for (Iterator i = strings.iterator(); i.hasNext();) { + String token = i.next(); if (!"/".equals(lastCharacter) && lastCharacter != null) { sb.append("/"); }