Browse Source

SEC-1012: Adding generics and general tidying up of tests etc

Luke Taylor 17 years ago
parent
commit
67c06d3d52
43 changed files with 444 additions and 531 deletions
  1. 12 12
      acl/src/main/java/org/springframework/security/acls/domain/BasePermission.java
  2. 4 4
      acl/src/main/java/org/springframework/security/afterinvocation/AbstractAclProvider.java
  3. 1 1
      acl/src/main/java/org/springframework/security/vote/AclEntryVoter.java
  4. 1 1
      core/src/main/java/org/springframework/security/AccessDecisionManager.java
  5. 1 1
      core/src/main/java/org/springframework/security/AfterInvocationManager.java
  6. 1 1
      core/src/main/java/org/springframework/security/afterinvocation/AfterInvocationProvider.java
  7. 1 1
      core/src/main/java/org/springframework/security/afterinvocation/AfterInvocationProviderManager.java
  8. 21 23
      core/src/main/java/org/springframework/security/authoritymapping/MapBasedAttributes2GrantedAuthoritiesMapper.java
  9. 5 3
      core/src/main/java/org/springframework/security/authoritymapping/MappableAttributesRetriever.java
  10. 10 9
      core/src/main/java/org/springframework/security/authoritymapping/SimpleMappableAttributesRetriever.java
  11. 16 14
      core/src/main/java/org/springframework/security/authoritymapping/XmlMappableAttributesRetriever.java
  12. 3 2
      core/src/main/java/org/springframework/security/config/FilterChainProxyPostProcessor.java
  13. 57 57
      core/src/main/java/org/springframework/security/config/SessionRegistryInjectionBeanPostProcessor.java
  14. 1 1
      core/src/main/java/org/springframework/security/expression/method/MethodExpressionAfterInvocationProvider.java
  15. 54 54
      core/src/main/java/org/springframework/security/ui/AuthenticationDetailsSourceImpl.java
  16. 4 4
      core/src/main/java/org/springframework/security/ui/WebAuthenticationDetailsSource.java
  17. 3 3
      core/src/main/java/org/springframework/security/ui/preauth/j2ee/AbstractPreAuthenticatedAuthenticationDetailsSource.java
  18. 5 4
      core/src/main/java/org/springframework/security/ui/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.java
  19. 1 1
      core/src/main/java/org/springframework/security/ui/switchuser/SwitchUserAuthorityChanger.java
  20. 8 11
      core/src/main/java/org/springframework/security/userdetails/memory/UserAttribute.java
  21. 3 3
      core/src/main/java/org/springframework/security/userdetails/memory/UserAttributeEditor.java
  22. 24 35
      core/src/main/java/org/springframework/security/util/MethodInvocationUtils.java
  23. 1 1
      core/src/main/java/org/springframework/security/vote/AbstractAccessDecisionManager.java
  24. 1 1
      core/src/test/java/org/springframework/security/MockAccessDecisionManager.java
  25. 1 1
      core/src/test/java/org/springframework/security/MockAfterInvocationManager.java
  26. 1 1
      core/src/test/java/org/springframework/security/afterinvocation/AfterInvocationProviderManagerTests.java
  27. 2 2
      core/src/test/java/org/springframework/security/annotation/BusinessService.java
  28. 1 1
      core/src/test/java/org/springframework/security/annotation/BusinessServiceImpl.java
  29. 1 1
      core/src/test/java/org/springframework/security/annotation/ExpressionProtectedBusinessServiceImpl.java
  30. 3 3
      core/src/test/java/org/springframework/security/annotation/Jsr250BusinessServiceImpl.java
  31. 10 10
      core/src/test/java/org/springframework/security/authoritymapping/SimpleMappableRolesRetrieverTests.java
  32. 2 2
      core/src/test/java/org/springframework/security/authoritymapping/SimpleRoles2GrantedAuthoritiesMapperTests.java
  33. 84 84
      core/src/test/java/org/springframework/security/authoritymapping/XmlMappableRolesRetrieverTests.java
  34. 2 2
      core/src/test/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParserTests.java
  35. 1 1
      core/src/test/java/org/springframework/security/config/MockAfterInvocationProvider.java
  36. 20 36
      core/src/test/java/org/springframework/security/intercept/method/MethodInvocationPrivilegeEvaluatorTests.java
  37. 2 2
      core/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorTests.java
  38. 2 19
      core/src/test/java/org/springframework/security/intercept/method/aspectj/AspectJSecurityInterceptorTests.java
  39. 14 34
      core/src/test/java/org/springframework/security/providers/UsernamePasswordAuthenticationTokenTests.java
  40. 18 40
      core/src/test/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationTokenTests.java
  41. 22 22
      core/src/test/java/org/springframework/security/ui/preauth/j2ee/WebXmlJ2eeDefinedRolesRetrieverTests.java
  42. 14 18
      core/src/test/java/org/springframework/security/ui/switchuser/SwitchUserProcessingFilterTests.java
  43. 6 5
      portlet/src/main/java/org/springframework/security/ui/portlet/PortletPreAuthenticatedAuthenticationDetailsSource.java

+ 12 - 12
acl/src/main/java/org/springframework/security/acls/domain/BasePermission.java

@@ -19,12 +19,12 @@ import org.springframework.security.acls.Permission;
 
 /**
  * A set of standard permissions.
- * 
+ *
  * <p>
  * You may subclass this class to add additional permissions, or use this class as a guide
  * for creating your own permission classes.
  * </p>
- * 
+ *
  * @author Ben Alex
  * @version $Id$
  */
@@ -34,25 +34,25 @@ public class BasePermission extends AbstractPermission {
     public static final Permission CREATE = new BasePermission(1 << 2, 'C'); // 4
     public static final Permission DELETE = new BasePermission(1 << 3, 'D'); // 8
     public static final Permission ADMINISTRATION = new BasePermission(1 << 4, 'A'); // 16
-    
-	protected static DefaultPermissionFactory defaultPermissionFactory = new DefaultPermissionFactory();
 
-	/**
+    protected static DefaultPermissionFactory defaultPermissionFactory = new DefaultPermissionFactory();
+
+    /**
      * Registers the public static permissions defined on this class. This is mandatory so
      * that the static methods will operate correctly.
      */
     static {
-    	registerPermissionsFor(BasePermission.class);
+        registerPermissionsFor(BasePermission.class);
     }
 
     protected BasePermission(int mask, char code) {
-    	super(mask, code);
+        super(mask, code);
     }
 
-    protected final static void registerPermissionsFor(Class subClass) {
-    	defaultPermissionFactory.registerPublicPermissions(subClass);
+    protected final static void registerPermissionsFor(Class<?> subClass) {
+        defaultPermissionFactory.registerPublicPermissions(subClass);
     }
-    
+
     public final static Permission buildFromMask(int mask) {
         return defaultPermissionFactory.buildFromMask(mask);
     }
@@ -62,11 +62,11 @@ public class BasePermission extends AbstractPermission {
     }
 
     public final static Permission buildFromName(String name) {
-    	return defaultPermissionFactory.buildFromName(name);
+        return defaultPermissionFactory.buildFromName(name);
     }
 
     public final static Permission[] buildFromName(String[] names) {
         return defaultPermissionFactory.buildFromName(names);
     }
 
-}
+}

+ 4 - 4
acl/src/main/java/org/springframework/security/afterinvocation/AbstractAclProvider.java

@@ -43,7 +43,7 @@ public abstract class AbstractAclProvider implements AfterInvocationProvider {
     //~ Instance fields ================================================================================================
 
     protected AclService aclService;
-    protected Class processDomainObjectClass = Object.class;
+    protected Class<?> processDomainObjectClass = Object.class;
     protected ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy = new ObjectIdentityRetrievalStrategyImpl();
     protected SidRetrievalStrategy sidRetrievalStrategy = new SidRetrievalStrategyImpl();
     protected String processConfigAttribute;
@@ -66,7 +66,7 @@ public abstract class AbstractAclProvider implements AfterInvocationProvider {
 
     //~ Methods ========================================================================================================
 
-    protected Class getProcessDomainObjectClass() {
+    protected Class<?> getProcessDomainObjectClass() {
         return processDomainObjectClass;
     }
 
@@ -99,7 +99,7 @@ public abstract class AbstractAclProvider implements AfterInvocationProvider {
         this.processConfigAttribute = processConfigAttribute;
     }
 
-    public void setProcessDomainObjectClass(Class processDomainObjectClass) {
+    public void setProcessDomainObjectClass(Class<?> processDomainObjectClass) {
         Assert.notNull(processDomainObjectClass, "processDomainObjectClass cannot be set to null");
         this.processDomainObjectClass = processDomainObjectClass;
     }
@@ -120,7 +120,7 @@ public abstract class AbstractAclProvider implements AfterInvocationProvider {
      *
      * @return always <code>true</code>
      */
-    public boolean supports(Class<? extends Object> clazz) {
+    public boolean supports(Class<?> clazz) {
         return true;
     }
 }

+ 1 - 1
acl/src/main/java/org/springframework/security/vote/AclEntryVoter.java

@@ -173,7 +173,7 @@ public class AclEntryVoter extends AbstractAclVoter {
             // Evaluate if we are required to use an inner domain object
             if (StringUtils.hasText(internalMethod)) {
                 try {
-                    Class clazz = domainObject.getClass();
+                    Class<?> clazz = domainObject.getClass();
                     Method method = clazz.getMethod(internalMethod, new Class[0]);
                     domainObject = method.invoke(domainObject, new Object[0]);
                 } catch (NoSuchMethodException nsme) {

+ 1 - 1
core/src/main/java/org/springframework/security/AccessDecisionManager.java

@@ -63,5 +63,5 @@ public interface AccessDecisionManager {
      *
      * @return <code>true</code> if the implementation can process the indicated class
      */
-    boolean supports(Class clazz);
+    boolean supports(Class<?> clazz);
 }

+ 1 - 1
core/src/main/java/org/springframework/security/AfterInvocationManager.java

@@ -87,5 +87,5 @@ public interface AfterInvocationManager {
      *
      * @return <code>true</code> if the implementation can process the indicated class
      */
-    boolean supports(Class clazz);
+    boolean supports(Class<?> clazz);
 }

+ 1 - 1
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<? extends Object> clazz);
+    boolean supports(Class<?> clazz);
 }

+ 1 - 1
core/src/main/java/org/springframework/security/afterinvocation/AfterInvocationProviderManager.java

@@ -122,7 +122,7 @@ public class AfterInvocationProviderManager implements AfterInvocationManager, I
      * @return if the <code>AfterInvocationProviderManager</code> can support the secure object class, which requires
      *         every one of its <code>AfterInvocationProvider</code>s to support the secure object class
      */
-    public boolean supports(Class clazz) {
+    public boolean supports(Class<?> clazz) {
         Iterator iter = this.providers.iterator();
 
         while (iter.hasNext()) {

+ 21 - 23
core/src/main/java/org/springframework/security/authoritymapping/MapBasedAttributes2GrantedAuthoritiesMapper.java

@@ -2,10 +2,11 @@ package org.springframework.security.authoritymapping;
 
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Collections;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 import java.util.StringTokenizer;
 
 import org.springframework.beans.factory.InitializingBean;
@@ -14,7 +15,6 @@ import org.springframework.security.GrantedAuthorityImpl;
 import org.springframework.util.Assert;
 import org.springframework.util.StringUtils;
 
-
 /**
  * This class implements the Attributes2GrantedAuthoritiesMapper and
  * MappableAttributesRetriever interfaces based on the supplied Map.
@@ -27,7 +27,7 @@ import org.springframework.util.StringUtils;
 public class MapBasedAttributes2GrantedAuthoritiesMapper implements Attributes2GrantedAuthoritiesMapper, MappableAttributesRetriever, InitializingBean {
     private Map<String, Collection<GrantedAuthority>> attributes2grantedAuthoritiesMap = null;
     private String stringSeparator = ",";
-    private String[] mappableAttributes = null;
+    private Set<String> mappableAttributes = null;
 
 
     public void afterPropertiesSet() throws Exception {
@@ -51,21 +51,17 @@ public class MapBasedAttributes2GrantedAuthoritiesMapper implements Attributes2G
     /**
      * @return Returns the attributes2grantedAuthoritiesMap.
      */
-    public Map getAttributes2grantedAuthoritiesMap() {
+    public Map<String, Collection<GrantedAuthority>> getAttributes2grantedAuthoritiesMap() {
         return attributes2grantedAuthoritiesMap;
     }
     /**
      * @param attributes2grantedAuthoritiesMap The attributes2grantedAuthoritiesMap to set.
      */
-    public void setAttributes2grantedAuthoritiesMap(final Map<String, Object> attributes2grantedAuthoritiesMap) {
+    public void setAttributes2grantedAuthoritiesMap(final Map attributes2grantedAuthoritiesMap) {
         Assert.notEmpty(attributes2grantedAuthoritiesMap,"A non-empty attributes2grantedAuthoritiesMap must be supplied");
         this.attributes2grantedAuthoritiesMap = preProcessMap(attributes2grantedAuthoritiesMap);
 
-        try {
-            mappableAttributes = (String[])this.attributes2grantedAuthoritiesMap.keySet().toArray(new String[]{});
-        } catch ( ArrayStoreException ase ) {
-            throw new IllegalArgumentException("attributes2grantedAuthoritiesMap contains non-String objects as keys");
-        }
+        mappableAttributes = Collections.unmodifiableSet(this.attributes2grantedAuthoritiesMap.keySet());
     }
 
     /**
@@ -74,11 +70,14 @@ public class MapBasedAttributes2GrantedAuthoritiesMapper implements Attributes2G
      * @param orgMap The map to process
      * @return the processed Map
      */
-    private Map<String, Collection<GrantedAuthority>> preProcessMap(Map<String, Object> orgMap) {
-        Map result = new HashMap(orgMap.size());
-
-        for(Map.Entry entry : orgMap.entrySet()) {
-            result.put(entry.getKey(),getGrantedAuthorityCollection(entry.getValue()));
+    private Map<String, Collection<GrantedAuthority>> preProcessMap(Map<?, ?> orgMap) {
+        Map<String, Collection<GrantedAuthority>> result =
+            new HashMap<String, Collection<GrantedAuthority>>(orgMap.size());
+
+        for(Map.Entry<?,?> entry : orgMap.entrySet()) {
+            Assert.isInstanceOf(String.class, entry.getKey(),
+                    "attributes2grantedAuthoritiesMap contains non-String objects as keys");
+            result.put((String)entry.getKey(),getGrantedAuthorityCollection(entry.getValue()));
         }
         return result;
     }
@@ -90,8 +89,8 @@ public class MapBasedAttributes2GrantedAuthoritiesMapper implements Attributes2G
      *            The value to convert to a GrantedAuthority Collection
      * @return Collection containing the GrantedAuthority Collection
      */
-    private Collection getGrantedAuthorityCollection(Object value) {
-        Collection result = new ArrayList();
+    private Collection<GrantedAuthority> getGrantedAuthorityCollection(Object value) {
+        Collection<GrantedAuthority> result = new ArrayList<GrantedAuthority>();
         addGrantedAuthorityCollection(result,value);
         return result;
     }
@@ -109,7 +108,7 @@ public class MapBasedAttributes2GrantedAuthoritiesMapper implements Attributes2G
             return;
         }
         if ( value instanceof Collection ) {
-            addGrantedAuthorityCollection(result,(Collection)value);
+            addGrantedAuthorityCollection(result,(Collection<?>)value);
         } else if ( value instanceof Object[] ) {
             addGrantedAuthorityCollection(result,(Object[])value);
         } else if ( value instanceof String ) {
@@ -121,10 +120,9 @@ public class MapBasedAttributes2GrantedAuthoritiesMapper implements Attributes2G
         }
     }
 
-    private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, Collection value) {
-        Iterator it = value.iterator();
-        while ( it.hasNext() ) {
-            addGrantedAuthorityCollection(result,it.next());
+    private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, Collection<?> value) {
+        for(Object elt : value) {
+            addGrantedAuthorityCollection(result, elt);
         }
     }
 
@@ -148,7 +146,7 @@ public class MapBasedAttributes2GrantedAuthoritiesMapper implements Attributes2G
      *
      * @see org.springframework.security.authoritymapping.MappableAttributesRetriever#getMappableAttributes()
      */
-    public String[] getMappableAttributes() {
+    public Set<String> getMappableAttributes() {
         return mappableAttributes;
     }
     /**

+ 5 - 3
core/src/main/java/org/springframework/security/authoritymapping/MappableAttributesRetriever.java

@@ -1,5 +1,7 @@
 package org.springframework.security.authoritymapping;
 
+import java.util.Set;
+
 /**
  * Interface to be implemented by classes that can retrieve a list of mappable
  * security attribute strings (for example the list of all available J2EE roles in a web or EJB
@@ -10,10 +12,10 @@ package org.springframework.security.authoritymapping;
  */
 public interface MappableAttributesRetriever {
     /**
-     * Implementations of this method should return a list of all string attributes which
+     * Implementations of this method should return a set of all string attributes which
      * can be mapped to <tt>GrantedAuthority</tt>s.
      *
-     * @return list of all mappable roles
+     * @return set of all mappable roles
      */
-    String[] getMappableAttributes();
+    Set<String> getMappableAttributes();
 }

+ 10 - 9
core/src/main/java/org/springframework/security/authoritymapping/SimpleMappableAttributesRetriever.java

@@ -1,6 +1,9 @@
 package org.springframework.security.authoritymapping;
 
-import org.springframework.util.Assert;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
 
 /**
  * This class implements the MappableAttributesRetriever interface by just returning
@@ -11,23 +14,21 @@ import org.springframework.util.Assert;
  * @since 2.0
  */
 public class SimpleMappableAttributesRetriever implements MappableAttributesRetriever {
-    private String[] mappableAttributes = null;
+    private Set<String> mappableAttributes = null;
 
     /*
      * (non-Javadoc)
      *
      * @see org.springframework.security.authoritymapping.MappableAttributesRetriever#getMappableAttributes()
      */
-    public String[] getMappableAttributes() {
-        Assert.notNull(mappableAttributes, "No mappable roles have been set");
-        String[] copy = new String[mappableAttributes.length];
-        System.arraycopy(mappableAttributes, 0, copy, 0, copy.length);
-        return copy;
+    public Set<String> getMappableAttributes() {
+        return mappableAttributes;
     }
 
     public void setMappableAttributes(String[] aMappableRoles) {
-        this.mappableAttributes = new String[aMappableRoles.length];
-        System.arraycopy(aMappableRoles, 0, mappableAttributes, 0, mappableAttributes.length);
+        mappableAttributes = new HashSet<String>(aMappableRoles.length);
+        mappableAttributes.addAll(Arrays.asList(aMappableRoles));
+        mappableAttributes = Collections.unmodifiableSet(mappableAttributes);
     }
 
 }

+ 16 - 14
core/src/main/java/org/springframework/security/authoritymapping/XmlMappableAttributesRetriever.java

@@ -5,7 +5,10 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.io.StringReader;
 import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
 import java.util.List;
+import java.util.Set;
 
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
@@ -41,7 +44,7 @@ import org.xml.sax.SAXException;
 public abstract class XmlMappableAttributesRetriever implements MappableAttributesRetriever, InitializingBean {
     private static final Log logger = LogFactory.getLog(XmlMappableAttributesRetriever.class);
 
-    private String[] mappableAttributes = null;
+    private Set<String> mappableAttributes = null;
 
     private InputStream xmlInputStream = null;
 
@@ -55,27 +58,25 @@ public abstract class XmlMappableAttributesRetriever implements MappableAttribut
     public void afterPropertiesSet() throws Exception {
         Assert.notNull(xmlInputStream, "An XML InputStream must be set");
         Assert.notNull(xpathExpression, "An XPath expression must be set");
-        mappableAttributes = getMappableAttributes(xmlInputStream);
+        mappableAttributes = Collections.unmodifiableSet(getMappableAttributes(xmlInputStream));
     }
 
-    public String[] getMappableAttributes() {
-        String[] copy = new String[mappableAttributes.length];
-        System.arraycopy(mappableAttributes, 0, copy, 0, copy.length);
-        return copy;
+    public Set<String> getMappableAttributes() {
+        return mappableAttributes;
     }
 
     /**
      * Get the mappable roles from the specified XML document.
      */
-    private String[] getMappableAttributes(InputStream aStream) {
+    private Set<String> getMappableAttributes(InputStream aStream) {
         if (logger.isDebugEnabled()) {
             logger.debug("Reading mappable attributes from XML document");
         }
         try {
             Document doc = getDocument(aStream);
-            String[] roles = getMappableAttributes(doc);
+            Set<String> roles = getMappableAttributes(doc);
             if (logger.isDebugEnabled()) {
-                logger.debug("Mappable attributes from XML document: " + Arrays.asList(roles));
+                logger.debug("Mappable attributes from XML document: " + roles);
             }
             return roles;
         } finally {
@@ -118,13 +119,14 @@ public abstract class XmlMappableAttributesRetriever implements MappableAttribut
      * @return String[] the list of roles.
      * @throws JaxenException
      */
-    private String[] getMappableAttributes(Document doc) {
+    private Set<String> getMappableAttributes(Document doc) {
         try {
             DOMXPath xpath = new DOMXPath(xpathExpression);
-            List roleElements = xpath.selectNodes(doc);
-            String[] roles = new String[roleElements.size()];
-            for (int i = 0; i < roles.length; i++) {
-                roles[i] = ((Node) roleElements.get(i)).getNodeValue();
+            List<Node> roleElements = xpath.selectNodes(doc);
+            Set<String> roles = new HashSet<String>(roleElements.size());
+
+            for (Node n : roleElements) {
+                roles.add(n.getNodeValue());
             }
             return roles;
         } catch (JaxenException e) {

+ 3 - 2
core/src/main/java/org/springframework/security/config/FilterChainProxyPostProcessor.java

@@ -43,6 +43,7 @@ public class FilterChainProxyPostProcessor implements BeanPostProcessor, BeanFac
 
     private ListableBeanFactory beanFactory;
 
+    @SuppressWarnings("unchecked")
     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
         if(!BeanIds.FILTER_CHAIN_PROXY.equals(beanName)) {
             return bean;
@@ -51,7 +52,7 @@ public class FilterChainProxyPostProcessor implements BeanPostProcessor, BeanFac
         FilterChainProxy filterChainProxy = (FilterChainProxy) bean;
         FilterChainList filterList = (FilterChainList) beanFactory.getBean(BeanIds.FILTER_LIST);
 
-        List filters = new ArrayList(filterList.getFilters());
+        List<Filter> filters = new ArrayList<Filter>(filterList.getFilters());
         Collections.sort(filters, new OrderComparator());
 
         logger.info("Checking sorted filter chain: " + filters);
@@ -82,7 +83,7 @@ public class FilterChainProxyPostProcessor implements BeanPostProcessor, BeanFac
         checkFilterStack(filters);
 
         // Note that this returns a copy
-        Map filterMap = filterChainProxy.getFilterChainMap();
+        Map<String, List<Filter>> filterMap = filterChainProxy.getFilterChainMap();
         filterMap.put(filterChainProxy.getMatcher().getUniversalMatchPattern(), filters);
         filterChainProxy.setFilterChainMap(filterMap);
 

+ 57 - 57
core/src/main/java/org/springframework/security/config/SessionRegistryInjectionBeanPostProcessor.java

@@ -18,16 +18,16 @@ import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 
 /**
- * Registered by the <tt>AuthenticationManagerBeanDefinitionParser</tt> if an external 
- * ConcurrentSessionController is set (and hence an external SessionRegistry). 
+ * Registered by the <tt>AuthenticationManagerBeanDefinitionParser</tt> if an external
+ * ConcurrentSessionController is set (and hence an external SessionRegistry).
  * Its responsibility is to set the SessionRegistry on namespace-registered beans which require access
  * to it.
  * <p>
  * It will attempt to read the registry directly from the registered controller. If that fails, it will look in
  * the application context for a registered SessionRegistry bean.
- * 
- * See SEC-879. 
- * 
+ *
+ * See SEC-879.
+ *
  * @author Luke Taylor
  * @since 2.0.3
  */
@@ -38,57 +38,57 @@ class SessionRegistryInjectionBeanPostProcessor implements BeanPostProcessor, Be
     private final String controllerBeanName;
 
     SessionRegistryInjectionBeanPostProcessor(String controllerBeanName) {
-    	this.controllerBeanName = controllerBeanName;
+        this.controllerBeanName = controllerBeanName;
+    }
+
+    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
+        if (BeanIds.FORM_LOGIN_FILTER.equals(beanName) ||
+                BeanIds.OPEN_ID_FILTER.equals(beanName)) {
+            ((AbstractProcessingFilter) bean).setSessionRegistry(getSessionRegistry());
+        } else if (BeanIds.SESSION_FIXATION_PROTECTION_FILTER.equals(beanName)) {
+            ((SessionFixationProtectionFilter)bean).setSessionRegistry(getSessionRegistry());
+        }
+
+        return bean;
+    }
+
+    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
+        return bean;
+    }
+
+    private SessionRegistry getSessionRegistry() {
+        if (sessionRegistry != null) {
+            return sessionRegistry;
+        }
+
+        logger.info("Attempting to read SessionRegistry from registered ConcurrentSessionController bean");
+
+        ConcurrentSessionController controller = (ConcurrentSessionController) beanFactory.getBean(controllerBeanName);
+
+        if (controller instanceof ConcurrentSessionControllerImpl) {
+            sessionRegistry = ((ConcurrentSessionControllerImpl)controller).getSessionRegistry();
+
+            return sessionRegistry;
+        }
+
+        logger.info("ConcurrentSessionController is not a standard implementation. SessionRegistry could not be read from it. Looking for it in the context.");
+
+        List<SessionRegistry> sessionRegs = new ArrayList<SessionRegistry>(beanFactory.getBeansOfType(SessionRegistry.class).values());
+
+        if (sessionRegs.size() == 0) {
+            throw new SecurityConfigurationException("concurrent-session-controller-ref was set but no SessionRegistry could be obtained from the application context.");
+        }
+
+        if (sessionRegs.size() > 1) {
+            logger.warn("More than one SessionRegistry instance in application context. Possible configuration errors may result.");
+        }
+
+        sessionRegistry = (SessionRegistry) sessionRegs.get(0);
+
+        return sessionRegistry;
+    }
+
+    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
+        this.beanFactory = (ListableBeanFactory) beanFactory;
     }
-    
-	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
-		if (BeanIds.FORM_LOGIN_FILTER.equals(beanName) || 
-				BeanIds.OPEN_ID_FILTER.equals(beanName)) {
-			((AbstractProcessingFilter) bean).setSessionRegistry(getSessionRegistry());
-		} else if (BeanIds.SESSION_FIXATION_PROTECTION_FILTER.equals(beanName)) {
-			((SessionFixationProtectionFilter)bean).setSessionRegistry(getSessionRegistry());
-		}
-
-		return bean;
-	}	
-	
-	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
-		return bean;
-	}
-	
-	private SessionRegistry getSessionRegistry() {
-		if (sessionRegistry != null) {
-			return sessionRegistry;
-		}
-		
-		logger.info("Attempting to read SessionRegistry from registered ConcurrentSessionController bean");
-		
-		ConcurrentSessionController controller = (ConcurrentSessionController) beanFactory.getBean(controllerBeanName);
-		
-		if (controller instanceof ConcurrentSessionControllerImpl) {
-			sessionRegistry = ((ConcurrentSessionControllerImpl)controller).getSessionRegistry();
-			
-			return sessionRegistry;
-		}
-
-		logger.info("ConcurrentSessionController is not a standard implementation. SessionRegistry could not be read from it. Looking for it in the context.");
-		
-		List sessionRegs = new ArrayList(beanFactory.getBeansOfType(SessionRegistry.class).values());
-		
-		if (sessionRegs.size() == 0) {			
-			throw new SecurityConfigurationException("concurrent-session-controller-ref was set but no SessionRegistry could be obtained from the application context.");
-		}
-		
-		if (sessionRegs.size() > 1) {
-			logger.warn("More than one SessionRegistry instance in application context. Possible configuration errors may result.");
-		}
-		
-		sessionRegistry = (SessionRegistry) sessionRegs.get(0);
-		
-		return sessionRegistry;
-	}
-
-	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
-		this.beanFactory = (ListableBeanFactory) beanFactory;
-	}
 }

+ 1 - 1
core/src/main/java/org/springframework/security/expression/method/MethodExpressionAfterInvocationProvider.java

@@ -86,7 +86,7 @@ public class MethodExpressionAfterInvocationProvider implements AfterInvocationP
         return attribute instanceof PostInvocationExpressionAttribute;
     }
 
-    public boolean supports(Class<? extends Object> clazz) {
+    public boolean supports(Class<?> clazz) {
         return clazz.isAssignableFrom(MethodInvocation.class);
     }
 

+ 54 - 54
core/src/main/java/org/springframework/security/ui/AuthenticationDetailsSourceImpl.java

@@ -14,68 +14,68 @@ import org.springframework.util.ReflectionUtils;
  * Any object that accepts an <code>Object</code> as its sole constructor can
  * be used instead of this default.
  * </p>
- * 
+ *
  * @author Ruud Senden
  * @since 2.0
  */
 public class AuthenticationDetailsSourceImpl implements AuthenticationDetailsSource {
-	//~ Instance fields ================================================================================================
+    //~ Instance fields ================================================================================================
 
-	private Class clazz = AuthenticationDetails.class;
-	
-	//~ Methods ========================================================================================================
+    private Class<?> clazz = AuthenticationDetails.class;
 
-	public Object buildDetails(Object context) {
-		try {
-			Constructor constructor = getFirstMatchingConstructor(context);
-			return constructor.newInstance(new Object[] { context });
-		} catch (NoSuchMethodException ex) {
-			ReflectionUtils.handleReflectionException(ex);
-		} catch (InvocationTargetException ex) {
-			ReflectionUtils.handleReflectionException(ex);
-		} catch (InstantiationException ex) {
-			ReflectionUtils.handleReflectionException(ex);
-		} catch (IllegalAccessException ex) {
-			ReflectionUtils.handleReflectionException(ex);
-		}
+    //~ Methods ========================================================================================================
 
-		return null;
-	}
+    public Object buildDetails(Object context) {
+        try {
+            Constructor<?> constructor = getFirstMatchingConstructor(context);
+            return constructor.newInstance(new Object[] { context });
+        } catch (NoSuchMethodException ex) {
+            ReflectionUtils.handleReflectionException(ex);
+        } catch (InvocationTargetException ex) {
+            ReflectionUtils.handleReflectionException(ex);
+        } catch (InstantiationException ex) {
+            ReflectionUtils.handleReflectionException(ex);
+        } catch (IllegalAccessException ex) {
+            ReflectionUtils.handleReflectionException(ex);
+        }
 
-	/**
-	 * Return the first matching constructor that can take the given object
-	 * as an argument. Please note that we cannot use 
-	 * getDeclaredConstructor(new Class[]{object.getClass()})
-	 * as this will only match if the constructor argument type matches
-	 * the object type exactly (instead of checking whether it is assignable)
-	 * 
-	 * @param object the object for which to find a matching constructor
-	 * @return a matching constructor for the given object
-	 * @throws NoSuchMethodException if no matching constructor can be found
-	 */
-	private Constructor getFirstMatchingConstructor(Object object) throws NoSuchMethodException {
-		Constructor[] constructors = clazz.getDeclaredConstructors();
-		Constructor constructor = null;
-		for (int i = 0; i < constructors.length; i++) {
-			Class[] parameterTypes = constructors[i].getParameterTypes();
-			if (parameterTypes.length == 1 && (object == null || parameterTypes[0].isInstance(object))) {
-				constructor = constructors[i];
-				break;
-			}
-		}
+        return null;
+    }
 
-		if (constructor == null) {
-			if (object == null) {
-				throw new NoSuchMethodException("No constructor found that can take a single argument");
-			} else {
-				throw new NoSuchMethodException("No constructor found that can take a single argument of type " + object.getClass());
-			}
-		}
-		return constructor;
-	}
+    /**
+     * Return the first matching constructor that can take the given object
+     * as an argument. Please note that we cannot use
+     * getDeclaredConstructor(new Class[]{object.getClass()})
+     * as this will only match if the constructor argument type matches
+     * the object type exactly (instead of checking whether it is assignable)
+     *
+     * @param object the object for which to find a matching constructor
+     * @return a matching constructor for the given object
+     * @throws NoSuchMethodException if no matching constructor can be found
+     */
+    private Constructor<?> getFirstMatchingConstructor(Object object) throws NoSuchMethodException {
+        Constructor<?>[] constructors = clazz.getDeclaredConstructors();
+        Constructor<?> constructor = null;
+        for (int i = 0; i < constructors.length; i++) {
+            Class<?>[] parameterTypes = constructors[i].getParameterTypes();
+            if (parameterTypes.length == 1 && (object == null || parameterTypes[0].isInstance(object))) {
+                constructor = constructors[i];
+                break;
+            }
+        }
 
-	public void setClazz(Class clazz) {
-		Assert.notNull(clazz, "Class required");
-		this.clazz = clazz;
-	}
+        if (constructor == null) {
+            if (object == null) {
+                throw new NoSuchMethodException("No constructor found that can take a single argument");
+            } else {
+                throw new NoSuchMethodException("No constructor found that can take a single argument of type " + object.getClass());
+            }
+        }
+        return constructor;
+    }
+
+    public void setClazz(Class<?> clazz) {
+        Assert.notNull(clazz, "Class required");
+        this.clazz = clazz;
+    }
 }

+ 4 - 4
core/src/main/java/org/springframework/security/ui/WebAuthenticationDetailsSource.java

@@ -28,7 +28,7 @@ import javax.servlet.http.HttpServletRequest;
  * Implementation of {@link AuthenticationDetailsSource} which builds the details object from
  * an <tt>HttpServletRequest</tt> object.
  * <p>
- * By default will create an instance of <code>WebAuthenticationDetails</code>. Any object that accepts a 
+ * By default will create an instance of <code>WebAuthenticationDetails</code>. Any object that accepts a
  * <code>HttpServletRequest</code> as its sole constructor can be used instead of this default.
  *
  * @author Ben Alex
@@ -37,7 +37,7 @@ import javax.servlet.http.HttpServletRequest;
 public class WebAuthenticationDetailsSource implements AuthenticationDetailsSource {
     //~ Instance fields ================================================================================================
 
-    private Class clazz = WebAuthenticationDetails.class;
+    private Class<?> clazz = WebAuthenticationDetails.class;
 
     //~ Methods ========================================================================================================
 
@@ -47,7 +47,7 @@ public class WebAuthenticationDetailsSource implements AuthenticationDetailsSour
     public Object buildDetails(Object context) {
         Assert.isInstanceOf(HttpServletRequest.class, context);
         try {
-            Constructor constructor = clazz.getConstructor(new Class[] {HttpServletRequest.class});
+            Constructor<?> constructor = clazz.getConstructor(new Class[] {HttpServletRequest.class});
 
             return constructor.newInstance(new Object[] {context});
         } catch (NoSuchMethodException ex) {
@@ -63,7 +63,7 @@ public class WebAuthenticationDetailsSource implements AuthenticationDetailsSour
         return null;
     }
 
-    public void setClazz(Class clazz) {
+    public void setClazz(Class<?> clazz) {
         Assert.notNull(clazz, "Class required");
         this.clazz = clazz;
     }

+ 3 - 3
core/src/main/java/org/springframework/security/ui/preauth/j2ee/AbstractPreAuthenticatedAuthenticationDetailsSource.java

@@ -1,8 +1,8 @@
 package org.springframework.security.ui.preauth.j2ee;
 
-import java.util.Arrays;
 import java.util.Collection;
 import java.util.List;
+import java.util.Set;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
@@ -26,7 +26,7 @@ import org.springframework.util.Assert;
  */
 public abstract class AbstractPreAuthenticatedAuthenticationDetailsSource extends AuthenticationDetailsSourceImpl {
     protected final Log logger = LogFactory.getLog(getClass());
-    protected String[] j2eeMappableRoles;
+    protected Set<String> j2eeMappableRoles;
     protected Attributes2GrantedAuthoritiesMapper j2eeUserRoles2GrantedAuthoritiesMapper =
         new SimpleAttributes2GrantedAuthoritiesMapper();
 
@@ -72,7 +72,7 @@ public abstract class AbstractPreAuthenticatedAuthenticationDetailsSource extend
      * @param mappableRoles the possible roles as determined by the MappableAttributesRetriever
      * @return the subset of mappable roles which the current user has.
      */
-    protected abstract Collection<String> getUserRoles(Object context, String[] mappableRoles);
+    protected abstract Collection<String> getUserRoles(Object context, Set<String> mappableRoles);
 
     /**
      * @param aJ2eeMappableRolesRetriever

+ 5 - 4
core/src/main/java/org/springframework/security/ui/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.java

@@ -5,6 +5,7 @@ import org.springframework.security.authoritymapping.SimpleAttributes2GrantedAut
 
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Set;
 
 import javax.servlet.http.HttpServletRequest;
 
@@ -36,12 +37,12 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource extends Abs
      *                returned by the MappableAttributesRetriever.
      * @return GrantedAuthority[] mapped from the user's J2EE roles.
      */
-    protected Collection<String> getUserRoles(Object context, String[] mappableRoles) {
+    protected Collection<String> getUserRoles(Object context, Set<String> mappableRoles) {
         ArrayList<String> j2eeUserRolesList = new ArrayList<String>();
 
-        for (int i = 0; i < mappableRoles.length; i++) {
-            if (((HttpServletRequest)context).isUserInRole(mappableRoles[i])) {
-                j2eeUserRolesList.add(mappableRoles[i]);
+        for (String role : mappableRoles) {
+            if (((HttpServletRequest)context).isUserInRole(role)) {
+                j2eeUserRolesList.add(role);
             }
         }
 

+ 1 - 1
core/src/main/java/org/springframework/security/ui/switchuser/SwitchUserAuthorityChanger.java

@@ -28,5 +28,5 @@ public interface SwitchUserAuthorityChanger {
      *
      * @return the modified list of granted authorities.
      */
-    List modifyGrantedAuthorities(UserDetails targetUser, Authentication currentAuthentication, List authoritiesToBeGranted);
+    List<GrantedAuthority> modifyGrantedAuthorities(UserDetails targetUser, Authentication currentAuthentication, List<GrantedAuthority> authoritiesToBeGranted);
 }

+ 8 - 11
core/src/main/java/org/springframework/security/userdetails/memory/UserAttribute.java

@@ -33,14 +33,13 @@ import java.util.Vector;
 public class UserAttribute {
     //~ Instance fields ================================================================================================
 
-    private List authorities = new Vector();
+    private List<GrantedAuthority> authorities = new Vector<GrantedAuthority>();
     private String password;
     private boolean enabled = true;
 
     //~ Constructors ===================================================================================================
 
     public UserAttribute() {
-        super();
     }
 
     //~ Methods ========================================================================================================
@@ -52,7 +51,7 @@ public class UserAttribute {
     public GrantedAuthority[] getAuthorities() {
         GrantedAuthority[] toReturn = {new GrantedAuthorityImpl("demo")};
 
-        return (GrantedAuthority[]) this.authorities.toArray(toReturn);
+        return this.authorities.toArray(toReturn);
     }
 
     /**
@@ -61,7 +60,7 @@ public class UserAttribute {
      * @param authorities {@link List} &lt;{@link GrantedAuthority}>
      * @since 1.1
      */
-    public void setAuthorities(List authorities) {
+    public void setAuthorities(List<GrantedAuthority> authorities) {
         this.authorities = authorities;
     }
 
@@ -69,15 +68,13 @@ public class UserAttribute {
      * Set all authorities for this user from String values.
      * It will create the necessary {@link GrantedAuthority} objects.
      *
-     * @param authoritiesAsString {@link List} &lt;{@link String}>
+     * @param authoritiesAsStrings {@link List} &lt;{@link String}>
      * @since 1.1
      */
-    public void setAuthoritiesAsString(List authoritiesAsString) {
-        setAuthorities(new ArrayList(authoritiesAsString.size()));
-        Iterator it = authoritiesAsString.iterator();
-        while (it.hasNext()) {
-            GrantedAuthority grantedAuthority = new GrantedAuthorityImpl((String) it.next());
-            addAuthority(grantedAuthority);
+    public void setAuthoritiesAsString(List<String> authoritiesAsStrings) {
+        setAuthorities(new ArrayList<GrantedAuthority>(authoritiesAsStrings.size()));
+        for(String authority : authoritiesAsStrings) {
+            addAuthority(new GrantedAuthorityImpl(authority));
         }
     }
 

+ 3 - 3
core/src/main/java/org/springframework/security/userdetails/memory/UserAttributeEditor.java

@@ -35,7 +35,7 @@ public class UserAttributeEditor extends PropertyEditorSupport {
             String[] tokens = StringUtils.commaDelimitedListToStringArray(s);
             UserAttribute userAttrib = new UserAttribute();
 
-            List authoritiesAsString = new ArrayList();
+            List<String> authoritiesAsStrings = new ArrayList<String>();
 
             for (int i = 0; i < tokens.length; i++) {
                 String currentToken = tokens[i].trim();
@@ -48,11 +48,11 @@ public class UserAttributeEditor extends PropertyEditorSupport {
                     } else if (currentToken.toLowerCase().equals("disabled")) {
                         userAttrib.setEnabled(false);
                     } else {
-                        authoritiesAsString.add(currentToken);
+                        authoritiesAsStrings.add(currentToken);
                     }
                 }
             }
-            userAttrib.setAuthoritiesAsString(authoritiesAsString);
+            userAttrib.setAuthoritiesAsString(authoritiesAsStrings);
 
             if (userAttrib.isValid()) {
                 setValue(userAttrib);

+ 24 - 35
core/src/main/java/org/springframework/security/util/MethodInvocationUtils.java

@@ -27,7 +27,8 @@ import org.springframework.util.Assert;
 
 /**
  * Static utility methods for creating <code>MethodInvocation</code>s usable within Spring Security.
- * <p>All methods of this class return a {@link org.springframework.security.util.SimpleMethodInvocation}.</p>
+ * <p>
+ * All methods of this class return a {@link org.springframework.security.util.SimpleMethodInvocation}.
  *
  * @author Ben Alex
  * @version $Id$
@@ -40,58 +41,46 @@ public final class MethodInvocationUtils {
 
     //~ Methods ========================================================================================================
 
-    /**
-     * Generates a <code>MethodInvocation</code> for specified <code>methodName</code> on the passed object.
-     *
-     * @param object the object that will be used to find the relevant <code>Method</code>
-     * @param methodName the name of the method to find
-     *
-     * @return a <code>MethodInvocation</code>, or <code>null</code> if there was a problem
-     */
-    public static MethodInvocation create(Object object, String methodName) {
-        return create(object, methodName, null);
-    }
-
     /**
      * Generates a <code>MethodInvocation</code> for specified <code>methodName</code> on the passed object,
      * using the <code>args</code> to locate the method.
      *
      * @param object the object that will be used to find the relevant <code>Method</code>
      * @param methodName the name of the method to find
-     * @param args arguments that are required as part of the method signature
+     * @param args arguments that are required as part of the method signature (can be empty)
      *
      * @return a <code>MethodInvocation</code>, or <code>null</code> if there was a problem
      */
-    public static MethodInvocation create(Object object, String methodName, Object[] args) {
+    public static MethodInvocation create(Object object, String methodName, Object... args) {
         Assert.notNull(object, "Object required");
 
-        Class[] classArgs = null;
+        Class<?>[] classArgs = null;
 
         if (args != null) {
-            List list = new ArrayList();
+            List<Class<?>> list = new ArrayList<Class<?>>();
 
             for (int i = 0; i < args.length; i++) {
                 list.add(args[i].getClass());
             }
 
-            classArgs = (Class[]) list.toArray(new Class[] {});
+            classArgs = list.toArray(new Class[] {});
         }
-        
+
         // Determine the type that declares the requested method, taking into account proxies
-        Class target = AopUtils.getTargetClass(object);
+        Class<?> target = AopUtils.getTargetClass(object);
         if (object instanceof Advised) {
-        	Advised a = (Advised) object;
-        	if (!a.isProxyTargetClass()) {
-        		Class[] possibleInterfaces = a.getProxiedInterfaces();
-        		for (int i = 0; i < possibleInterfaces.length; i++) {
-        			try {
-            			possibleInterfaces[i].getMethod(methodName, classArgs);
-            			// to get here means no exception happened
-            			target = possibleInterfaces[i];
-            			break;
-        			} catch (Exception tryTheNextOne) {}
-        		}
-        	}
+            Advised a = (Advised) object;
+            if (!a.isProxyTargetClass()) {
+                Class<?>[] possibleInterfaces = a.getProxiedInterfaces();
+                for (int i = 0; i < possibleInterfaces.length; i++) {
+                    try {
+                        possibleInterfaces[i].getMethod(methodName, classArgs);
+                        // to get here means no exception happened
+                        target = possibleInterfaces[i];
+                        break;
+                    } catch (Exception tryTheNextOne) {}
+                }
+            }
         }
 
         return createFromClass(object, target, methodName, classArgs, args);
@@ -105,7 +94,7 @@ public final class MethodInvocationUtils {
      *
      * @return a <code>MethodInvocation</code>, or <code>null</code> if there was a problem
      */
-    public static MethodInvocation createFromClass(Class clazz, String methodName) {
+    public static MethodInvocation createFromClass(Class<?> clazz, String methodName) {
         return createFromClass(null, clazz, methodName, null, null);
     }
 
@@ -120,8 +109,8 @@ public final class MethodInvocationUtils {
      * @param args the actual arguments that should be passed to SimpleMethodInvocation
      * @return a <code>MethodInvocation</code>, or <code>null</code> if there was a problem
      */
-    public static MethodInvocation createFromClass(Object targetObject, Class clazz, String methodName, Class[] classArgs, Object[] args) {
-    	Assert.notNull(clazz, "Class required");
+    public static MethodInvocation createFromClass(Object targetObject, Class<?> clazz, String methodName, Class<?>[] classArgs, Object[] args) {
+        Assert.notNull(clazz, "Class required");
         Assert.hasText(methodName, "MethodName required");
 
         Method method;

+ 1 - 1
core/src/main/java/org/springframework/security/vote/AbstractAccessDecisionManager.java

@@ -113,7 +113,7 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan
      * @param clazz the type of secured object being presented
      * @return true if this type is supported
      */
-    public boolean supports(Class clazz) {
+    public boolean supports(Class<?> clazz) {
         Iterator<AccessDecisionVoter> iter = this.decisionVoters.iterator();
 
         while (iter.hasNext()) {

+ 1 - 1
core/src/test/java/org/springframework/security/MockAccessDecisionManager.java

@@ -52,7 +52,7 @@ public class MockAccessDecisionManager implements AccessDecisionManager {
         }
     }
 
-    public boolean supports(Class clazz) {
+    public boolean supports(Class<?> clazz) {
         return true;
     }
 }

+ 1 - 1
core/src/test/java/org/springframework/security/MockAfterInvocationManager.java

@@ -53,7 +53,7 @@ public class MockAfterInvocationManager implements AfterInvocationManager {
         }
     }
 
-    public boolean supports(Class clazz) {
+    public boolean supports(Class<?> clazz) {
         return true;
     }
 }

+ 1 - 1
core/src/test/java/org/springframework/security/afterinvocation/AfterInvocationProviderManagerTests.java

@@ -159,7 +159,7 @@ public class AfterInvocationProviderManagerTests extends TestCase {
             return returnedObject;
         }
 
-        public boolean supports(Class<? extends Object> clazz) {
+        public boolean supports(Class<?> clazz) {
             return secureObject.isAssignableFrom(clazz);
         }
 

+ 2 - 2
core/src/test/java/org/springframework/security/annotation/BusinessService.java

@@ -51,10 +51,10 @@ public interface BusinessService {
 
     public int someOther(int input);
 
-    public List<Object> methodReturningAList(List<Object> someList);
+    public List<?> methodReturningAList(List<?> someList);
 
     public Object[] methodReturningAnArray(Object[] someArray);
 
-    public List<Object> methodReturningAList(String userName, String extraParam);
+    public List<?> methodReturningAList(String userName, String extraParam);
 
 }

+ 1 - 1
core/src/test/java/org/springframework/security/annotation/BusinessServiceImpl.java

@@ -37,7 +37,7 @@ public class BusinessServiceImpl<E extends Entity> implements BusinessService {
         return input;
     }
 
-    public List<Object> methodReturningAList(List<Object> someList) {
+    public List<?> methodReturningAList(List<?> someList) {
         return someList;
     }
 

+ 1 - 1
core/src/test/java/org/springframework/security/annotation/ExpressionProtectedBusinessServiceImpl.java

@@ -30,7 +30,7 @@ public class ExpressionProtectedBusinessServiceImpl implements BusinessService {
 
     @PreFilter(filterTarget="someList", value="filterObject == authentication.name or filterObject == 'sam'")
     @PostFilter("filterObject == 'bob'")
-    public List<Object> methodReturningAList(List<Object> someList) {
+    public List<?> methodReturningAList(List<?> someList) {
         return someList;
     }
 

+ 3 - 3
core/src/test/java/org/springframework/security/annotation/Jsr250BusinessServiceImpl.java

@@ -38,12 +38,12 @@ public class Jsr250BusinessServiceImpl implements BusinessService {
         return input;
     }
 
-    public List<Object> methodReturningAList(List<Object> someList) {
+    public List<?> methodReturningAList(List<?> someList) {
         return someList;
     }
 
-    public List<Object> methodReturningAList(String userName, String arg2) {
-        return new ArrayList();
+    public List<?> methodReturningAList(String userName, String arg2) {
+        return new ArrayList<Object>();
     }
 
     public Object[] methodReturningAnArray(Object[] someArray) {

+ 10 - 10
core/src/test/java/org/springframework/security/authoritymapping/SimpleMappableRolesRetrieverTests.java

@@ -2,6 +2,7 @@ package org.springframework.security.authoritymapping;
 
 import java.util.Arrays;
 import java.util.Collection;
+import java.util.Set;
 
 import junit.framework.TestCase;
 
@@ -12,15 +13,14 @@ import junit.framework.TestCase;
  */
 public class SimpleMappableRolesRetrieverTests extends TestCase {
 
-	public final void testGetSetMappableRoles() {
-		String[] roles = new String[] { "Role1", "Role2" };
-		SimpleMappableAttributesRetriever r = new SimpleMappableAttributesRetriever();
-		r.setMappableAttributes(roles);
-		String[] result = r.getMappableAttributes();
-		Collection resultColl = Arrays.asList(result);
-		Collection rolesColl = Arrays.asList(roles);
-		assertTrue("Role collections do not match; result: " + resultColl + ", expected: " + rolesColl, rolesColl.containsAll(resultColl)
-				&& resultColl.containsAll(rolesColl));
-	}
+    public final void testGetSetMappableRoles() {
+        String[] roles = new String[] { "Role1", "Role2" };
+        SimpleMappableAttributesRetriever r = new SimpleMappableAttributesRetriever();
+        r.setMappableAttributes(roles);
+        Set<String> result = r.getMappableAttributes();
+        Collection<String> rolesColl = Arrays.asList(roles);
+        assertTrue("Role collections do not match; result: " + result + ", expected: " + rolesColl, rolesColl.containsAll(result)
+                && result.containsAll(rolesColl));
+    }
 
 }

+ 2 - 2
core/src/test/java/org/springframework/security/authoritymapping/SimpleRoles2GrantedAuthoritiesMapperTests.java

@@ -100,11 +100,11 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase {
 
     private void testGetGrantedAuthorities(SimpleAttributes2GrantedAuthoritiesMapper mapper, String[] roles, String[] expectedGas) {
         List<GrantedAuthority> result = mapper.getGrantedAuthorities(Arrays.asList(roles));
-        Collection resultColl = new ArrayList(result.size());
+        Collection<String> resultColl = new ArrayList<String>(result.size());
         for (int i = 0; i < result.size(); i++) {
             resultColl.add(result.get(i).getAuthority());
         }
-        Collection expectedColl = Arrays.asList(expectedGas);
+        Collection<String> expectedColl = Arrays.asList(expectedGas);
         assertTrue("Role collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl
                 .containsAll(resultColl)
                 && resultColl.containsAll(expectedColl));

+ 84 - 84
core/src/test/java/org/springframework/security/authoritymapping/XmlMappableRolesRetrieverTests.java

@@ -5,96 +5,96 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.util.Arrays;
 import java.util.Collection;
+import java.util.Set;
 
 import junit.framework.TestCase;
 
 /**
- * 
+ *
  * @author TSARDD
  * @since 18-okt-2007
  */
 public class XmlMappableRolesRetrieverTests extends TestCase {
-	private static final String DEFAULT_XML = "<roles><role>Role1</role><role>Role2</role></roles>";
-
-	private static final String DEFAULT_XPATH = "/roles/role/text()";
-
-	private static final String[] DEFAULT_EXPECTED_ROLES = new String[] { "Role1", "Role2" };
-
-	public final void testAfterPropertiesSetException() {
-		TestXmlMappableAttributesRetriever t = new TestXmlMappableAttributesRetriever();
-		try {
-			t.afterPropertiesSet();
-			fail("AfterPropertiesSet didn't throw expected exception");
-		} catch (IllegalArgumentException expected) {
-		} catch (Exception unexpected) {
-			fail("AfterPropertiesSet throws unexpected exception");
-		}
-	}
-
-	public void testGetMappableRoles() {
-		XmlMappableAttributesRetriever r = getXmlMappableRolesRetriever(true, getDefaultInputStream(), DEFAULT_XPATH);
-		String[] resultRoles = r.getMappableAttributes();
-		assertNotNull("Result roles should not be null", resultRoles);
-		assertTrue("Number of result roles doesn't match expected number of roles", resultRoles.length == DEFAULT_EXPECTED_ROLES.length);
-		Collection resultRolesColl = Arrays.asList(resultRoles);
-		Collection expectedRolesColl = Arrays.asList(DEFAULT_EXPECTED_ROLES);
-		assertTrue("Role collections do not match", expectedRolesColl.containsAll(resultRolesColl)
-				&& resultRolesColl.containsAll(expectedRolesColl));
-	}
-
-	public void testCloseInputStream() {
-		testCloseInputStream(true);
-	}
-
-	public void testDontCloseInputStream() {
-		testCloseInputStream(false);
-	}
-
-	private void testCloseInputStream(boolean closeAfterRead) {
-		CloseableByteArrayInputStream is = getDefaultInputStream();
-		XmlMappableAttributesRetriever r = getXmlMappableRolesRetriever(closeAfterRead, is, DEFAULT_XPATH);
-		r.getMappableAttributes();
-		assertEquals(is.isClosed(), closeAfterRead);
-	}
-
-	private XmlMappableAttributesRetriever getXmlMappableRolesRetriever(boolean closeInputStream, InputStream is, String xpath) {
-		XmlMappableAttributesRetriever result = new TestXmlMappableAttributesRetriever();
-		result.setCloseInputStream(closeInputStream);
-		result.setXmlInputStream(is);
-		result.setXpathExpression(xpath);
-		try {
-			result.afterPropertiesSet();
-		} catch (Exception e) {
-			fail("Unexpected exception" + e.toString());
-		}
-		return result;
-	}
-
-	private CloseableByteArrayInputStream getDefaultInputStream() {
-		return getInputStream(DEFAULT_XML);
-	}
-
-	private CloseableByteArrayInputStream getInputStream(String data) {
-		return new CloseableByteArrayInputStream(data.getBytes());
-	}
-
-	private static final class TestXmlMappableAttributesRetriever extends XmlMappableAttributesRetriever {
-	}
-
-	private static final class CloseableByteArrayInputStream extends ByteArrayInputStream {
-		private boolean closed = false;
-
-		public CloseableByteArrayInputStream(byte[] buf) {
-			super(buf);
-		}
-
-		public void close() throws IOException {
-			super.close();
-			closed = true;
-		}
-
-		public boolean isClosed() {
-			return closed;
-		}
-	}
+    private static final String DEFAULT_XML = "<roles><role>Role1</role><role>Role2</role></roles>";
+
+    private static final String DEFAULT_XPATH = "/roles/role/text()";
+
+    private static final String[] DEFAULT_EXPECTED_ROLES = new String[] { "Role1", "Role2" };
+
+    public final void testAfterPropertiesSetException() {
+        TestXmlMappableAttributesRetriever t = new TestXmlMappableAttributesRetriever();
+        try {
+            t.afterPropertiesSet();
+            fail("AfterPropertiesSet didn't throw expected exception");
+        } catch (IllegalArgumentException expected) {
+        } catch (Exception unexpected) {
+            fail("AfterPropertiesSet throws unexpected exception");
+        }
+    }
+
+    public void testGetMappableRoles() {
+        XmlMappableAttributesRetriever r = getXmlMappableRolesRetriever(true, getDefaultInputStream(), DEFAULT_XPATH);
+        Set<String> resultRoles = r.getMappableAttributes();
+        assertNotNull("Result roles should not be null", resultRoles);
+        assertEquals("Number of result roles doesn't match expected number of roles", DEFAULT_EXPECTED_ROLES.length, resultRoles.size());
+        Collection expectedRolesColl = Arrays.asList(DEFAULT_EXPECTED_ROLES);
+        assertTrue("Role collections do not match", expectedRolesColl.containsAll(resultRoles)
+                && resultRoles.containsAll(expectedRolesColl));
+    }
+
+    public void testCloseInputStream() {
+        testCloseInputStream(true);
+    }
+
+    public void testDontCloseInputStream() {
+        testCloseInputStream(false);
+    }
+
+    private void testCloseInputStream(boolean closeAfterRead) {
+        CloseableByteArrayInputStream is = getDefaultInputStream();
+        XmlMappableAttributesRetriever r = getXmlMappableRolesRetriever(closeAfterRead, is, DEFAULT_XPATH);
+        r.getMappableAttributes();
+        assertEquals(is.isClosed(), closeAfterRead);
+    }
+
+    private XmlMappableAttributesRetriever getXmlMappableRolesRetriever(boolean closeInputStream, InputStream is, String xpath) {
+        XmlMappableAttributesRetriever result = new TestXmlMappableAttributesRetriever();
+        result.setCloseInputStream(closeInputStream);
+        result.setXmlInputStream(is);
+        result.setXpathExpression(xpath);
+        try {
+            result.afterPropertiesSet();
+        } catch (Exception e) {
+            fail("Unexpected exception" + e.toString());
+        }
+        return result;
+    }
+
+    private CloseableByteArrayInputStream getDefaultInputStream() {
+        return getInputStream(DEFAULT_XML);
+    }
+
+    private CloseableByteArrayInputStream getInputStream(String data) {
+        return new CloseableByteArrayInputStream(data.getBytes());
+    }
+
+    private static final class TestXmlMappableAttributesRetriever extends XmlMappableAttributesRetriever {
+    }
+
+    private static final class CloseableByteArrayInputStream extends ByteArrayInputStream {
+        private boolean closed = false;
+
+        public CloseableByteArrayInputStream(byte[] buf) {
+            super(buf);
+        }
+
+        public void close() throws IOException {
+            super.close();
+            closed = true;
+        }
+
+        public boolean isClosed() {
+            return closed;
+        }
+    }
 }

+ 2 - 2
core/src/test/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParserTests.java

@@ -221,11 +221,11 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
                 AUTH_PROVIDER_XML);
         SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("bob","bobspassword"));
         target = (BusinessService) appContext.getBean("target");
-        List arg = new ArrayList();
+        List<String> arg = new ArrayList<String>();
         arg.add("joe");
         arg.add("bob");
         arg.add("sam");
-        List result = target.methodReturningAList(arg);
+        List<?> result = target.methodReturningAList(arg);
         // Expression is (filterObject == name or filterObject == 'sam'), so "joe" should be gone after pre-filter
         // PostFilter should remove sam from the return object
         assertEquals(1, result.size());

+ 1 - 1
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<? extends Object> clazz) {
+    public boolean supports(Class<?> clazz) {
         return true;
     }
 

+ 20 - 36
core/src/test/java/org/springframework/security/intercept/method/MethodInvocationPrivilegeEvaluatorTests.java

@@ -15,24 +15,19 @@
 
 package org.springframework.security.intercept.method;
 
-import junit.framework.TestCase;
+import static org.junit.Assert.*;
 
-import org.springframework.security.GrantedAuthority;
-import org.springframework.security.GrantedAuthorityImpl;
+import org.aopalliance.intercept.MethodInvocation;
+import org.junit.Test;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.support.ClassPathXmlApplicationContext;
 import org.springframework.security.ITargetObject;
 import org.springframework.security.OtherTargetObject;
-
 import org.springframework.security.intercept.method.aopalliance.MethodSecurityInterceptor;
-
 import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
-
+import org.springframework.security.util.AuthorityUtils;
 import org.springframework.security.util.MethodInvocationUtils;
 
-import org.aopalliance.intercept.MethodInvocation;
-
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.support.ClassPathXmlApplicationContext;
-
 
 /**
  * Tests {@link org.springframework.security.intercept.method.MethodInvocationPrivilegeEvaluator}.
@@ -40,16 +35,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
  * @author Ben Alex
  * @version $Id$
  */
-public class MethodInvocationPrivilegeEvaluatorTests extends TestCase {
-    //~ Constructors ===================================================================================================
-
-    public MethodInvocationPrivilegeEvaluatorTests() {
-        super();
-    }
-
-    public MethodInvocationPrivilegeEvaluatorTests(String arg0) {
-        super(arg0);
-    }
+public class MethodInvocationPrivilegeEvaluatorTests {
 
     //~ Methods ========================================================================================================
 
@@ -60,10 +46,6 @@ public class MethodInvocationPrivilegeEvaluatorTests extends TestCase {
         return context.getBean("target");
     }
 
-    public static void main(String[] args) {
-        junit.textui.TestRunner.run(MethodInvocationPrivilegeEvaluatorTests.class);
-    }
-
     private MethodSecurityInterceptor makeSecurityInterceptor() {
         ApplicationContext context = new ClassPathXmlApplicationContext(
                 "org/springframework/security/intercept/method/aopalliance/applicationContext.xml");
@@ -71,11 +53,12 @@ public class MethodInvocationPrivilegeEvaluatorTests extends TestCase {
         return (MethodSecurityInterceptor) context.getBean("securityInterceptor");
     }
 
-    public void testAllowsAccessUsingCreate() throws Exception {
+    @Test
+    public void allowsAccessUsingCreate() throws Exception {
         UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
-                new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_LOWER")});
+                AuthorityUtils.createAuthorityList("MOCK_LOWER"));
         Object object = lookupTargetObject();
-        MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", new Object[] {"foobar"});
+        MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", "foobar");
         MethodSecurityInterceptor interceptor = makeSecurityInterceptor();
 
         MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
@@ -85,10 +68,10 @@ public class MethodInvocationPrivilegeEvaluatorTests extends TestCase {
         assertTrue(mipe.isAllowed(mi, token));
     }
 
-    public void testAllowsAccessUsingCreateFromClass()
-        throws Exception {
+    @Test
+    public void allowsAccessUsingCreateFromClass() throws Exception {
         UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
-                new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_LOWER")});
+                AuthorityUtils.createAuthorityList("MOCK_LOWER"));
         MethodInvocation mi = MethodInvocationUtils.createFromClass(new OtherTargetObject(), ITargetObject.class, "makeLowerCase",
                 new Class[] {String.class}, new Object[] {"Hello world"});
         MethodSecurityInterceptor interceptor = makeSecurityInterceptor();
@@ -100,9 +83,10 @@ public class MethodInvocationPrivilegeEvaluatorTests extends TestCase {
         assertTrue(mipe.isAllowed(mi, token));
     }
 
-    public void testDeclinesAccessUsingCreate() throws Exception {
+    @Test
+    public void declinesAccessUsingCreate() throws Exception {
         UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
-                new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_NOT_HELD")});
+                AuthorityUtils.createAuthorityList("ROLE_NOT_HELD"));
         Object object = lookupTargetObject();
         MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", new Object[] {"foobar"});
         MethodSecurityInterceptor interceptor = makeSecurityInterceptor();
@@ -114,10 +98,10 @@ public class MethodInvocationPrivilegeEvaluatorTests extends TestCase {
         assertFalse(mipe.isAllowed(mi, token));
     }
 
-    public void testDeclinesAccessUsingCreateFromClass()
-        throws Exception {
+    @Test
+    public void declinesAccessUsingCreateFromClass() throws Exception {
         UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
-                new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_NOT_HELD")});
+                AuthorityUtils.createAuthorityList("ROLE_NOT_HELD"));
         MethodInvocation mi = MethodInvocationUtils.createFromClass(new OtherTargetObject(), ITargetObject.class, "makeLowerCase",
                 new Class[] {String.class}, new Object[] {"helloWorld"});
         MethodSecurityInterceptor interceptor = makeSecurityInterceptor();

+ 2 - 2
core/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorTests.java

@@ -407,7 +407,7 @@ public class MethodSecurityInterceptorTests extends TestCase {
             throw new UnsupportedOperationException("mock method not implemented");
         }
 
-        public boolean supports(Class clazz) {
+        public boolean supports(Class<?> clazz) {
             if (String.class.isAssignableFrom(clazz)) {
                 return true;
             } else {
@@ -426,7 +426,7 @@ public class MethodSecurityInterceptorTests extends TestCase {
             throw new UnsupportedOperationException("mock method not implemented");
         }
 
-        public boolean supports(Class clazz) {
+        public boolean supports(Class<?> clazz) {
             if (String.class.isAssignableFrom(clazz)) {
                 return true;
             } else {

+ 2 - 19
core/src/test/java/org/springframework/security/intercept/method/aspectj/AspectJSecurityInterceptorTests.java

@@ -42,26 +42,9 @@ import org.springframework.security.util.AuthorityUtils;
  * @version $Id$
  */
 public class AspectJSecurityInterceptorTests extends TestCase {
-    //~ Constructors ===================================================================================================
-
-    public AspectJSecurityInterceptorTests() {
-    }
-
-    public AspectJSecurityInterceptorTests(String arg0) {
-        super(arg0);
-    }
 
     //~ Methods ========================================================================================================
 
-    public final void setUp() throws Exception {
-        super.setUp();
-    }
-
-    protected void tearDown() throws Exception {
-        super.tearDown();
-        SecurityContextHolder.clearContext();
-    }
-
     public void testCallbackIsInvokedWhenPermissionGranted() throws Exception {
         AspectJSecurityInterceptor si = new AspectJSecurityInterceptor();
         si.setApplicationEventPublisher(new MockApplicationEventPublisher(true));
@@ -78,7 +61,7 @@ public class AspectJSecurityInterceptorTests extends TestCase {
 
         si.afterPropertiesSet();
 
-        Class clazz = TargetObject.class;
+        Class<TargetObject> clazz = TargetObject.class;
         Method method = clazz.getMethod("countLength", new Class[] {String.class});
         MockJoinPoint joinPoint = new MockJoinPoint(new TargetObject(), method);
 
@@ -108,7 +91,7 @@ public class AspectJSecurityInterceptorTests extends TestCase {
 
         si.afterPropertiesSet();
 
-        Class clazz = TargetObject.class;
+        Class<TargetObject> clazz = TargetObject.class;
         Method method = clazz.getMethod("countLength", new Class[] {String.class});
         MockJoinPoint joinPoint = new MockJoinPoint(new TargetObject(), method);
 

+ 14 - 34
core/src/test/java/org/springframework/security/providers/UsernamePasswordAuthenticationTokenTests.java

@@ -15,10 +15,11 @@
 
 package org.springframework.security.providers;
 
-import junit.framework.TestCase;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 
-import org.springframework.security.GrantedAuthority;
-import org.springframework.security.GrantedAuthorityImpl;
+import org.junit.Test;
 import org.springframework.security.util.AuthorityUtils;
 
 
@@ -28,28 +29,12 @@ import org.springframework.security.util.AuthorityUtils;
  * @author Ben Alex
  * @version $Id$
  */
-public class UsernamePasswordAuthenticationTokenTests extends TestCase {
-    //~ Constructors ===================================================================================================
-
-    public UsernamePasswordAuthenticationTokenTests() {
-        super();
-    }
-
-    public UsernamePasswordAuthenticationTokenTests(String arg0) {
-        super(arg0);
-    }
+public class UsernamePasswordAuthenticationTokenTests {
 
     //~ Methods ========================================================================================================
 
-    public static void main(String[] args) {
-        junit.textui.TestRunner.run(UsernamePasswordAuthenticationTokenTests.class);
-    }
-
-    public final void setUp() throws Exception {
-        super.setUp();
-    }
-
-    public void testAuthenticated() {
+    @Test
+    public void authenticatedPropertyContractIsSatisfied() {
         UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", AuthorityUtils.NO_AUTHORITIES);
 
         // check default given we passed some GrantedAuthorty[]s (well, we passed empty list)
@@ -73,27 +58,22 @@ public class UsernamePasswordAuthenticationTokenTests extends TestCase {
             token.setAuthenticated(true);
             fail("Should have prohibited setAuthenticated(true)");
         } catch (IllegalArgumentException expected) {
-            assertTrue(true);
         }
     }
 
-    public void testGetters() {
+    @Test
+    public void gettersReturnCorrectData() {
         UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
-                new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
+                AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
         assertEquals("Test", token.getPrincipal());
         assertEquals("Password", token.getCredentials());
         assertEquals("ROLE_ONE", token.getAuthorities().get(0).getAuthority());
         assertEquals("ROLE_TWO", token.getAuthorities().get(1).getAuthority());
     }
 
-    public void testNoArgConstructorDoesntExist() {
-        Class clazz = UsernamePasswordAuthenticationToken.class;
-
-        try {
-            clazz.getDeclaredConstructor((Class[]) null);
-            fail("Should have thrown NoSuchMethodException");
-        } catch (NoSuchMethodException expected) {
-            assertTrue(true);
-        }
+    @Test(expected=NoSuchMethodException.class)
+    public void testNoArgConstructorDoesntExist() throws Exception {
+        Class<?> clazz = UsernamePasswordAuthenticationToken.class;
+        clazz.getDeclaredConstructor((Class[]) null);
     }
 }

+ 18 - 40
core/src/test/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationTokenTests.java

@@ -15,6 +15,8 @@
 
 package org.springframework.security.providers.anonymous;
 
+import java.util.List;
+
 import junit.framework.TestCase;
 
 import org.springframework.security.GrantedAuthority;
@@ -30,60 +32,46 @@ import org.springframework.security.util.AuthorityUtils;
  * @version $Id$
  */
 public class AnonymousAuthenticationTokenTests extends TestCase {
+
+    private final static List<GrantedAuthority> ROLES_12 = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO");
+
     //~ Methods ========================================================================================================
 
     public void testConstructorRejectsNulls() {
         try {
-            new AnonymousAuthenticationToken(null, "Test",
-                new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
+            new AnonymousAuthenticationToken(null, "Test", ROLES_12);
             fail("Should have thrown IllegalArgumentException");
         } catch (IllegalArgumentException expected) {
-            assertTrue(true);
         }
 
         try {
-            new AnonymousAuthenticationToken("key", null,
-                new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
+            new AnonymousAuthenticationToken("key", null, ROLES_12);
             fail("Should have thrown IllegalArgumentException");
         } catch (IllegalArgumentException expected) {
-            assertTrue(true);
         }
 
-//        try {
-//            new AnonymousAuthenticationToken("key", "Test", null);
-//            fail("Should have thrown IllegalArgumentException");
-//        } catch (IllegalArgumentException expected) {
-//            assertTrue(true);
-//        }
-
         try {
             new AnonymousAuthenticationToken("key", "Test", new GrantedAuthority[] {null});
             fail("Should have thrown IllegalArgumentException");
         } catch (IllegalArgumentException expected) {
-            assertTrue(true);
         }
 
         try {
             new AnonymousAuthenticationToken("key", "Test", AuthorityUtils.NO_AUTHORITIES );
             fail("Should have thrown IllegalArgumentException");
         } catch (IllegalArgumentException expected) {
-            assertTrue(true);
         }
     }
 
     public void testEqualsWhenEqual() {
-        AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test",
-                new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
-
-        AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("key", "Test",
-                new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
+        AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
+        AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
 
         assertEquals(token1, token2);
     }
 
     public void testGetters() {
-        AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key", "Test",
-                new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
+        AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
 
         assertEquals("key".hashCode(), token.getKeyHash());
         assertEquals("Test", token.getPrincipal());
@@ -94,49 +82,39 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
     }
 
     public void testNoArgConstructorDoesntExist() {
-        Class clazz = AnonymousAuthenticationToken.class;
+        Class<?> clazz = AnonymousAuthenticationToken.class;
 
         try {
             clazz.getDeclaredConstructor((Class[]) null);
             fail("Should have thrown NoSuchMethodException");
         } catch (NoSuchMethodException expected) {
-            assertTrue(true);
         }
     }
 
     public void testNotEqualsDueToAbstractParentEqualsCheck() {
-        AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test",
-                new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
-
-        AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("key", "DIFFERENT_PRINCIPAL",
-                new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
+        AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
+        AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("key", "DIFFERENT_PRINCIPAL", ROLES_12);
 
         assertFalse(token1.equals(token2));
     }
 
     public void testNotEqualsDueToDifferentAuthenticationClass() {
-        AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test",
-                new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
-
-        UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password",
-                new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
+        AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
+        UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password", ROLES_12);
 
         assertFalse(token1.equals(token2));
     }
 
     public void testNotEqualsDueToKey() {
-        AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test",
-                new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
+        AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
 
-        AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("DIFFERENT_KEY", "Test",
-                new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
+        AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("DIFFERENT_KEY", "Test", ROLES_12);
 
         assertFalse(token1.equals(token2));
     }
 
     public void testSetAuthenticatedIgnored() {
-        AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key", "Test",
-                new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
+        AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
         assertTrue(token.isAuthenticated());
         token.setAuthenticated(false);
         assertTrue(!token.isAuthenticated());

+ 22 - 22
core/src/test/java/org/springframework/security/ui/preauth/j2ee/WebXmlJ2eeDefinedRolesRetrieverTests.java

@@ -3,32 +3,32 @@ package org.springframework.security.ui.preauth.j2ee;
 import java.io.InputStream;
 import java.util.Arrays;
 import java.util.List;
+import java.util.Set;
 
 import junit.framework.TestCase;
 
 public class WebXmlJ2eeDefinedRolesRetrieverTests extends TestCase {
 
-	public final void testRole1To4Roles() throws Exception {
-		final List ROLE1TO4_EXPECTED_ROLES = Arrays.asList(new String[] { "Role1", "Role2", "Role3", "Role4" });
-		InputStream role1to4InputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("webxml/Role1-4.web.xml");
-		WebXmlMappableAttributesRetriever rolesRetriever = new WebXmlMappableAttributesRetriever();
-		rolesRetriever.setWebXmlInputStream(role1to4InputStream);
-		rolesRetriever.afterPropertiesSet();
-		String[] j2eeRoles = rolesRetriever.getMappableAttributes();
-		assertNotNull(j2eeRoles);
-		List j2eeRolesList = Arrays.asList(j2eeRoles);
-		assertTrue("J2eeRoles expected size: " + ROLE1TO4_EXPECTED_ROLES.size() + ", actual size: " + j2eeRolesList.size(), j2eeRolesList
-				.size() == ROLE1TO4_EXPECTED_ROLES.size());
-		assertTrue("J2eeRoles expected contents (arbitrary order): " + ROLE1TO4_EXPECTED_ROLES + ", actual content: " + j2eeRolesList,
-				j2eeRolesList.containsAll(ROLE1TO4_EXPECTED_ROLES));
-	}
+    public final void testRole1To4Roles() throws Exception {
+        final List<String> ROLE1TO4_EXPECTED_ROLES = Arrays.asList(new String[] { "Role1", "Role2", "Role3", "Role4" });
+        InputStream role1to4InputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("webxml/Role1-4.web.xml");
+        WebXmlMappableAttributesRetriever rolesRetriever = new WebXmlMappableAttributesRetriever();
+        rolesRetriever.setWebXmlInputStream(role1to4InputStream);
+        rolesRetriever.afterPropertiesSet();
+        Set<String> j2eeRoles = rolesRetriever.getMappableAttributes();
+        assertNotNull(j2eeRoles);
+        assertTrue("J2eeRoles expected size: " + ROLE1TO4_EXPECTED_ROLES.size() + ", actual size: " + j2eeRoles.size(),
+                j2eeRoles.size() == ROLE1TO4_EXPECTED_ROLES.size());
+        assertTrue("J2eeRoles expected contents (arbitrary order): " + ROLE1TO4_EXPECTED_ROLES + ", actual content: " + j2eeRoles,
+                j2eeRoles.containsAll(ROLE1TO4_EXPECTED_ROLES));
+    }
 
-	public final void testGetZeroJ2eeRoles() throws Exception {
-		InputStream noRolesInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("webxml/NoRoles.web.xml");
-		WebXmlMappableAttributesRetriever rolesRetriever = new WebXmlMappableAttributesRetriever();
-		rolesRetriever.setWebXmlInputStream(noRolesInputStream);
-		rolesRetriever.afterPropertiesSet();
-		String[] j2eeRoles = rolesRetriever.getMappableAttributes();
-		assertTrue("J2eeRoles expected size: 0, actual size: " + j2eeRoles.length, j2eeRoles.length == 0);
-	}
+    public final void testGetZeroJ2eeRoles() throws Exception {
+        InputStream noRolesInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("webxml/NoRoles.web.xml");
+        WebXmlMappableAttributesRetriever rolesRetriever = new WebXmlMappableAttributesRetriever();
+        rolesRetriever.setWebXmlInputStream(noRolesInputStream);
+        rolesRetriever.afterPropertiesSet();
+        Set<String> j2eeRoles = rolesRetriever.getMappableAttributes();
+        assertEquals("J2eeRoles expected size: 0, actual size: " + j2eeRoles.size(), 0, j2eeRoles.size());
+    }
 }

+ 14 - 18
core/src/test/java/org/springframework/security/ui/switchuser/SwitchUserProcessingFilterTests.java

@@ -40,6 +40,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.security.util.FieldUtils;
 import org.springframework.security.util.MockFilterChain;
 
@@ -52,6 +53,7 @@ import org.springframework.security.util.MockFilterChain;
  * @version $Id$
  */
 public class SwitchUserProcessingFilterTests {
+    private final static List<GrantedAuthority> ROLES_12 = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO");
 
     @Before
     public void authenticateCurrentUser() {
@@ -199,16 +201,14 @@ public class SwitchUserProcessingFilterTests {
     @Test
     public void exitUserJackLordToDanoSucceeds() throws Exception {
         // original user
-        GrantedAuthority[] auths = {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")};
-        UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken("dano", "hawaii50", auths);
+        UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken("dano", "hawaii50", ROLES_12);
 
         // set current user (Admin)
-        GrantedAuthority[] adminAuths = {
-                new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO"),
-                new SwitchUserGrantedAuthority("PREVIOUS_ADMINISTRATOR", source)
-            };
-        UsernamePasswordAuthenticationToken admin = new UsernamePasswordAuthenticationToken("jacklord", "hawaii50",
-                adminAuths);
+        List<GrantedAuthority> adminAuths = new ArrayList<GrantedAuthority>();
+        adminAuths.addAll(ROLES_12);
+        adminAuths.add(new SwitchUserGrantedAuthority("PREVIOUS_ADMINISTRATOR", source));
+        UsernamePasswordAuthenticationToken admin =
+            new UsernamePasswordAuthenticationToken("jacklord", "hawaii50", adminAuths);
 
         SecurityContextHolder.getContext().setAuthentication(admin);
 
@@ -333,8 +333,8 @@ public class SwitchUserProcessingFilterTests {
         SwitchUserProcessingFilter filter = new SwitchUserProcessingFilter();
         filter.setUserDetailsService(new MockUserDetailsService());
         filter.setSwitchUserAuthorityChanger(new SwitchUserAuthorityChanger() {
-            public List modifyGrantedAuthorities(UserDetails targetUser, Authentication currentAuthentication, List authoritiesToBeGranted) {
-                List auths = new ArrayList();
+            public List<GrantedAuthority> modifyGrantedAuthorities(UserDetails targetUser, Authentication currentAuthentication, List<GrantedAuthority> authoritiesToBeGranted) {
+                List <GrantedAuthority>auths = new ArrayList<GrantedAuthority>();
                 auths.add(new GrantedAuthorityImpl("ROLE_NEW"));
                 return auths;
             }
@@ -358,17 +358,13 @@ public class SwitchUserProcessingFilterTests {
             // wofat (account expired)
             // steve (credentials expired)
             if ("jacklord".equals(username) || "dano".equals(username)) {
-                return new User(username, password, true, true, true, true,
-                    new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
+                return new User(username, password, true, true, true, true, ROLES_12);
             } else if ("mcgarrett".equals(username)) {
-                return new User(username, password, false, true, true, true,
-                    new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
+                return new User(username, password, false, true, true, true, ROLES_12);
             } else if ("wofat".equals(username)) {
-                return new User(username, password, true, false, true, true,
-                    new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
+                return new User(username, password, true, false, true, true, ROLES_12);
             } else if ("steve".equals(username)) {
-                return new User(username, password, true, true, false, true,
-                    new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
+                return new User(username, password, true, true, false, true, ROLES_12);
             } else {
                 throw new UsernameNotFoundException("Could not find: " + username);
             }

+ 6 - 5
portlet/src/main/java/org/springframework/security/ui/portlet/PortletPreAuthenticatedAuthenticationDetailsSource.java

@@ -2,6 +2,7 @@ package org.springframework.security.ui.portlet;
 
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Set;
 
 import javax.portlet.PortletRequest;
 
@@ -13,12 +14,12 @@ public class PortletPreAuthenticatedAuthenticationDetailsSource extends Abstract
          setClazz(PortletPreAuthenticatedAuthenticationDetails.class);
     }
 
-    protected Collection<String> getUserRoles(Object context, String[] mappableRoles) {
-        ArrayList portletRoles = new ArrayList();
+    protected Collection<String> getUserRoles(Object context, Set<String> mappableRoles) {
+        ArrayList<String> portletRoles = new ArrayList<String>();
 
-        for (int i = 0; i < mappableRoles.length; i++) {
-            if (((PortletRequest)context).isUserInRole(mappableRoles[i])) {
-                portletRoles.add(mappableRoles[i]);
+        for (String role : mappableRoles) {
+            if (((PortletRequest)context).isUserInRole(role)) {
+                portletRoles.add(role);
             }
         }
         portletRoles.trimToSize();