diff --git a/acl/src/main/java/org/springframework/security/acls/domain/BasePermission.java b/acl/src/main/java/org/springframework/security/acls/domain/BasePermission.java index 5f83cc9000..575b9f32c9 100644 --- a/acl/src/main/java/org/springframework/security/acls/domain/BasePermission.java +++ b/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. - * + * *

* You may subclass this class to add additional permissions, or use this class as a guide * for creating your own permission classes. *

- * + * * @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); } -} \ No newline at end of file +} diff --git a/acl/src/main/java/org/springframework/security/afterinvocation/AbstractAclProvider.java b/acl/src/main/java/org/springframework/security/afterinvocation/AbstractAclProvider.java index e487d0d14b..1a05997406 100644 --- a/acl/src/main/java/org/springframework/security/afterinvocation/AbstractAclProvider.java +++ b/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 true */ - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { return true; } } diff --git a/acl/src/main/java/org/springframework/security/vote/AclEntryVoter.java b/acl/src/main/java/org/springframework/security/vote/AclEntryVoter.java index 751b1e3e41..512c448908 100644 --- a/acl/src/main/java/org/springframework/security/vote/AclEntryVoter.java +++ b/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) { diff --git a/core/src/main/java/org/springframework/security/AccessDecisionManager.java b/core/src/main/java/org/springframework/security/AccessDecisionManager.java index 9d4e63a258..058179cd48 100644 --- a/core/src/main/java/org/springframework/security/AccessDecisionManager.java +++ b/core/src/main/java/org/springframework/security/AccessDecisionManager.java @@ -63,5 +63,5 @@ public interface AccessDecisionManager { * * @return true if the implementation can process the indicated class */ - boolean supports(Class clazz); + boolean supports(Class clazz); } diff --git a/core/src/main/java/org/springframework/security/AfterInvocationManager.java b/core/src/main/java/org/springframework/security/AfterInvocationManager.java index a18b37691f..6853642242 100644 --- a/core/src/main/java/org/springframework/security/AfterInvocationManager.java +++ b/core/src/main/java/org/springframework/security/AfterInvocationManager.java @@ -87,5 +87,5 @@ public interface AfterInvocationManager { * * @return true if the implementation can process the indicated class */ - boolean supports(Class clazz); + boolean supports(Class clazz); } diff --git a/core/src/main/java/org/springframework/security/afterinvocation/AfterInvocationProvider.java b/core/src/main/java/org/springframework/security/afterinvocation/AfterInvocationProvider.java index 38d93db50b..2e16df4603 100644 --- a/core/src/main/java/org/springframework/security/afterinvocation/AfterInvocationProvider.java +++ b/core/src/main/java/org/springframework/security/afterinvocation/AfterInvocationProvider.java @@ -56,5 +56,5 @@ public interface AfterInvocationProvider { * * @return true if the implementation can process the indicated class */ - boolean supports(Class clazz); + boolean supports(Class clazz); } diff --git a/core/src/main/java/org/springframework/security/afterinvocation/AfterInvocationProviderManager.java b/core/src/main/java/org/springframework/security/afterinvocation/AfterInvocationProviderManager.java index 9e059dea30..64c2c2c69e 100644 --- a/core/src/main/java/org/springframework/security/afterinvocation/AfterInvocationProviderManager.java +++ b/core/src/main/java/org/springframework/security/afterinvocation/AfterInvocationProviderManager.java @@ -122,7 +122,7 @@ public class AfterInvocationProviderManager implements AfterInvocationManager, I * @return if the AfterInvocationProviderManager can support the secure object class, which requires * every one of its AfterInvocationProviders to support the secure object class */ - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { Iterator iter = this.providers.iterator(); while (iter.hasNext()) { diff --git a/core/src/main/java/org/springframework/security/authoritymapping/MapBasedAttributes2GrantedAuthoritiesMapper.java b/core/src/main/java/org/springframework/security/authoritymapping/MapBasedAttributes2GrantedAuthoritiesMapper.java index 5dfb510162..bc12a90869 100755 --- a/core/src/main/java/org/springframework/security/authoritymapping/MapBasedAttributes2GrantedAuthoritiesMapper.java +++ b/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> attributes2grantedAuthoritiesMap = null; private String stringSeparator = ","; - private String[] mappableAttributes = null; + private Set 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> getAttributes2grantedAuthoritiesMap() { return attributes2grantedAuthoritiesMap; } /** * @param attributes2grantedAuthoritiesMap The attributes2grantedAuthoritiesMap to set. */ - public void setAttributes2grantedAuthoritiesMap(final Map 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> preProcessMap(Map orgMap) { - Map result = new HashMap(orgMap.size()); + private Map> preProcessMap(Map orgMap) { + Map> result = + new HashMap>(orgMap.size()); - for(Map.Entry entry : orgMap.entrySet()) { - result.put(entry.getKey(),getGrantedAuthorityCollection(entry.getValue())); + 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 getGrantedAuthorityCollection(Object value) { + Collection result = new ArrayList(); 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 result, Collection value) { - Iterator it = value.iterator(); - while ( it.hasNext() ) { - addGrantedAuthorityCollection(result,it.next()); + private void addGrantedAuthorityCollection(Collection 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 getMappableAttributes() { return mappableAttributes; } /** diff --git a/core/src/main/java/org/springframework/security/authoritymapping/MappableAttributesRetriever.java b/core/src/main/java/org/springframework/security/authoritymapping/MappableAttributesRetriever.java index 6f4b74f774..b5f3365d62 100755 --- a/core/src/main/java/org/springframework/security/authoritymapping/MappableAttributesRetriever.java +++ b/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 GrantedAuthoritys. * - * @return list of all mappable roles + * @return set of all mappable roles */ - String[] getMappableAttributes(); + Set getMappableAttributes(); } diff --git a/core/src/main/java/org/springframework/security/authoritymapping/SimpleMappableAttributesRetriever.java b/core/src/main/java/org/springframework/security/authoritymapping/SimpleMappableAttributesRetriever.java index 5e46376142..ec205ea36a 100755 --- a/core/src/main/java/org/springframework/security/authoritymapping/SimpleMappableAttributesRetriever.java +++ b/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 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 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(aMappableRoles.length); + mappableAttributes.addAll(Arrays.asList(aMappableRoles)); + mappableAttributes = Collections.unmodifiableSet(mappableAttributes); } } diff --git a/core/src/main/java/org/springframework/security/authoritymapping/XmlMappableAttributesRetriever.java b/core/src/main/java/org/springframework/security/authoritymapping/XmlMappableAttributesRetriever.java index 3981df5ae1..1b1ebf8c98 100755 --- a/core/src/main/java/org/springframework/security/authoritymapping/XmlMappableAttributesRetriever.java +++ b/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 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 getMappableAttributes() { + return mappableAttributes; } /** * Get the mappable roles from the specified XML document. */ - private String[] getMappableAttributes(InputStream aStream) { + private Set getMappableAttributes(InputStream aStream) { if (logger.isDebugEnabled()) { logger.debug("Reading mappable attributes from XML document"); } try { Document doc = getDocument(aStream); - String[] roles = getMappableAttributes(doc); + Set 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 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 roleElements = xpath.selectNodes(doc); + Set roles = new HashSet(roleElements.size()); + + for (Node n : roleElements) { + roles.add(n.getNodeValue()); } return roles; } catch (JaxenException e) { diff --git a/core/src/main/java/org/springframework/security/config/FilterChainProxyPostProcessor.java b/core/src/main/java/org/springframework/security/config/FilterChainProxyPostProcessor.java index 11733d4636..08f833bf6f 100644 --- a/core/src/main/java/org/springframework/security/config/FilterChainProxyPostProcessor.java +++ b/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 filters = new ArrayList(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> filterMap = filterChainProxy.getFilterChainMap(); filterMap.put(filterChainProxy.getMatcher().getUniversalMatchPattern(), filters); filterChainProxy.setFilterChainMap(filterMap); diff --git a/core/src/main/java/org/springframework/security/config/SessionRegistryInjectionBeanPostProcessor.java b/core/src/main/java/org/springframework/security/config/SessionRegistryInjectionBeanPostProcessor.java index 8cb1744796..e740748fd8 100644 --- a/core/src/main/java/org/springframework/security/config/SessionRegistryInjectionBeanPostProcessor.java +++ b/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 AuthenticationManagerBeanDefinitionParser if an external - * ConcurrentSessionController is set (and hence an external SessionRegistry). + * Registered by the AuthenticationManagerBeanDefinitionParser 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. *

* 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; - } + 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()); + } - 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; - } + return bean; + } - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.beanFactory = (ListableBeanFactory) beanFactory; - } + 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; + } } diff --git a/core/src/main/java/org/springframework/security/expression/method/MethodExpressionAfterInvocationProvider.java b/core/src/main/java/org/springframework/security/expression/method/MethodExpressionAfterInvocationProvider.java index 69ade8c5dd..cb45168ebf 100644 --- a/core/src/main/java/org/springframework/security/expression/method/MethodExpressionAfterInvocationProvider.java +++ b/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 clazz) { + public boolean supports(Class clazz) { return clazz.isAssignableFrom(MethodInvocation.class); } diff --git a/core/src/main/java/org/springframework/security/ui/AuthenticationDetailsSourceImpl.java b/core/src/main/java/org/springframework/security/ui/AuthenticationDetailsSourceImpl.java index 676bbee977..c8c5db8f97 100755 --- a/core/src/main/java/org/springframework/security/ui/AuthenticationDetailsSourceImpl.java +++ b/core/src/main/java/org/springframework/security/ui/AuthenticationDetailsSourceImpl.java @@ -14,68 +14,68 @@ import org.springframework.util.ReflectionUtils; * Any object that accepts an Object as its sole constructor can * be used instead of this default. *

- * + * * @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; + } } diff --git a/core/src/main/java/org/springframework/security/ui/WebAuthenticationDetailsSource.java b/core/src/main/java/org/springframework/security/ui/WebAuthenticationDetailsSource.java index 830b01d701..56068f62bf 100644 --- a/core/src/main/java/org/springframework/security/ui/WebAuthenticationDetailsSource.java +++ b/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 HttpServletRequest object. *

- * By default will create an instance of WebAuthenticationDetails. Any object that accepts a + * By default will create an instance of WebAuthenticationDetails. Any object that accepts a * HttpServletRequest 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; } diff --git a/core/src/main/java/org/springframework/security/ui/preauth/j2ee/AbstractPreAuthenticatedAuthenticationDetailsSource.java b/core/src/main/java/org/springframework/security/ui/preauth/j2ee/AbstractPreAuthenticatedAuthenticationDetailsSource.java index 724953bb84..5b17974481 100644 --- a/core/src/main/java/org/springframework/security/ui/preauth/j2ee/AbstractPreAuthenticatedAuthenticationDetailsSource.java +++ b/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 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 getUserRoles(Object context, String[] mappableRoles); + protected abstract Collection getUserRoles(Object context, Set mappableRoles); /** * @param aJ2eeMappableRolesRetriever diff --git a/core/src/main/java/org/springframework/security/ui/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.java b/core/src/main/java/org/springframework/security/ui/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.java index d511ea7189..772fdfdb95 100755 --- a/core/src/main/java/org/springframework/security/ui/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.java +++ b/core/src/main/java/org/springframework/security/ui/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.java @@ -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 getUserRoles(Object context, String[] mappableRoles) { + protected Collection getUserRoles(Object context, Set mappableRoles) { ArrayList j2eeUserRolesList = new ArrayList(); - 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); } } diff --git a/core/src/main/java/org/springframework/security/ui/switchuser/SwitchUserAuthorityChanger.java b/core/src/main/java/org/springframework/security/ui/switchuser/SwitchUserAuthorityChanger.java index a5f386923f..7038f82734 100644 --- a/core/src/main/java/org/springframework/security/ui/switchuser/SwitchUserAuthorityChanger.java +++ b/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 modifyGrantedAuthorities(UserDetails targetUser, Authentication currentAuthentication, List authoritiesToBeGranted); } diff --git a/core/src/main/java/org/springframework/security/userdetails/memory/UserAttribute.java b/core/src/main/java/org/springframework/security/userdetails/memory/UserAttribute.java index d49fc2a533..4de3af77cd 100644 --- a/core/src/main/java/org/springframework/security/userdetails/memory/UserAttribute.java +++ b/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 authorities = new Vector(); 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} <{@link GrantedAuthority}> * @since 1.1 */ - public void setAuthorities(List authorities) { + public void setAuthorities(List 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} <{@link String}> + * @param authoritiesAsStrings {@link List} <{@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 authoritiesAsStrings) { + setAuthorities(new ArrayList(authoritiesAsStrings.size())); + for(String authority : authoritiesAsStrings) { + addAuthority(new GrantedAuthorityImpl(authority)); } } diff --git a/core/src/main/java/org/springframework/security/userdetails/memory/UserAttributeEditor.java b/core/src/main/java/org/springframework/security/userdetails/memory/UserAttributeEditor.java index 795b79aadc..1acc590016 100644 --- a/core/src/main/java/org/springframework/security/userdetails/memory/UserAttributeEditor.java +++ b/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 authoritiesAsStrings = new ArrayList(); 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); diff --git a/core/src/main/java/org/springframework/security/util/MethodInvocationUtils.java b/core/src/main/java/org/springframework/security/util/MethodInvocationUtils.java index 6b3165d1e9..3197c8be9d 100644 --- a/core/src/main/java/org/springframework/security/util/MethodInvocationUtils.java +++ b/core/src/main/java/org/springframework/security/util/MethodInvocationUtils.java @@ -27,7 +27,8 @@ import org.springframework.util.Assert; /** * Static utility methods for creating MethodInvocations usable within Spring Security. - *

All methods of this class return a {@link org.springframework.security.util.SimpleMethodInvocation}.

+ *

+ * 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 MethodInvocation for specified methodName on the passed object. - * - * @param object the object that will be used to find the relevant Method - * @param methodName the name of the method to find - * - * @return a MethodInvocation, or null if there was a problem - */ - public static MethodInvocation create(Object object, String methodName) { - return create(object, methodName, null); - } - /** * Generates a MethodInvocation for specified methodName on the passed object, * using the args to locate the method. * * @param object the object that will be used to find the relevant Method * @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 MethodInvocation, or null 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> list = new ArrayList>(); 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 MethodInvocation, or null 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 MethodInvocation, or null 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; diff --git a/core/src/main/java/org/springframework/security/vote/AbstractAccessDecisionManager.java b/core/src/main/java/org/springframework/security/vote/AbstractAccessDecisionManager.java index e59ec40a11..eb5758903e 100644 --- a/core/src/main/java/org/springframework/security/vote/AbstractAccessDecisionManager.java +++ b/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 iter = this.decisionVoters.iterator(); while (iter.hasNext()) { diff --git a/core/src/test/java/org/springframework/security/MockAccessDecisionManager.java b/core/src/test/java/org/springframework/security/MockAccessDecisionManager.java index ad4112a4f0..36681f9938 100644 --- a/core/src/test/java/org/springframework/security/MockAccessDecisionManager.java +++ b/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; } } diff --git a/core/src/test/java/org/springframework/security/MockAfterInvocationManager.java b/core/src/test/java/org/springframework/security/MockAfterInvocationManager.java index 847e197da0..c361fc65b9 100644 --- a/core/src/test/java/org/springframework/security/MockAfterInvocationManager.java +++ b/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; } } diff --git a/core/src/test/java/org/springframework/security/afterinvocation/AfterInvocationProviderManagerTests.java b/core/src/test/java/org/springframework/security/afterinvocation/AfterInvocationProviderManagerTests.java index 2a3c4fa85b..4c231298f5 100644 --- a/core/src/test/java/org/springframework/security/afterinvocation/AfterInvocationProviderManagerTests.java +++ b/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 clazz) { + public boolean supports(Class clazz) { return secureObject.isAssignableFrom(clazz); } diff --git a/core/src/test/java/org/springframework/security/annotation/BusinessService.java b/core/src/test/java/org/springframework/security/annotation/BusinessService.java index cbe3629353..68b177185c 100644 --- a/core/src/test/java/org/springframework/security/annotation/BusinessService.java +++ b/core/src/test/java/org/springframework/security/annotation/BusinessService.java @@ -51,10 +51,10 @@ public interface BusinessService { public int someOther(int input); - public List methodReturningAList(List someList); + public List methodReturningAList(List someList); public Object[] methodReturningAnArray(Object[] someArray); - public List methodReturningAList(String userName, String extraParam); + public List methodReturningAList(String userName, String extraParam); } diff --git a/core/src/test/java/org/springframework/security/annotation/BusinessServiceImpl.java b/core/src/test/java/org/springframework/security/annotation/BusinessServiceImpl.java index 4234fc77b6..df84a2e57c 100644 --- a/core/src/test/java/org/springframework/security/annotation/BusinessServiceImpl.java +++ b/core/src/test/java/org/springframework/security/annotation/BusinessServiceImpl.java @@ -37,7 +37,7 @@ public class BusinessServiceImpl implements BusinessService { return input; } - public List methodReturningAList(List someList) { + public List methodReturningAList(List someList) { return someList; } diff --git a/core/src/test/java/org/springframework/security/annotation/ExpressionProtectedBusinessServiceImpl.java b/core/src/test/java/org/springframework/security/annotation/ExpressionProtectedBusinessServiceImpl.java index f9ee029f87..a1473526d5 100644 --- a/core/src/test/java/org/springframework/security/annotation/ExpressionProtectedBusinessServiceImpl.java +++ b/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 methodReturningAList(List someList) { + public List methodReturningAList(List someList) { return someList; } diff --git a/core/src/test/java/org/springframework/security/annotation/Jsr250BusinessServiceImpl.java b/core/src/test/java/org/springframework/security/annotation/Jsr250BusinessServiceImpl.java index 51c9bba6c7..4cf5470ab3 100644 --- a/core/src/test/java/org/springframework/security/annotation/Jsr250BusinessServiceImpl.java +++ b/core/src/test/java/org/springframework/security/annotation/Jsr250BusinessServiceImpl.java @@ -38,12 +38,12 @@ public class Jsr250BusinessServiceImpl implements BusinessService { return input; } - public List methodReturningAList(List someList) { + public List methodReturningAList(List someList) { return someList; } - public List methodReturningAList(String userName, String arg2) { - return new ArrayList(); + public List methodReturningAList(String userName, String arg2) { + return new ArrayList(); } public Object[] methodReturningAnArray(Object[] someArray) { diff --git a/core/src/test/java/org/springframework/security/authoritymapping/SimpleMappableRolesRetrieverTests.java b/core/src/test/java/org/springframework/security/authoritymapping/SimpleMappableRolesRetrieverTests.java index e70f53372a..208e74eeb7 100755 --- a/core/src/test/java/org/springframework/security/authoritymapping/SimpleMappableRolesRetrieverTests.java +++ b/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 result = r.getMappableAttributes(); + Collection rolesColl = Arrays.asList(roles); + assertTrue("Role collections do not match; result: " + result + ", expected: " + rolesColl, rolesColl.containsAll(result) + && result.containsAll(rolesColl)); + } } diff --git a/core/src/test/java/org/springframework/security/authoritymapping/SimpleRoles2GrantedAuthoritiesMapperTests.java b/core/src/test/java/org/springframework/security/authoritymapping/SimpleRoles2GrantedAuthoritiesMapperTests.java index 8d51495163..f4290f412a 100755 --- a/core/src/test/java/org/springframework/security/authoritymapping/SimpleRoles2GrantedAuthoritiesMapperTests.java +++ b/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 result = mapper.getGrantedAuthorities(Arrays.asList(roles)); - Collection resultColl = new ArrayList(result.size()); + Collection resultColl = new ArrayList(result.size()); for (int i = 0; i < result.size(); i++) { resultColl.add(result.get(i).getAuthority()); } - Collection expectedColl = Arrays.asList(expectedGas); + Collection expectedColl = Arrays.asList(expectedGas); assertTrue("Role collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl .containsAll(resultColl) && resultColl.containsAll(expectedColl)); diff --git a/core/src/test/java/org/springframework/security/authoritymapping/XmlMappableRolesRetrieverTests.java b/core/src/test/java/org/springframework/security/authoritymapping/XmlMappableRolesRetrieverTests.java index f15a03fad1..dcf5933639 100755 --- a/core/src/test/java/org/springframework/security/authoritymapping/XmlMappableRolesRetrieverTests.java +++ b/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 = "Role1Role2"; + private static final String DEFAULT_XML = "Role1Role2"; - private static final String DEFAULT_XPATH = "/roles/role/text()"; + private static final String DEFAULT_XPATH = "/roles/role/text()"; - private static final String[] DEFAULT_EXPECTED_ROLES = new String[] { "Role1", "Role2" }; + 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 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 testGetMappableRoles() { + XmlMappableAttributesRetriever r = getXmlMappableRolesRetriever(true, getDefaultInputStream(), DEFAULT_XPATH); + Set 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 testCloseInputStream() { + testCloseInputStream(true); + } - public void testDontCloseInputStream() { - testCloseInputStream(false); - } + 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 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 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 getDefaultInputStream() { + return getInputStream(DEFAULT_XML); + } - private CloseableByteArrayInputStream getInputStream(String data) { - return new CloseableByteArrayInputStream(data.getBytes()); - } + private CloseableByteArrayInputStream getInputStream(String data) { + return new CloseableByteArrayInputStream(data.getBytes()); + } - private static final class TestXmlMappableAttributesRetriever extends XmlMappableAttributesRetriever { - } + private static final class TestXmlMappableAttributesRetriever extends XmlMappableAttributesRetriever { + } - private static final class CloseableByteArrayInputStream extends ByteArrayInputStream { - private boolean closed = false; + private static final class CloseableByteArrayInputStream extends ByteArrayInputStream { + private boolean closed = false; - public CloseableByteArrayInputStream(byte[] buf) { - super(buf); - } + public CloseableByteArrayInputStream(byte[] buf) { + super(buf); + } - public void close() throws IOException { - super.close(); - closed = true; - } + public void close() throws IOException { + super.close(); + closed = true; + } - public boolean isClosed() { - return closed; - } - } + public boolean isClosed() { + return closed; + } + } } diff --git a/core/src/test/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParserTests.java b/core/src/test/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParserTests.java index 4bbc6272f8..b20062c719 100644 --- a/core/src/test/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParserTests.java +++ b/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 arg = new ArrayList(); 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()); diff --git a/core/src/test/java/org/springframework/security/config/MockAfterInvocationProvider.java b/core/src/test/java/org/springframework/security/config/MockAfterInvocationProvider.java index 87d4ad9224..68c3d3a3bb 100644 --- a/core/src/test/java/org/springframework/security/config/MockAfterInvocationProvider.java +++ b/core/src/test/java/org/springframework/security/config/MockAfterInvocationProvider.java @@ -18,7 +18,7 @@ public class MockAfterInvocationProvider implements AfterInvocationProvider { return true; } - public boolean supports(Class clazz) { + public boolean supports(Class clazz) { return true; } diff --git a/core/src/test/java/org/springframework/security/intercept/method/MethodInvocationPrivilegeEvaluatorTests.java b/core/src/test/java/org/springframework/security/intercept/method/MethodInvocationPrivilegeEvaluatorTests.java index d7a3fafb75..c966b51238 100644 --- a/core/src/test/java/org/springframework/security/intercept/method/MethodInvocationPrivilegeEvaluatorTests.java +++ b/core/src/test/java/org/springframework/security/intercept/method/MethodInvocationPrivilegeEvaluatorTests.java @@ -15,23 +15,18 @@ package org.springframework.security.intercept.method; -import junit.framework.TestCase; - -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; -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.MethodInvocationUtils; +import static org.junit.Assert.*; 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; /** @@ -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(); diff --git a/core/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorTests.java b/core/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorTests.java index 08d0ac59de..4670e3df7b 100644 --- a/core/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorTests.java +++ b/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 { diff --git a/core/src/test/java/org/springframework/security/intercept/method/aspectj/AspectJSecurityInterceptorTests.java b/core/src/test/java/org/springframework/security/intercept/method/aspectj/AspectJSecurityInterceptorTests.java index a9608bcd4c..a1ed432572 100644 --- a/core/src/test/java/org/springframework/security/intercept/method/aspectj/AspectJSecurityInterceptorTests.java +++ b/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 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 clazz = TargetObject.class; Method method = clazz.getMethod("countLength", new Class[] {String.class}); MockJoinPoint joinPoint = new MockJoinPoint(new TargetObject(), method); diff --git a/core/src/test/java/org/springframework/security/providers/UsernamePasswordAuthenticationTokenTests.java b/core/src/test/java/org/springframework/security/providers/UsernamePasswordAuthenticationTokenTests.java index 737db6223e..9933035d67 100644 --- a/core/src/test/java/org/springframework/security/providers/UsernamePasswordAuthenticationTokenTests.java +++ b/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); } } diff --git a/core/src/test/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationTokenTests.java b/core/src/test/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationTokenTests.java index 22eac02fc2..868611a213 100644 --- a/core/src/test/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationTokenTests.java +++ b/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 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()); diff --git a/core/src/test/java/org/springframework/security/ui/preauth/j2ee/WebXmlJ2eeDefinedRolesRetrieverTests.java b/core/src/test/java/org/springframework/security/ui/preauth/j2ee/WebXmlJ2eeDefinedRolesRetrieverTests.java index c0f3bc05ee..37de7fd817 100755 --- a/core/src/test/java/org/springframework/security/ui/preauth/j2ee/WebXmlJ2eeDefinedRolesRetrieverTests.java +++ b/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 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 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 j2eeRoles = rolesRetriever.getMappableAttributes(); + assertEquals("J2eeRoles expected size: 0, actual size: " + j2eeRoles.size(), 0, j2eeRoles.size()); + } } diff --git a/core/src/test/java/org/springframework/security/ui/switchuser/SwitchUserProcessingFilterTests.java b/core/src/test/java/org/springframework/security/ui/switchuser/SwitchUserProcessingFilterTests.java index 7faf83604c..6525dfc08d 100644 --- a/core/src/test/java/org/springframework/security/ui/switchuser/SwitchUserProcessingFilterTests.java +++ b/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 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 adminAuths = new ArrayList(); + 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 modifyGrantedAuthorities(UserDetails targetUser, Authentication currentAuthentication, List authoritiesToBeGranted) { + List auths = new ArrayList(); 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); } diff --git a/portlet/src/main/java/org/springframework/security/ui/portlet/PortletPreAuthenticatedAuthenticationDetailsSource.java b/portlet/src/main/java/org/springframework/security/ui/portlet/PortletPreAuthenticatedAuthenticationDetailsSource.java index cafd72f52c..8989a70a3b 100644 --- a/portlet/src/main/java/org/springframework/security/ui/portlet/PortletPreAuthenticatedAuthenticationDetailsSource.java +++ b/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 getUserRoles(Object context, String[] mappableRoles) { - ArrayList portletRoles = new ArrayList(); + protected Collection getUserRoles(Object context, Set mappableRoles) { + ArrayList portletRoles = new ArrayList(); - 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();