SEC-1012: Added more generics and warning suppression

This commit is contained in:
Luke Taylor 2008-11-11 09:06:50 +00:00
parent be34724207
commit e5b1073501
77 changed files with 533 additions and 613 deletions

View File

@ -25,7 +25,6 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import javax.sql.DataSource;
@ -51,7 +50,6 @@ import org.springframework.security.acls.sid.PrincipalSid;
import org.springframework.security.acls.sid.Sid;
import org.springframework.security.util.FieldUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
@ -100,30 +98,30 @@ public final class BasicLookupStrategy implements LookupStrategy {
private static String computeRepeatingSql(String repeatingSql, int requiredRepetitions) {
Assert.isTrue(requiredRepetitions >= 1, "Must be => 1");
String startSql = "select acl_object_identity.object_id_identity, "
+ "acl_entry.ace_order, "
+ "acl_object_identity.id as acl_id, "
+ "acl_object_identity.parent_object, "
+ "acl_object_identity.entries_inheriting, "
+ "acl_entry.id as ace_id, "
+ "acl_entry.mask, "
+ "acl_entry.granting, "
+ "acl_entry.audit_success, "
+ "acl_entry.audit_failure, "
+ "acl_sid.principal as ace_principal, "
+ "acl_sid.sid as ace_sid, "
+ "acli_sid.principal as acl_principal, "
+ "acli_sid.sid as acl_sid, "
+ "acl_class.class "
+ "from acl_object_identity "
+ "left join acl_sid acli_sid on acli_sid.id = acl_object_identity.owner_sid "
+ "left join acl_class on acl_class.id = acl_object_identity.object_id_class "
+ "left join acl_entry on acl_object_identity.id = acl_entry.acl_object_identity "
+ "left join acl_sid on acl_entry.sid = acl_sid.id "
+ "where ( ";
String startSql = "select acl_object_identity.object_id_identity, "
+ "acl_entry.ace_order, "
+ "acl_object_identity.id as acl_id, "
+ "acl_object_identity.parent_object, "
+ "acl_object_identity.entries_inheriting, "
+ "acl_entry.id as ace_id, "
+ "acl_entry.mask, "
+ "acl_entry.granting, "
+ "acl_entry.audit_success, "
+ "acl_entry.audit_failure, "
+ "acl_sid.principal as ace_principal, "
+ "acl_sid.sid as ace_sid, "
+ "acli_sid.principal as acl_principal, "
+ "acli_sid.sid as acl_sid, "
+ "acl_class.class "
+ "from acl_object_identity "
+ "left join acl_sid acli_sid on acli_sid.id = acl_object_identity.owner_sid "
+ "left join acl_class on acl_class.id = acl_object_identity.object_id_class "
+ "left join acl_entry on acl_object_identity.id = acl_entry.acl_object_identity "
+ "left join acl_sid on acl_entry.sid = acl_sid.id "
+ "where ( ";
String endSql = ") order by acl_object_identity.object_id_identity"
+ " asc, acl_entry.ace_order asc";
String endSql = ") order by acl_object_identity.object_id_identity"
+ " asc, acl_entry.ace_order asc";
StringBuffer sqlStringBuffer = new StringBuffer();
sqlStringBuffer.append(startSql);
@ -148,11 +146,8 @@ public final class BasicLookupStrategy implements LookupStrategy {
* @param inputMap the unconverted <code>AclImpl</code>s
* @param currentIdentity the current<code>Acl</code> that we wish to convert (this may be
*
* @return
*
* @throws IllegalStateException DOCUMENT ME!
*/
private AclImpl convert(Map inputMap, Long currentIdentity) {
private AclImpl convert(Map<Long,AclImpl> inputMap, Long currentIdentity) {
Assert.notEmpty(inputMap, "InputMap required");
Assert.notNull(currentIdentity, "CurrentIdentity required");
@ -177,31 +172,31 @@ public final class BasicLookupStrategy implements LookupStrategy {
// Copy the "aces" from the input to the destination
Field fieldAces = FieldUtils.getField(AclImpl.class, "aces");
Field fieldAcl = FieldUtils.getField(AccessControlEntryImpl.class, "acl");
try {
fieldAces.setAccessible(true);
fieldAces.setAccessible(true);
fieldAcl.setAccessible(true);
// Obtain the "aces" from the input ACL
Iterator i = ((List) fieldAces.get(inputAcl)).iterator();
// Create a list in which to store the "aces" for the "result" AclImpl instance
List acesNew = new ArrayList();
List<AccessControlEntryImpl> acesNew = new ArrayList<AccessControlEntryImpl>();
// Iterate over the "aces" input and replace each nested AccessControlEntryImpl.getAcl() with the new "result" AclImpl instance
// This ensures StubAclParent instances are removed, as per SEC-951
while(i.hasNext()) {
AccessControlEntryImpl ace = (AccessControlEntryImpl) i.next();
fieldAcl.set(ace, result);
acesNew.add(ace);
AccessControlEntryImpl ace = (AccessControlEntryImpl) i.next();
fieldAcl.set(ace, result);
acesNew.add(ace);
}
// Finally, now that the "aces" have been converted to have the "result" AclImpl instance, modify the "result" AclImpl instance
fieldAces.set(result, acesNew);
} catch (IllegalAccessException ex) {
throw new IllegalStateException("Could not obtain or set AclImpl or AccessControlEntryImpl fields");
}
return result;
}
@ -214,10 +209,8 @@ public final class BasicLookupStrategy implements LookupStrategy {
* @param rs the ResultSet focused on a current row
*
* @throws SQLException if something goes wrong converting values
* @throws IllegalStateException DOCUMENT ME!
*/
private void convertCurrentResultIntoObject(Map acls, ResultSet rs)
throws SQLException {
private void convertCurrentResultIntoObject(Map<Long,AclImpl> acls, ResultSet rs) throws SQLException {
Long id = new Long(rs.getLong("acl_id"));
// If we already have an ACL for this ID, just create the ACE
@ -262,7 +255,7 @@ public final class BasicLookupStrategy implements LookupStrategy {
}
int mask = rs.getInt("mask");
Permission permission = convertMaskIntoPermission(mask);
Permission permission = convertMaskIntoPermission(mask);
boolean granting = rs.getBoolean("granting");
boolean auditSuccess = rs.getBoolean("audit_success");
boolean auditFailure = rs.getBoolean("audit_failure");
@ -271,11 +264,11 @@ public final class BasicLookupStrategy implements LookupStrategy {
auditSuccess, auditFailure);
Field acesField = FieldUtils.getField(AclImpl.class, "aces");
List aces;
List<AccessControlEntryImpl> aces;
try {
acesField.setAccessible(true);
aces = (List) acesField.get(acl);
aces = (List<AccessControlEntryImpl>) acesField.get(acl);
} catch (IllegalAccessException ex) {
throw new IllegalStateException("Could not obtain AclImpl.ace field: cause[" + ex.getMessage() + "]");
}
@ -287,23 +280,20 @@ public final class BasicLookupStrategy implements LookupStrategy {
}
}
protected Permission convertMaskIntoPermission(int mask) {
return BasePermission.buildFromMask(mask);
}
protected Permission convertMaskIntoPermission(int mask) {
return BasePermission.buildFromMask(mask);
}
/**
* Looks up a batch of <code>ObjectIdentity</code>s directly from the database.<p>The caller is responsible
* for optimization issues, such as selecting the identities to lookup, ensuring the cache doesn't contain them
* already, and adding the returned elements to the cache etc.</p>
* <p>This subclass is required to return fully valid <code>Acl</code>s, including properly-configured
* <p>
* This subclass is required to return fully valid <code>Acl</code>s, including properly-configured
* parent ACLs.</p>
*
* @param objectIdentities DOCUMENT ME!
* @param sids DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private Map lookupObjectIdentities(final ObjectIdentity[] objectIdentities, Sid[] sids) {
private Map<ObjectIdentity, Acl> lookupObjectIdentities(final ObjectIdentity[] objectIdentities, Sid[] sids) {
Assert.notEmpty(objectIdentities, "Must provide identities to lookup");
final Map acls = new HashMap(); // contains Acls with StubAclParents
@ -331,14 +321,14 @@ public final class BasicLookupStrategy implements LookupStrategy {
}
}
}, new ProcessResultSet(acls, sids));
// Lookup the parents, now that our JdbcTemplate has released the database connection (SEC-547)
if (parentsToLookup.size() > 0) {
lookupPrimaryKeys(acls, parentsToLookup, sids);
lookupPrimaryKeys(acls, parentsToLookup, sids);
}
// Finally, convert our "acls" containing StubAclParents into true Acls
Map resultMap = new HashMap();
Map<ObjectIdentity, Acl> resultMap = new HashMap<ObjectIdentity, Acl>();
Iterator iter = acls.values().iterator();
while (iter.hasNext()) {
@ -380,10 +370,10 @@ public final class BasicLookupStrategy implements LookupStrategy {
}
}
}, new ProcessResultSet(acls, sids));
// Lookup the parents, now that our JdbcTemplate has released the database connection (SEC-547)
if (parentsToLookup.size() > 0) {
lookupPrimaryKeys(acls, parentsToLookup, sids);
lookupPrimaryKeys(acls, parentsToLookup, sids);
}
}
@ -400,29 +390,29 @@ public final class BasicLookupStrategy implements LookupStrategy {
* @return a <tt>Map</tt> where keys represent the {@link ObjectIdentity} of the located {@link Acl} and values
* are the located {@link Acl} (never <tt>null</tt> although some entries may be missing; this method
* should not throw {@link NotFoundException}, as a chain of {@link LookupStrategy}s may be used
* to automatically create entries if required)
* to automatically create entries if required)
*/
public Map readAclsById(ObjectIdentity[] objects, Sid[] sids) {
public Map<ObjectIdentity, Acl> readAclsById(ObjectIdentity[] objects, Sid[] sids) {
Assert.isTrue(batchSize >= 1, "BatchSize must be >= 1");
Assert.notEmpty(objects, "Objects to lookup required");
// Map<ObjectIdentity,Acl>
Map result = new HashMap(); // contains FULLY loaded Acl objects
Map<ObjectIdentity, Acl> result = new HashMap<ObjectIdentity, Acl>(); // contains FULLY loaded Acl objects
Set currentBatchToLoad = new HashSet(); // contains ObjectIdentitys
Set<ObjectIdentity> currentBatchToLoad = new HashSet<ObjectIdentity>(); // contains ObjectIdentitys
for (int i = 0; i < objects.length; i++) {
boolean aclFound = false;
boolean aclFound = false;
// Check we don't already have this ACL in the results
// Check we don't already have this ACL in the results
if (result.containsKey(objects[i])) {
aclFound = true;
}
// Check cache for the present ACL entry
if (!aclFound) {
Acl acl = aclCache.getFromCache(objects[i]);
Acl acl = aclCache.getFromCache(objects[i]);
// Ensure any cached element supports all the requested SIDs
// (they should always, as our base impl doesn't filter on SID)
if (acl != null) {
@ -436,7 +426,7 @@ public final class BasicLookupStrategy implements LookupStrategy {
}
}
}
// Load the ACL from the database
if (!aclFound) {
currentBatchToLoad.add(objects[i]);
@ -444,21 +434,21 @@ public final class BasicLookupStrategy implements LookupStrategy {
// Is it time to load from JDBC the currentBatchToLoad?
if ((currentBatchToLoad.size() == this.batchSize) || ((i + 1) == objects.length)) {
if (currentBatchToLoad.size() > 0) {
Map loadedBatch = lookupObjectIdentities((ObjectIdentity[]) currentBatchToLoad.toArray(new ObjectIdentity[] {}), sids);
if (currentBatchToLoad.size() > 0) {
Map<ObjectIdentity, Acl> loadedBatch = lookupObjectIdentities(currentBatchToLoad.toArray(new ObjectIdentity[] {}), sids);
// Add loaded batch (all elements 100% initialized) to results
result.putAll(loadedBatch);
// Add the loaded batch to the cache
Iterator loadedAclIterator = loadedBatch.values().iterator();
while (loadedAclIterator.hasNext()) {
aclCache.putInCache((AclImpl) loadedAclIterator.next());
}
currentBatchToLoad.clear();
}
// Add loaded batch (all elements 100% initialized) to results
result.putAll(loadedBatch);
// Add the loaded batch to the cache
Iterator<Acl> loadedAclIterator = loadedBatch.values().iterator();
while (loadedAclIterator.hasNext()) {
aclCache.putInCache((AclImpl) loadedAclIterator.next());
}
currentBatchToLoad.clear();
}
}
}
@ -493,7 +483,7 @@ public final class BasicLookupStrategy implements LookupStrategy {
* @throws DataAccessException
*/
public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
Set parentIdsToLookup = new HashSet(); // Set of parent_id Longs
Set<Long> parentIdsToLookup = new HashSet<Long>(); // Set of parent_id Longs
while (rs.next()) {
// Convert current row into an Acl (albeit with a StubAclParent)

View File

@ -14,6 +14,7 @@
*/
package org.springframework.security.acls.jdbc;
import org.springframework.security.acls.Acl;
import org.springframework.security.acls.NotFoundException;
import org.springframework.security.acls.objectidentity.ObjectIdentity;
import org.springframework.security.acls.sid.Sid;
@ -23,7 +24,7 @@ import java.util.Map;
/**
* Performs lookups for {@link org.springframework.security.acls.AclService}.
*
*
* @author Ben Alex
* @version $Id$
*/
@ -40,7 +41,7 @@ public interface LookupStrategy {
* @return a <tt>Map</tt> where keys represent the {@link ObjectIdentity} of the located {@link Acl} and values
* are the located {@link Acl} (never <tt>null</tt> although some entries may be missing; this method
* should not throw {@link NotFoundException}, as a chain of {@link LookupStrategy}s may be used
* to automatically create entries if required)
* to automatically create entries if required)
*/
Map readAclsById(ObjectIdentity[] objects, Sid[] sids);
Map<ObjectIdentity, Acl> readAclsById(ObjectIdentity[] objects, Sid[] sids);
}

View File

@ -120,7 +120,7 @@ public abstract class AbstractAclProvider implements AfterInvocationProvider {
*
* @return always <code>true</code>
*/
public boolean supports(Class clazz) {
public boolean supports(Class<? extends Object> clazz) {
return true;
}
}

View File

@ -202,7 +202,7 @@ public class CasAuthenticationProvider implements AuthenticationProvider, Initia
this.ticketValidator = ticketValidator;
}
public boolean supports(final Class authentication) {
public boolean supports(final Class<? extends Object> authentication) {
if (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)) {
return true;
} else if (CasAuthenticationToken.class.isAssignableFrom(authentication)) {

View File

@ -20,10 +20,12 @@ import org.springframework.security.providers.rememberme.RememberMeAuthenticatio
/**
* Basic implementation of {@link AuthenticationTrustResolver}.<p>Makes trust decisions based on whether the passed
* <code>Authentication</code> is an instance of a defined class.</p>
* <p>If {@link #anonymousClass} or {@link #rememberMeClass} is <code>null</code>, the corresponding method will
* always return <code>false</code>.</p>
* Basic implementation of {@link AuthenticationTrustResolver}.
* <p>
* Makes trust decisions based on whether the passed <code>Authentication</code> is an instance of a defined class.
* <p>
* If {@link #anonymousClass} or {@link #rememberMeClass} is <code>null</code>, the corresponding method will
* always return <code>false</code>.
*
* @author Ben Alex
* @version $Id$
@ -31,16 +33,16 @@ import org.springframework.security.providers.rememberme.RememberMeAuthenticatio
public class AuthenticationTrustResolverImpl implements AuthenticationTrustResolver {
//~ Instance fields ================================================================================================
private Class anonymousClass = AnonymousAuthenticationToken.class;
private Class rememberMeClass = RememberMeAuthenticationToken.class;
private Class<? extends Authentication> anonymousClass = AnonymousAuthenticationToken.class;
private Class<? extends Authentication> rememberMeClass = RememberMeAuthenticationToken.class;
//~ Methods ========================================================================================================
public Class getAnonymousClass() {
Class<? extends Authentication> getAnonymousClass() {
return anonymousClass;
}
public Class getRememberMeClass() {
Class<? extends Authentication> getRememberMeClass() {
return rememberMeClass;
}
@ -60,11 +62,11 @@ public class AuthenticationTrustResolverImpl implements AuthenticationTrustResol
return rememberMeClass.isAssignableFrom(authentication.getClass());
}
public void setAnonymousClass(Class anonymousClass) {
public void setAnonymousClass(Class<? extends Authentication> anonymousClass) {
this.anonymousClass = anonymousClass;
}
public void setRememberMeClass(Class rememberMeClass) {
public void setRememberMeClass(Class<? extends Authentication> rememberMeClass) {
this.rememberMeClass = rememberMeClass;
}
}

View File

@ -38,6 +38,7 @@ import org.springframework.util.Assert;
* @author Ben Alex
* @version $Id$
*/
@SuppressWarnings("all")
public class ConfigAttributeDefinition implements Serializable {
public static final ConfigAttributeDefinition NO_ATTRIBUTES = new ConfigAttributeDefinition();

View File

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

View File

@ -226,7 +226,7 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProvider implements
*
* @return always <code>true</code>
*/
public boolean supports(Class clazz) {
public boolean supports(Class<? extends Object> clazz) {
return true;
}
}

View File

@ -210,7 +210,7 @@ public class BasicAclEntryAfterInvocationProvider implements AfterInvocationProv
*
* @return always <code>true</code>
*/
public boolean supports(Class clazz) {
public boolean supports(Class<? extends Object> clazz) {
return true;
}
}

View File

@ -32,7 +32,7 @@ public class Jsr250Voter implements AccessDecisionVoter {
* @param clazz the class.
* @return true
*/
public boolean supports(Class clazz) {
public boolean supports(Class<? extends Object> clazz) {
return true;
}

View File

@ -15,27 +15,24 @@
package org.springframework.security.concurrent;
import org.springframework.security.ui.session.HttpSessionDestroyedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.util.Assert;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.security.ui.session.HttpSessionDestroyedEvent;
import org.springframework.util.Assert;
/**
* Base implementation of {@link org.springframework.security.concurrent.SessionRegistry}
* which also listens for {@link org.springframework.security.ui.session.HttpSessionDestroyedEvent}s
@ -56,95 +53,96 @@ public class SessionRegistryImpl implements SessionRegistry, ApplicationListener
// ~ Instance fields ===============================================================================================
private Map principals = Collections.synchronizedMap(new HashMap()); // <principal:Object,SessionIdSet>
private Map sessionIds = Collections.synchronizedMap(new HashMap()); // <sessionId:Object,SessionInformation>
/** <principal:Object,SessionIdSet> */
private Map<Object,Set<String>> principals = Collections.synchronizedMap(new HashMap<Object,Set<String>>());
/** <sessionId:Object,SessionInformation> */
private Map<String, SessionInformation> sessionIds = Collections.synchronizedMap(new HashMap<String, SessionInformation>());
// ~ Methods =======================================================================================================
// ~ Methods =======================================================================================================
public Object[] getAllPrincipals() {
return principals.keySet().toArray();
}
public Object[] getAllPrincipals() {
return principals.keySet().toArray();
}
public SessionInformation[] getAllSessions(Object principal, boolean includeExpiredSessions) {
Set sessionsUsedByPrincipal = (Set) principals.get(principal);
public SessionInformation[] getAllSessions(Object principal, boolean includeExpiredSessions) {
Set<String> sessionsUsedByPrincipal = principals.get(principal);
if (sessionsUsedByPrincipal == null) {
return null;
}
return null;
}
List list = new ArrayList();
List<SessionInformation> list = new ArrayList<SessionInformation>();
synchronized (sessionsUsedByPrincipal) {
for (Iterator iter = sessionsUsedByPrincipal.iterator(); iter.hasNext();) {
String sessionId = (String) iter.next();
SessionInformation sessionInformation = getSessionInformation(sessionId);
for (String sessionId : sessionsUsedByPrincipal) {
SessionInformation sessionInformation = getSessionInformation(sessionId);
if (sessionInformation == null) {
continue;
}
if (includeExpiredSessions || !sessionInformation.isExpired()) {
list.add(sessionInformation);
}
}
}
list.add(sessionInformation);
}
}
}
return (SessionInformation[]) list.toArray(new SessionInformation[] {});
}
return (SessionInformation[]) list.toArray(new SessionInformation[0]);
}
public SessionInformation getSessionInformation(String sessionId) {
Assert.hasText(sessionId, "SessionId required as per interface contract");
public SessionInformation getSessionInformation(String sessionId) {
Assert.hasText(sessionId, "SessionId required as per interface contract");
return (SessionInformation) sessionIds.get(sessionId);
}
return (SessionInformation) sessionIds.get(sessionId);
}
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof HttpSessionDestroyedEvent) {
String sessionId = ((HttpSession) event.getSource()).getId();
removeSessionInformation(sessionId);
}
}
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof HttpSessionDestroyedEvent) {
String sessionId = ((HttpSession) event.getSource()).getId();
removeSessionInformation(sessionId);
}
}
public void refreshLastRequest(String sessionId) {
Assert.hasText(sessionId, "SessionId required as per interface contract");
public void refreshLastRequest(String sessionId) {
Assert.hasText(sessionId, "SessionId required as per interface contract");
SessionInformation info = getSessionInformation(sessionId);
SessionInformation info = getSessionInformation(sessionId);
if (info != null) {
info.refreshLastRequest();
}
}
if (info != null) {
info.refreshLastRequest();
}
}
public synchronized void registerNewSession(String sessionId, Object principal) {
Assert.hasText(sessionId, "SessionId required as per interface contract");
Assert.notNull(principal, "Principal required as per interface contract");
public synchronized void registerNewSession(String sessionId, Object principal) {
Assert.hasText(sessionId, "SessionId required as per interface contract");
Assert.notNull(principal, "Principal required as per interface contract");
if (logger.isDebugEnabled()) {
logger.debug("Registering session " + sessionId +", for principal " + principal);
}
if (getSessionInformation(sessionId) != null) {
removeSessionInformation(sessionId);
}
removeSessionInformation(sessionId);
}
sessionIds.put(sessionId, new SessionInformation(principal, sessionId, new Date()));
Set sessionsUsedByPrincipal = (Set) principals.get(principal);
Set<String> sessionsUsedByPrincipal = principals.get(principal);
if (sessionsUsedByPrincipal == null) {
sessionsUsedByPrincipal = Collections.synchronizedSet(new HashSet(4));
if (sessionsUsedByPrincipal == null) {
sessionsUsedByPrincipal = Collections.synchronizedSet(new HashSet<String>(4));
principals.put(principal, sessionsUsedByPrincipal);
}
sessionsUsedByPrincipal.add(sessionId);
}
sessionsUsedByPrincipal.add(sessionId);
}
public void removeSessionInformation(String sessionId) {
Assert.hasText(sessionId, "SessionId required as per interface contract");
public void removeSessionInformation(String sessionId) {
Assert.hasText(sessionId, "SessionId required as per interface contract");
SessionInformation info = getSessionInformation(sessionId);
SessionInformation info = getSessionInformation(sessionId);
if (info == null) {
if (info == null) {
return;
}
@ -154,7 +152,7 @@ public class SessionRegistryImpl implements SessionRegistry, ApplicationListener
sessionIds.remove(sessionId);
Set sessionsUsedByPrincipal = (Set) principals.get(info.getPrincipal());
Set<String> sessionsUsedByPrincipal = principals.get(info.getPrincipal());
if (sessionsUsedByPrincipal == null) {
return;
@ -163,7 +161,7 @@ public class SessionRegistryImpl implements SessionRegistry, ApplicationListener
if (logger.isDebugEnabled()) {
logger.debug("Removing session " + sessionId + " from principal's set of registered sessions");
}
synchronized (sessionsUsedByPrincipal) {
sessionsUsedByPrincipal.remove(sessionId);
@ -175,5 +173,5 @@ public class SessionRegistryImpl implements SessionRegistry, ApplicationListener
principals.remove(info.getPrincipal());
}
}
}
}
}

View File

@ -6,54 +6,56 @@ import java.util.List;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.security.providers.AuthenticationProvider;
import org.springframework.security.providers.ProviderManager;
import org.springframework.util.Assert;
/**
* Extended version of {@link ProviderManager the default authentication manager} which lazily initializes
* the list of {@link AuthenticationProvider}s. This prevents some of the issues that have occurred with
* the list of {@link AuthenticationProvider}s. This prevents some of the issues that have occurred with
* namespace configuration where early instantiation of a security interceptor has caused the AuthenticationManager
* and thus dependent beans (typically UserDetailsService implementations or DAOs) to be initialized too early.
*
* and thus dependent beans (typically UserDetailsService implementations or DAOs) to be initialized too early.
*
* @author Luke Taylor
* @since 2.0.4
*/
public class NamespaceAuthenticationManager extends ProviderManager implements BeanFactoryAware {
BeanFactory beanFactory;
List providerBeanNames;
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
BeanFactory beanFactory;
List<String> providerBeanNames;
public void afterPropertiesSet() throws Exception {
Assert.notNull(providerBeanNames, "provideBeanNames has not been set");
Assert.notEmpty(providerBeanNames, "No authentication providers were found in the application context");
super.afterPropertiesSet();
}
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
/**
* Overridden to lazily-initialize the list of providers on first use.
*/
public List getProviders() {
// We use the names array to determine whether the list has been set yet.
if (providerBeanNames != null) {
List providers = new ArrayList();
Iterator beanNames = providerBeanNames.iterator();
while (beanNames.hasNext()) {
providers.add(beanFactory.getBean((String) beanNames.next()));
}
providerBeanNames = null;
setProviders(providers);
}
return super.getProviders();
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(providerBeanNames, "provideBeanNames has not been set");
Assert.notEmpty(providerBeanNames, "No authentication providers were found in the application context");
public void setProviderBeanNames(List provideBeanNames) {
this.providerBeanNames = provideBeanNames;
}
super.afterPropertiesSet();
}
/**
* Overridden to lazily-initialize the list of providers on first use.
*/
public List<AuthenticationProvider> getProviders() {
// We use the names array to determine whether the list has been set yet.
if (providerBeanNames != null) {
ArrayList<AuthenticationProvider> providers = new ArrayList<AuthenticationProvider>();
Iterator<String> beanNames = providerBeanNames.iterator();
while (beanNames.hasNext()) {
providers.add((AuthenticationProvider) beanFactory.getBean(beanNames.next()));
}
providerBeanNames = null;
providers.trimToSize();
setProviders(providers);
}
return super.getProviders();
}
public void setProviderBeanNames(List<String> provideBeanNames) {
this.providerBeanNames = provideBeanNames;
}
}

View File

@ -106,7 +106,7 @@ public class HttpSessionContextIntegrationFilter extends SpringSecurityFilter im
//~ Instance fields ================================================================================================
private Class contextClass = SecurityContextImpl.class;
private Class<? extends SecurityContext> contextClass = SecurityContextImpl.class;
private Object contextObject;
@ -152,8 +152,8 @@ public class HttpSessionContextIntegrationFilter extends SpringSecurityFilter im
* method.
*/
private boolean cloneFromHttpSession = false;
private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
public boolean isCloneFromHttpSession() {
return cloneFromHttpSession;
@ -180,7 +180,7 @@ public class HttpSessionContextIntegrationFilter extends SpringSecurityFilter im
throw new IllegalArgumentException(
"If using forceEagerSessionCreation, you must set allowSessionCreation to also be true");
}
contextObject = generateNewContext();
}
@ -327,7 +327,7 @@ public class HttpSessionContextIntegrationFilter extends SpringSecurityFilter im
/**
* Stores the supplied security context in the session (if available) and if it has changed since it was
* set at the start of the request. If the AuthenticationTrustResolver identifies the current user as
* anonymous, then the context will not be stored.
* anonymous, then the context will not be stored.
*
* @param securityContext the context object obtained from the SecurityContextHolder after the request has
* been processed by the filter chain. SecurityContextHolder.getContext() cannot be used to obtain
@ -363,13 +363,13 @@ public class HttpSessionContextIntegrationFilter extends SpringSecurityFilter im
+ "(because the allowSessionCreation property is false) - SecurityContext thus not "
+ "stored for next request");
}
} else if (!contextObject.equals(securityContext)) {
} else if (!contextObject.equals(securityContext)) {
if (logger.isDebugEnabled()) {
logger.debug("HttpSession being created as SecurityContextHolder contents are non-default");
}
httpSession = safeGetSession(request, true);
} else {
if (logger.isDebugEnabled()) {
logger.debug("HttpSession is null, but SecurityContextHolder has not changed from default: ' "
@ -383,28 +383,28 @@ public class HttpSessionContextIntegrationFilter extends SpringSecurityFilter im
// If HttpSession exists, store current SecurityContextHolder contents but only if
// the SecurityContext has actually changed (see JIRA SEC-37)
if (httpSession != null && securityContext.hashCode() != contextHashBeforeChainExecution) {
// See SEC-766
if (authenticationTrustResolver.isAnonymous(securityContext.getAuthentication())) {
// See SEC-766
if (authenticationTrustResolver.isAnonymous(securityContext.getAuthentication())) {
if (logger.isDebugEnabled()) {
logger.debug("SecurityContext contents are anonymous - context will not be stored in HttpSession. ");
}
} else {
httpSession.setAttribute(SPRING_SECURITY_CONTEXT_KEY, securityContext);
if (logger.isDebugEnabled()) {
logger.debug("SecurityContext stored to HttpSession: '" + securityContext + "'");
}
}
} else {
httpSession.setAttribute(SPRING_SECURITY_CONTEXT_KEY, securityContext);
if (logger.isDebugEnabled()) {
logger.debug("SecurityContext stored to HttpSession: '" + securityContext + "'");
}
}
}
}
private HttpSession safeGetSession(HttpServletRequest request, boolean allowCreate) {
try {
return request.getSession(allowCreate);
}
catch (IllegalStateException ignored) {
return null;
}
}
}
public SecurityContext generateNewContext() throws ServletException {
@ -427,10 +427,11 @@ public class HttpSessionContextIntegrationFilter extends SpringSecurityFilter im
this.allowSessionCreation = allowSessionCreation;
}
protected Class getContextClass() {
protected Class<? extends SecurityContext> getContextClass() {
return contextClass;
}
@SuppressWarnings("unchecked")
public void setContextClass(Class secureContext) {
this.contextClass = secureContext;
}

View File

@ -31,7 +31,7 @@ import org.springframework.util.Assert;
public class InheritableThreadLocalSecurityContextHolderStrategy implements SecurityContextHolderStrategy {
//~ Static fields/initializers =====================================================================================
private static ThreadLocal contextHolder = new InheritableThreadLocal();
private static ThreadLocal<SecurityContext> contextHolder = new InheritableThreadLocal<SecurityContext>();
//~ Methods ========================================================================================================
@ -44,7 +44,7 @@ public class InheritableThreadLocalSecurityContextHolderStrategy implements Secu
contextHolder.set(new SecurityContextImpl());
}
return (SecurityContext) contextHolder.get();
return contextHolder.get();
}
public void setContext(SecurityContext context) {

View File

@ -31,7 +31,7 @@ import org.springframework.util.Assert;
public class ThreadLocalSecurityContextHolderStrategy implements SecurityContextHolderStrategy {
//~ Static fields/initializers =====================================================================================
private static ThreadLocal contextHolder = new ThreadLocal();
private static ThreadLocal<SecurityContext> contextHolder = new ThreadLocal<SecurityContext>();
//~ Methods ========================================================================================================
@ -44,7 +44,7 @@ public class ThreadLocalSecurityContextHolderStrategy implements SecurityContext
contextHolder.set(new SecurityContextImpl());
}
return (SecurityContext) contextHolder.get();
return contextHolder.get();
}
public void setContext(SecurityContext context) {

View File

@ -1,9 +1,9 @@
package org.springframework.security.expression;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.List;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
@ -49,9 +49,10 @@ public class DefaultSecurityExpressionHandler implements SecurityExpressionHandl
return ctx;
}
@SuppressWarnings("unchecked")
public Object filter(Object filterTarget, Expression filterExpression, EvaluationContext ctx) {
SecurityExpressionRoot rootObject = (SecurityExpressionRoot) ctx.getRootContextObject();
Set removeList = new HashSet();
List retainList;
if (logger.isDebugEnabled()) {
logger.debug("Filtering with expression: " + filterExpression.getExpressionString());
@ -59,6 +60,7 @@ public class DefaultSecurityExpressionHandler implements SecurityExpressionHandl
if (filterTarget instanceof Collection) {
Collection collection = (Collection)filterTarget;
retainList = new ArrayList(collection.size());
if (logger.isDebugEnabled()) {
logger.debug("Filtering collection with " + collection.size() + " elements");
@ -66,24 +68,24 @@ public class DefaultSecurityExpressionHandler implements SecurityExpressionHandl
for (Object filterObject : (Collection)filterTarget) {
rootObject.setFilterObject(filterObject);
if (!ExpressionUtils.evaluateAsBoolean(filterExpression, ctx)) {
removeList.add(filterObject);
if (ExpressionUtils.evaluateAsBoolean(filterExpression, ctx)) {
retainList.add(filterObject);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Removing elements: " + removeList);
logger.debug("Retaining elements: " + retainList);
}
for(Object toRemove : removeList) {
((Collection)filterTarget).remove(toRemove);
}
collection.clear();
collection.addAll(retainList);
return filterTarget;
}
if (filterTarget.getClass().isArray()) {
Object[] array = (Object[])filterTarget;
retainList = new ArrayList(array.length);
if (logger.isDebugEnabled()) {
logger.debug("Filtering collection with " + array.length + " elements");
@ -92,21 +94,19 @@ public class DefaultSecurityExpressionHandler implements SecurityExpressionHandl
for (int i = 0; i < array.length; i++) {
rootObject.setFilterObject(array[i]);
if (!ExpressionUtils.evaluateAsBoolean(filterExpression, ctx)) {
removeList.add(array[i]);
if (ExpressionUtils.evaluateAsBoolean(filterExpression, ctx)) {
retainList.add(array[i]);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Removing elements: " + removeList);
logger.debug("Retaining elements: " + retainList);
}
Object[] filtered = (Object[]) Array.newInstance(filterTarget.getClass().getComponentType(),
array.length - removeList.size());
for (int i = 0, j = 0; i < array.length; i++) {
if (!removeList.contains(array[i])) {
filtered[j++] = array[i];
}
retainList.size());
for (int i = 0; i < retainList.size(); i++) {
filtered[i] = retainList.get(i);
}
return filtered;

View File

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

View File

@ -35,7 +35,7 @@ public class MethodExpressionVoter implements AccessDecisionVoter {
return attribute instanceof AbstractExpressionBasedMethodConfigAttribute;
}
public boolean supports(Class clazz) {
public boolean supports(Class<? extends Object> clazz) {
return clazz.isAssignableFrom(MethodInvocation.class);
}

View File

@ -13,7 +13,7 @@ public class WebExpressionVoter implements AccessDecisionVoter {
return false;
}
public boolean supports(Class clazz) {
public boolean supports(Class<? extends Object> clazz) {
return clazz.isAssignableFrom(FilterInvocation.class);
}

View File

@ -359,7 +359,7 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
*
* @return the type of secure object the subclass provides services for
*/
public abstract Class getSecureObjectClass();
public abstract Class<? extends Object> getSecureObjectClass();
public boolean isAlwaysReauthenticate() {
return alwaysReauthenticate;

View File

@ -45,7 +45,7 @@ public class MethodSecurityInterceptor extends AbstractSecurityInterceptor imple
return this.objectDefinitionSource;
}
public Class getSecureObjectClass() {
public Class<? extends Object> getSecureObjectClass() {
return MethodInvocation.class;
}

View File

@ -24,7 +24,7 @@ public class AspectJAnnotationSecurityInterceptor extends AbstractSecurityInterc
return this.objectDefinitionSource;
}
public Class getSecureObjectClass() {
public Class<? extends Object> getSecureObjectClass() {
return JoinPoint.class;
}

View File

@ -46,7 +46,7 @@ public class AspectJSecurityInterceptor extends AbstractSecurityInterceptor {
return this.objectDefinitionSource;
}
public Class getSecureObjectClass() {
public Class<? extends Object> getSecureObjectClass() {
return JoinPoint.class;
}

View File

@ -54,7 +54,7 @@ import org.springframework.security.util.UrlMatcher;
*/
public class DefaultFilterInvocationDefinitionSource implements FilterInvocationDefinitionSource {
private static final Set HTTP_METHODS = new HashSet(Arrays.asList(new String[]{ "DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT", "TRACE" }));
private static final Set<String> HTTP_METHODS = new HashSet<String>(Arrays.asList("DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT", "TRACE"));
protected final Log logger = LogFactory.getLog(getClass());
@ -62,9 +62,10 @@ public class DefaultFilterInvocationDefinitionSource implements FilterInvocation
* Non method-specific map of URL patterns to <tt>List<ConfiAttribute></tt>s
* TODO: Store in the httpMethod map with null key.
*/
private Map requestMap = new LinkedHashMap();
private Map<Object, List<ConfigAttribute>> requestMap = new LinkedHashMap<Object, List<ConfigAttribute>>();
/** Stores request maps keyed by specific HTTP methods */
private Map httpMethodMap = new HashMap();
private Map<String, Map<Object, List<ConfigAttribute>>> httpMethodMap =
new HashMap<String, Map<Object, List<ConfigAttribute>>>();
private UrlMatcher urlMatcher;
@ -108,7 +109,7 @@ public class DefaultFilterInvocationDefinitionSource implements FilterInvocation
* a match for a particular URL.
*/
void addSecureUrl(String pattern, String method, List<ConfigAttribute> attr) {
Map mapToUse = getRequestMapForHttpMethod(method);
Map<Object, List<ConfigAttribute>> mapToUse = getRequestMapForHttpMethod(method);
mapToUse.put(urlMatcher.compile(pattern), attr);
@ -123,7 +124,7 @@ public class DefaultFilterInvocationDefinitionSource implements FilterInvocation
* @param method GET, POST etc
* @return map of URL patterns to <tt>ConfigAttribute</tt>s for this method.
*/
private Map getRequestMapForHttpMethod(String method) {
private Map<Object, List<ConfigAttribute>> getRequestMapForHttpMethod(String method) {
if (method == null) {
return requestMap;
}
@ -131,10 +132,10 @@ public class DefaultFilterInvocationDefinitionSource implements FilterInvocation
throw new IllegalArgumentException("Unrecognised HTTP method: '" + method + "'");
}
Map methodRequestmap = (Map) httpMethodMap.get(method);
Map<Object, List<ConfigAttribute>> methodRequestmap = httpMethodMap.get(method);
if (methodRequestmap == null) {
methodRequestmap = new LinkedHashMap();
methodRequestmap = new LinkedHashMap<Object, List<ConfigAttribute>>();
httpMethodMap.put(method, methodRequestmap);
}
@ -195,7 +196,7 @@ public class DefaultFilterInvocationDefinitionSource implements FilterInvocation
List<ConfigAttribute> attributes = null;
Map methodSpecificMap = (Map) httpMethodMap.get(method);
Map<Object, List<ConfigAttribute>> methodSpecificMap = httpMethodMap.get(method);
if (methodSpecificMap != null) {
attributes = lookupUrlInMap(methodSpecificMap, url);
@ -208,10 +209,9 @@ public class DefaultFilterInvocationDefinitionSource implements FilterInvocation
return attributes;
}
private List<ConfigAttribute> lookupUrlInMap(Map<RequestKey, List<ConfigAttribute>> requestMap,
String url) {
private List<ConfigAttribute> lookupUrlInMap(Map<Object, List<ConfigAttribute>> requestMap, String url) {
for (Map.Entry<RequestKey, List<ConfigAttribute>> entry : requestMap.entrySet()) {
for (Map.Entry<Object, List<ConfigAttribute>> entry : requestMap.entrySet()) {
Object p = entry.getKey();
boolean matched = urlMatcher.pathMatchesUrl(entry.getKey(), url);
@ -235,7 +235,7 @@ public class DefaultFilterInvocationDefinitionSource implements FilterInvocation
return this.requestMap.size();
}
Map getRequestMap() {
/*Map<Object, List<ConfigAttribute>>*/ Map getRequestMap() {
return requestMap;
}

View File

@ -23,7 +23,7 @@ import java.util.regex.Pattern;
*/
public class FIDSToFilterChainMapConverter {
private LinkedHashMap filterChainMap = new LinkedHashMap();
private LinkedHashMap<String, List<Filter>> filterChainMap = new LinkedHashMap<String, List<Filter>>();
private UrlMatcher matcher;
public FIDSToFilterChainMapConverter(DefaultFilterInvocationDefinitionSource fids, ApplicationContext appContext) {
@ -31,15 +31,12 @@ public class FIDSToFilterChainMapConverter {
Assert.notNull(fids.getAllConfigAttributes(), "FilterChainProxy requires the " +
"FilterInvocationDefinitionSource to return a non-null response to getAllConfigAttributes()");
matcher = fids.getUrlMatcher();
Map requestMap = fids.getRequestMap();
Iterator paths = requestMap.keySet().iterator();
Map<Object, List<ConfigAttribute>> requestMap = fids.getRequestMap();
while (paths.hasNext()) {
Object entry = paths.next();
for(Object entry : requestMap.keySet()) {
String path = entry instanceof Pattern ? ((Pattern)entry).pattern() : (String)entry;
List<? extends ConfigAttribute> configAttributeDefinition = (List<? extends ConfigAttribute>) requestMap.get(entry);
List filters = new ArrayList();
List<ConfigAttribute> configAttributeDefinition = requestMap.get(entry);
List<Filter> filters = new ArrayList<Filter>();
for(ConfigAttribute attr : configAttributeDefinition) {
String filterName = attr.getAttribute();
@ -48,7 +45,7 @@ public class FIDSToFilterChainMapConverter {
"method, which is invalid when used with FilterChainProxy");
if (!filterName.equals(FilterChainProxy.TOKEN_NONE)) {
filters.add(appContext.getBean(filterName, Filter.class));
filters.add((Filter) appContext.getBean(filterName, Filter.class));
}
}
@ -56,7 +53,7 @@ public class FIDSToFilterChainMapConverter {
}
}
public Map getFilterChainMap() {
public Map<String, List<Filter>> getFilterChainMap() {
return filterChainMap;
}

View File

@ -87,7 +87,7 @@ public class FilterSecurityInterceptor extends AbstractSecurityInterceptor imple
return this.objectDefinitionSource;
}
public Class getSecureObjectClass() {
public Class<? extends Object> getSecureObjectClass() {
return FilterInvocation.class;
}

View File

@ -44,7 +44,7 @@ public class DefaultSpringSecurityContextSource extends LdapContextSource implem
StringTokenizer st = new StringTokenizer(providerUrl);
ArrayList urls = new ArrayList();
ArrayList<String> urls = new ArrayList<String>();
// Work out rootDn from the first URL and check that the other URLs (if any) match
while (st.hasMoreTokens()) {
@ -62,10 +62,11 @@ public class DefaultSpringSecurityContextSource extends LdapContextSource implem
}
}
super.setUrls((String[]) urls.toArray(new String[urls.size()]));
super.setUrls(urls.toArray(new String[urls.size()]));
super.setBase(rootDn);
}
@SuppressWarnings("unchecked")
public DirContext getReadWriteContext(String userDn, Object credentials) {
Hashtable env = new Hashtable(getAnonymousEnv());

View File

@ -63,5 +63,5 @@ public interface AuthenticationProvider {
* @return <code>true</code> if the implementation can more closely evaluate the <code>Authentication</code> class
* presented
*/
boolean supports(Class authentication);
boolean supports(Class<? extends Object> authentication);
}

View File

@ -15,9 +15,23 @@
package org.springframework.security.providers;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.AbstractAuthenticationManager;
import org.springframework.security.AccountExpiredException;
import org.springframework.security.SpringSecurityMessageSource;
import org.springframework.security.AccountStatusException;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationServiceException;
@ -25,7 +39,7 @@ import org.springframework.security.BadCredentialsException;
import org.springframework.security.CredentialsExpiredException;
import org.springframework.security.DisabledException;
import org.springframework.security.LockedException;
import org.springframework.security.AccountStatusException;
import org.springframework.security.SpringSecurityMessageSource;
import org.springframework.security.concurrent.ConcurrentLoginException;
import org.springframework.security.concurrent.ConcurrentSessionController;
import org.springframework.security.concurrent.NullConcurrentSessionController;
@ -41,26 +55,8 @@ import org.springframework.security.event.authentication.AuthenticationFailurePr
import org.springframework.security.event.authentication.AuthenticationFailureServiceExceptionEvent;
import org.springframework.security.event.authentication.AuthenticationSuccessEvent;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.util.Assert;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
/**
* Iterates an {@link Authentication} request through a list of {@link AuthenticationProvider}s.
@ -109,7 +105,7 @@ public class ProviderManager extends AbstractAuthenticationManager implements In
private ApplicationEventPublisher applicationEventPublisher;
private ConcurrentSessionController sessionController = new NullConcurrentSessionController();
private List providers;
private List<AuthenticationProvider> providers;
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private Properties exceptionMappings = new Properties();
private Properties additionalExceptionMappings = new Properties();
@ -167,15 +163,10 @@ public class ProviderManager extends AbstractAuthenticationManager implements In
* @throws AuthenticationException if authentication fails.
*/
public Authentication doAuthentication(Authentication authentication) throws AuthenticationException {
Iterator iter = getProviders().iterator();
Class toTest = authentication.getClass();
Class<? extends Authentication> toTest = authentication.getClass();
AuthenticationException lastException = null;
while (iter.hasNext()) {
AuthenticationProvider provider = (AuthenticationProvider) iter.next();
for (AuthenticationProvider provider : getProviders()) {
if (!provider.supports(toTest)) {
continue;
}
@ -265,7 +256,7 @@ public class ProviderManager extends AbstractAuthenticationManager implements In
}
}
public List getProviders() {
public List<AuthenticationProvider> getProviders() {
if (providers == null || providers.size() == 0) {
throw new IllegalArgumentException("A list of AuthenticationProviders is required");
}
@ -299,22 +290,20 @@ public class ProviderManager extends AbstractAuthenticationManager implements In
* @throws IllegalArgumentException if the list is empty or null, or any of the elements in the list is not an
* AuthenticationProvider instance.
*/
@SuppressWarnings("unchecked")
public void setProviders(List providers) {
Assert.notEmpty(providers, "A list of AuthenticationProviders is required");
Iterator iter = providers.iterator();
Assert.notEmpty(providers, "A list of AuthenticationProviders is required");
while (iter.hasNext()) {
Object currentObject = iter.next();
Assert.isInstanceOf(AuthenticationProvider.class, currentObject,
"Can only provide AuthenticationProvider instances");
for(Object currentObject : providers) {
Assert.isInstanceOf(AuthenticationProvider.class, currentObject, "Can only provide AuthenticationProvider instances");
}
this.providers = providers;
}
/**
* Set the {@link ConcurrentSessionController} to be used for limiting users' sessions. The {@link
* NullConcurrentSessionController} is used by default.
* Set the {@link ConcurrentSessionController} to be used for limiting users' sessions.
* The {@link NullConcurrentSessionController} is used by default.
*
* @param sessionController {@link ConcurrentSessionController}
*/

View File

@ -37,7 +37,7 @@ public class TestingAuthenticationProvider implements AuthenticationProvider {
return authentication;
}
public boolean supports(Class authentication) {
public boolean supports(Class<? extends Object> authentication) {
return TestingAuthenticationToken.class.isAssignableFrom(authentication);
}
}

View File

@ -76,7 +76,7 @@ public class AnonymousAuthenticationProvider implements AuthenticationProvider,
this.messages = new MessageSourceAccessor(messageSource);
}
public boolean supports(Class authentication) {
public boolean supports(Class<? extends Object> authentication) {
return (AnonymousAuthenticationToken.class.isAssignableFrom(authentication));
}
}

View File

@ -259,7 +259,7 @@ public abstract class AbstractUserDetailsAuthenticationProvider implements Authe
this.userCache = userCache;
}
public boolean supports(Class authentication) {
public boolean supports(Class<? extends Object> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}

View File

@ -431,7 +431,7 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli
this.loginExceptionResolver = loginExceptionResolver;
}
public boolean supports(Class aClass) {
public boolean supports(Class<? extends Object> aClass) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass);
}

View File

@ -253,7 +253,7 @@ public class LdapAuthenticationProvider implements AuthenticationProvider {
return new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());
}
public boolean supports(Class authentication) {
public boolean supports(Class<? extends Object> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}

View File

@ -87,12 +87,12 @@ public abstract class AbstractLdapAuthenticator implements LdapAuthenticator, In
*
* @return the list of possible DN matches, empty if <tt>userDnPatterns</tt> wasn't set.
*/
protected List getUserDns(String username) {
protected List<String> getUserDns(String username) {
if (userDnFormat == null) {
return Collections.EMPTY_LIST;
return Collections.emptyList();
}
List userDns = new ArrayList(userDnFormat.length);
List<String> userDns = new ArrayList<String>(userDnFormat.length);
String[] args = new String[] {username};
synchronized (userDnFormat) {

View File

@ -97,7 +97,7 @@ public class PreAuthenticatedAuthenticationProvider implements AuthenticationPro
/**
* Indicate that this provider only supports PreAuthenticatedAuthenticationToken (sub)classes.
*/
public boolean supports(Class authentication) {
public boolean supports(Class<? extends Object> authentication) {
return PreAuthenticatedAuthenticationToken.class.isAssignableFrom(authentication);
}

View File

@ -71,7 +71,7 @@ public class RemoteAuthenticationProvider implements AuthenticationProvider, Ini
this.remoteAuthenticationManager = remoteAuthenticationManager;
}
public boolean supports(Class authentication) {
public boolean supports(Class<? extends Object> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
}

View File

@ -83,7 +83,7 @@ public class RememberMeAuthenticationProvider implements AuthenticationProvider,
this.messages = new MessageSourceAccessor(messageSource);
}
public boolean supports(Class authentication) {
public boolean supports(Class<? extends Object> authentication) {
return (RememberMeAuthenticationToken.class.isAssignableFrom(authentication));
}
}

View File

@ -74,7 +74,7 @@ public class RunAsImplAuthenticationProvider implements InitializingBean, Authen
this.messages = new MessageSourceAccessor(messageSource);
}
public boolean supports(Class authentication) {
public boolean supports(Class<? extends Object> authentication) {
if (RunAsUserToken.class.isAssignableFrom(authentication)) {
return true;
} else {

View File

@ -22,13 +22,13 @@ public abstract class FilterChainOrder {
public static final int CHANNEL_FILTER = FILTER_CHAIN_FIRST;
public static final int CONCURRENT_SESSION_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int HTTP_SESSION_CONTEXT_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int HTTP_SESSION_CONTEXT_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int LOGOUT_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int X509_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int PRE_AUTH_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int CAS_PROCESSING_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int AUTHENTICATION_PROCESSING_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int OPENID_PROCESSING_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int OPENID_PROCESSING_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int LOGIN_PAGE_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int BASIC_PROCESSING_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int SERVLET_API_SUPPORT_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
@ -36,11 +36,11 @@ public abstract class FilterChainOrder {
public static final int ANONYMOUS_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int EXCEPTION_TRANSLATION_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int NTLM_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int SESSION_FIXATION_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int SESSION_FIXATION_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int FILTER_SECURITY_INTERCEPTOR = FILTER_CHAIN_FIRST + INTERVAL * i++;
public static final int SWITCH_USER_FILTER = FILTER_CHAIN_FIRST + INTERVAL * i++;
private static final Map filterNameToOrder = new LinkedHashMap();
private static final Map<String, Integer> filterNameToOrder = new LinkedHashMap<String, Integer>();
static {
filterNameToOrder.put("FIRST", new Integer(Integer.MIN_VALUE));
@ -58,7 +58,7 @@ public abstract class FilterChainOrder {
filterNameToOrder.put("ANONYMOUS_FILTER", new Integer(ANONYMOUS_FILTER));
filterNameToOrder.put("EXCEPTION_TRANSLATION_FILTER", new Integer(EXCEPTION_TRANSLATION_FILTER));
filterNameToOrder.put("NTLM_FILTER", new Integer(NTLM_FILTER));
filterNameToOrder.put("SESSION_CONTEXT_INTEGRATION_FILTER", new Integer(HTTP_SESSION_CONTEXT_FILTER));
filterNameToOrder.put("SESSION_CONTEXT_INTEGRATION_FILTER", new Integer(HTTP_SESSION_CONTEXT_FILTER));
filterNameToOrder.put("FILTER_SECURITY_INTERCEPTOR", new Integer(FILTER_SECURITY_INTERCEPTOR));
filterNameToOrder.put("SWITCH_USER_FILTER", new Integer(SWITCH_USER_FILTER));
filterNameToOrder.put("LAST", new Integer(Integer.MAX_VALUE));
@ -66,7 +66,7 @@ public abstract class FilterChainOrder {
/** Allows filters to be used by name in the XSD file without explicit reference to Java constants */
public static int getOrder(String filterName) {
Integer order = (Integer) filterNameToOrder.get(filterName);
Integer order = filterNameToOrder.get(filterName);
Assert.notNull(order, "Unable to match filter name " + filterName);

View File

@ -37,7 +37,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource extends Abs
* @return GrantedAuthority[] mapped from the user's J2EE roles.
*/
protected Collection<String> getUserRoles(Object context, String[] mappableRoles) {
ArrayList j2eeUserRolesList = new ArrayList();
ArrayList<String> j2eeUserRolesList = new ArrayList<String>();
for (int i = 0; i < mappableRoles.length; i++) {
if (((HttpServletRequest)context).isUserInRole(mappableRoles[i])) {

View File

@ -33,6 +33,7 @@ import java.util.NoSuchElementException;
* @author Andrey Grebnev
* @version $Id$
*/
@SuppressWarnings("unchecked")
public class Enumerator implements Enumeration {
//~ Instance fields ================================================================================================
@ -73,7 +74,7 @@ public class Enumerator implements Enumeration {
this.iterator = iterator;
}
/**
/**
* Return an Enumeration over the values returned by the specified
* Iterator.
*
@ -81,7 +82,6 @@ public class Enumerator implements Enumeration {
* @param clone true to clone iterator
*/
public Enumerator(Iterator iterator, boolean clone) {
super();
if (!clone) {
this.iterator = iterator;
@ -96,7 +96,7 @@ public class Enumerator implements Enumeration {
}
}
/**
/**
* Return an Enumeration over the values of the specified Map.
*
* @param map Map whose values should be enumerated

View File

@ -46,6 +46,7 @@ import java.util.TreeMap;
* @author Ben Alex
* @version $Id$
*/
@SuppressWarnings("unchecked")
public class SavedRequest implements java.io.Serializable {
//~ Static fields/initializers =====================================================================================

View File

@ -23,6 +23,7 @@ import org.springframework.security.userdetails.User;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.security.util.AuthorityUtils;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.support.MessageSourceAccessor;
@ -47,23 +48,23 @@ import javax.sql.DataSource;
/**
* <tt>UserDetailsServiceRetrieves</tt> implementation which retrieves the user details
* <tt>UserDetailsServiceRetrieves</tt> implementation which retrieves the user details
* (username, password, enabled flag, and authorities) from a database using JDBC queries.
*
* <h3>Default Schema</h3>
*
* <h3>Default Schema</h3>
* A default database schema is assumed, with two tables "users" and "authorities".
*
*
* <h4>The Users table</h4>
*
*
* This table contains the login name, password and enabled status of the user.
*
*
* <table>
* <tr><th>Column</th></tr>
* <tr><td>username</td></tr>
* <tr><td>password</td></tr>
* <tr><td>enabled</td></tr>
* </table>
*
*
* <h4>The Authorities Table</h4>
*
* <table>
@ -73,7 +74,7 @@ import javax.sql.DataSource;
* </table>
*
* If you are using an existing schema you will have to set the queries <tt>usersByUsernameQuery</tt> and
* <tt>authoritiesByUsernameQuery</tt> to match your database setup
* <tt>authoritiesByUsernameQuery</tt> to match your database setup
* (see {@link #DEF_USERS_BY_USERNAME_QUERY} and {@link #DEF_AUTHORITIES_BY_USERNAME_QUERY}).
*
* <p>
@ -81,7 +82,7 @@ import javax.sql.DataSource;
* accounts or the expiration of user credentials. However, it does recognise and honour the user enabled/disabled
* column. This should map to a <tt>boolean</tt> type in the result set (the SQL type will depend on the
* database you are using). All the other columns map to <tt>String</tt>s.
*
*
* <h3>Group Support</h3>
* Support for group-based authorities can be enabled by setting the <tt>enableGroups</tt> property to <tt>true</tt>
* (you may also then wish to set <tt>enableAuthorities</tt> to <tt>false</tt> to disable loading of authorities
@ -151,7 +152,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {
* @param authorities the current granted authorities, as populated from the <code>authoritiesByUsername</code>
* mapping
*/
protected void addCustomAuthorities(String username, List authorities) {}
protected void addCustomAuthorities(String username, List<GrantedAuthority> authorities) {}
public String getUsersByUsernameQuery() {
return usersByUsernameQuery;
@ -172,7 +173,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {
}
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
List users = loadUsersByUsername(username);
List<UserDetails> users = loadUsersByUsername(username);
if (users.size() == 0) {
throw new UsernameNotFoundException(
@ -181,7 +182,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {
UserDetails user = (UserDetails) users.get(0); // contains no GrantedAuthority[]
Set dbAuthsSet = new HashSet();
Set<GrantedAuthority> dbAuthsSet = new HashSet<GrantedAuthority>();
if (enableAuthorities) {
dbAuthsSet.addAll(loadUserAuthorities(user.getUsername()));
@ -191,7 +192,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {
dbAuthsSet.addAll(loadGroupAuthorities(user.getUsername()));
}
List dbAuths = new ArrayList(dbAuthsSet);
List<GrantedAuthority> dbAuths = new ArrayList<GrantedAuthority>(dbAuthsSet);
addCustomAuthorities(user.getUsername(), dbAuths);
@ -201,49 +202,47 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {
new Object[] {username}, "User {0} has no GrantedAuthority"), username);
}
GrantedAuthority[] arrayAuths = (GrantedAuthority[]) dbAuths.toArray(new GrantedAuthority[dbAuths.size()]);
return createUserDetails(username, user, arrayAuths);
return createUserDetails(username, user, dbAuths);
}
/**
* Executes the <tt>usersByUsernameQuery</tt> and returns a list of UserDetails objects (there should normally
* only be one matching user).
/**
* Executes the <tt>usersByUsernameQuery</tt> and returns a list of UserDetails objects (there should normally
* only be one matching user).
*/
protected List loadUsersByUsername(String username) {
protected List<UserDetails> loadUsersByUsername(String username) {
return usersByUsernameMapping.execute(username);
}
/**
* Loads authorities by executing the authoritiesByUsernameQuery.
*
*
* @return a list of GrantedAuthority objects for the user
*/
protected List loadUserAuthorities(String username) {
protected List<GrantedAuthority> loadUserAuthorities(String username) {
return authoritiesByUsernameMapping.execute(username);
}
protected List loadGroupAuthorities(String username) {
protected List<GrantedAuthority> loadGroupAuthorities(String username) {
return groupAuthoritiesByUsernameMapping.execute(username);
}
/**
* Can be overridden to customize the creation of the final UserDetailsObject returnd from <tt>loadUserByUsername</tt>.
*
*
* @param username the name originally passed to loadUserByUsername
* @param userFromUserQuery the object returned from the execution of the
* @param userFromUserQuery the object returned from the execution of the
* @param combinedAuthorities the combined array of authorities from all the authority loading queries.
* @return the final UserDetails which should be used in the system.
*/
protected UserDetails createUserDetails(String username, UserDetails userFromUserQuery,
GrantedAuthority[] combinedAuthorities) {
protected UserDetails createUserDetails(String username, UserDetails userFromUserQuery,
List<GrantedAuthority> combinedAuthorities) {
String returnUsername = userFromUserQuery.getUsername();
if (!usernameBasedPrimaryKey) {
returnUsername = username;
}
return new User(returnUsername, userFromUserQuery.getPassword(), userFromUserQuery.isEnabled(),
return new User(returnUsername, userFromUserQuery.getPassword(), userFromUserQuery.isEnabled(),
true, true, true, combinedAuthorities);
}
@ -395,8 +394,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {
String username = rs.getString(1);
String password = rs.getString(2);
boolean enabled = rs.getBoolean(3);
UserDetails user = new User(username, password, enabled, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("HOLDER")});
UserDetails user = new User(username, password, enabled, true, true, true, AuthorityUtils.NO_AUTHORITIES);
return user;
}

View File

@ -37,7 +37,7 @@ public class Person extends LdapUserDetailsImpl {
private String sn;
private String description;
private String telephoneNumber;
private List cn = new ArrayList();
private List<String> cn = new ArrayList<String>();
protected Person() {
}
@ -47,18 +47,18 @@ public class Person extends LdapUserDetailsImpl {
}
public String[] getCn() {
return (String[]) cn.toArray(new String[cn.size()]);
return cn.toArray(new String[cn.size()]);
}
public String getDescription() {
return description;
}
return description;
}
public String getTelephoneNumber() {
return telephoneNumber;
}
public String getTelephoneNumber() {
return telephoneNumber;
}
protected void populateContext(DirContextAdapter adapter) {
protected void populateContext(DirContextAdapter adapter) {
adapter.setAttributeValue("sn", sn);
adapter.setAttributeValues("cn", getCn());
adapter.setAttributeValue("description", getDescription());
@ -89,12 +89,12 @@ public class Person extends LdapUserDetailsImpl {
}
}
public Essence(Person copyMe) {
public Essence(Person copyMe) {
super(copyMe);
setSn(copyMe.sn);
setDescription(copyMe.getDescription());
setTelephoneNumber(copyMe.getTelephoneNumber());
((Person) instance).cn = new ArrayList(copyMe.cn);
((Person) instance).cn = new ArrayList<String>(copyMe.cn);
}
protected LdapUserDetailsImpl createTarget() {
@ -112,14 +112,14 @@ public class Person extends LdapUserDetailsImpl {
public void addCn(String value) {
((Person) instance).cn.add(value);
}
public void setTelephoneNumber(String tel) {
((Person) instance).telephoneNumber = tel;
}
public void setDescription(String desc) {
((Person) instance).description = desc;
}
public void setTelephoneNumber(String tel) {
((Person) instance).telephoneNumber = tel;
}
public void setDescription(String desc) {
((Person) instance).description = desc;
}
public LdapUserDetails createUserDetails() {
Person p = (Person) super.createUserDetails();

View File

@ -74,6 +74,7 @@ import javax.servlet.ServletResponse;
* @author Ben Alex
* @version $Id$
*/
@SuppressWarnings("unchecked")
public class FilterToBeanProxy implements Filter {
//~ Instance fields ================================================================================================

View File

@ -35,12 +35,12 @@ import java.util.Map;
public class PortMapperImpl implements PortMapper {
//~ Instance fields ================================================================================================
private Map httpsPortMappings;
private Map<Integer, Integer> httpsPortMappings;
//~ Constructors ===================================================================================================
public PortMapperImpl() {
httpsPortMappings = new HashMap();
httpsPortMappings = new HashMap<Integer, Integer>();
httpsPortMappings.put(new Integer(80), new Integer(443));
httpsPortMappings.put(new Integer(8080), new Integer(8443));
}
@ -50,18 +50,16 @@ public class PortMapperImpl implements PortMapper {
/**
* Returns the translated (Integer -> Integer) version of the original port mapping specified via
* setHttpsPortMapping()
*
* @return DOCUMENT ME!
*/
public Map getTranslatedPortMappings() {
public Map<Integer, Integer> getTranslatedPortMappings() {
return httpsPortMappings;
}
public Integer lookupHttpPort(Integer httpsPort) {
Iterator iter = httpsPortMappings.keySet().iterator();
Iterator<Integer> iter = httpsPortMappings.keySet().iterator();
while (iter.hasNext()) {
Integer httpPort = (Integer) iter.next();
Integer httpPort = iter.next();
if (httpsPortMappings.get(httpPort).equals(httpsPort)) {
return httpPort;
@ -72,7 +70,7 @@ public class PortMapperImpl implements PortMapper {
}
public Integer lookupHttpsPort(Integer httpPort) {
return (Integer) httpsPortMappings.get(httpPort);
return httpsPortMappings.get(httpPort);
}
/**
@ -93,17 +91,14 @@ public class PortMapperImpl implements PortMapper {
* @throws IllegalArgumentException if input map does not consist of String keys and values, each representing an
* integer port number in the range 1-65535 for that mapping.
*/
public void setPortMappings(Map newMappings) {
public void setPortMappings(Map<String,String> newMappings) {
Assert.notNull(newMappings, "A valid list of HTTPS port mappings must be provided");
httpsPortMappings.clear();
Iterator it = newMappings.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Integer httpPort = new Integer((String) entry.getKey());
Integer httpsPort = new Integer((String) entry.getValue());
for (Map.Entry<String,String> entry : newMappings.entrySet()) {
Integer httpPort = new Integer(entry.getKey());
Integer httpsPort = new Integer(entry.getValue());
if ((httpPort.intValue() < 1) || (httpPort.intValue() > 65535) || (httpsPort.intValue() < 1)
|| (httpsPort.intValue() > 65535)) {

View File

@ -84,12 +84,12 @@ public final class StringSplitUtils {
* @return a <code>Map</code> representing the array contents, or <code>null</code> if the array to process was
* null or empty
*/
public static Map splitEachArrayElementAndCreateMap(String[] array, String delimiter, String removeCharacters) {
public static Map<String, String> splitEachArrayElementAndCreateMap(String[] array, String delimiter, String removeCharacters) {
if ((array == null) || (array.length == 0)) {
return null;
}
Map map = new HashMap();
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < array.length; i++) {
String postRemove;
@ -155,7 +155,7 @@ public final class StringSplitUtils {
return EMPTY_STRING_ARRAY;
}
List list = new ArrayList();
List<String> list = new ArrayList<String>();
int i = 0;
int start = 0;
boolean match = false;
@ -188,7 +188,7 @@ public final class StringSplitUtils {
list.add(str.substring(start, i));
}
return (String[]) list.toArray(new String[list.size()]);
return list.toArray(new String[list.size()]);
}
}

View File

@ -40,7 +40,7 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan
MessageSourceAware {
//~ Instance fields ================================================================================================
private List decisionVoters;
private List<AccessDecisionVoter> decisionVoters;
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
@ -72,10 +72,10 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan
this.allowIfAllAbstainDecisions = allowIfAllAbstainDecisions;
}
public void setDecisionVoters(List newList) {
public void setDecisionVoters(List<AccessDecisionVoter> newList) {
Assert.notEmpty(newList);
Iterator iter = newList.iterator();
Iterator<AccessDecisionVoter> iter = newList.iterator();
while (iter.hasNext()) {
Object currentObject = iter.next();
@ -91,10 +91,10 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan
}
public boolean supports(ConfigAttribute attribute) {
Iterator iter = this.decisionVoters.iterator();
Iterator<AccessDecisionVoter> iter = this.decisionVoters.iterator();
while (iter.hasNext()) {
AccessDecisionVoter voter = (AccessDecisionVoter) iter.next();
AccessDecisionVoter voter = iter.next();
if (voter.supports(attribute)) {
return true;
@ -114,10 +114,10 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan
* @return true if this type is supported
*/
public boolean supports(Class clazz) {
Iterator iter = this.decisionVoters.iterator();
Iterator<AccessDecisionVoter> iter = this.decisionVoters.iterator();
while (iter.hasNext()) {
AccessDecisionVoter voter = (AccessDecisionVoter) iter.next();
AccessDecisionVoter voter = iter.next();
if (!voter.supports(clazz)) {
return false;

View File

@ -78,7 +78,7 @@ public abstract class AbstractAclVoter implements AccessDecisionVoter {
*
* @return <code>true</code> if the secure object is <code>MethodInvocation</code>, <code>false</code> otherwise
*/
public boolean supports(Class clazz) {
public boolean supports(Class<? extends Object> clazz) {
if (MethodInvocation.class.isAssignableFrom(clazz)) {
return true;
} else if (JoinPoint.class.isAssignableFrom(clazz)) {

View File

@ -63,7 +63,7 @@ public interface AccessDecisionVoter {
*
* @return true if the implementation can process the indicated class
*/
boolean supports(Class clazz);
boolean supports(Class<? extends Object> clazz);
/**
* Indicates whether or not access is granted.

View File

@ -83,17 +83,14 @@ public class AuthenticatedVoter implements AccessDecisionVoter {
*
* @return always <code>true</code>
*/
public boolean supports(Class clazz) {
public boolean supports(Class<? extends Object> clazz) {
return true;
}
public int vote(Authentication authentication, Object object, List<ConfigAttribute> attributes) {
int result = ACCESS_ABSTAIN;
Iterator iter = attributes.iterator();
while (iter.hasNext()) {
ConfigAttribute attribute = (ConfigAttribute) iter.next();
for (ConfigAttribute attribute : attributes) {
if (this.supports(attribute)) {
result = ACCESS_DENIED;

View File

@ -88,7 +88,7 @@ public class RoleVoter implements AccessDecisionVoter {
*
* @return always <code>true</code>
*/
public boolean supports(Class clazz) {
public boolean supports(Class<? extends Object> clazz) {
return true;
}

View File

@ -29,22 +29,9 @@ import org.springframework.security.providers.rememberme.RememberMeAuthenticatio
* @version $Id$
*/
public class AuthenticationTrustResolverImplTests extends TestCase {
//~ Constructors ===================================================================================================
public AuthenticationTrustResolverImplTests() {
super();
}
public AuthenticationTrustResolverImplTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AuthenticationTrustResolverImplTests.class);
}
public void testCorrectOperationIsAnonymous() {
AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl();
assertTrue(trustResolver.isAnonymous(
@ -69,11 +56,11 @@ public class AuthenticationTrustResolverImplTests extends TestCase {
AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl();
assertEquals(AnonymousAuthenticationToken.class, trustResolver.getAnonymousClass());
trustResolver.setAnonymousClass(String.class);
assertEquals(String.class, trustResolver.getAnonymousClass());
trustResolver.setAnonymousClass(TestingAuthenticationToken.class);
assertEquals(TestingAuthenticationToken.class, trustResolver.getAnonymousClass());
assertEquals(RememberMeAuthenticationToken.class, trustResolver.getRememberMeClass());
trustResolver.setRememberMeClass(String.class);
assertEquals(String.class, trustResolver.getRememberMeClass());
trustResolver.setRememberMeClass(TestingAuthenticationToken.class);
assertEquals(TestingAuthenticationToken.class, trustResolver.getRememberMeClass());
}
}

View File

@ -35,16 +35,8 @@ import org.springframework.security.util.SimpleMethodInvocation;
* @author Ben Alex
* @version $Id$
*/
@SuppressWarnings("unchecked")
public class AfterInvocationProviderManagerTests extends TestCase {
//~ Constructors ===================================================================================================
public AfterInvocationProviderManagerTests() {
super();
}
public AfterInvocationProviderManagerTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
@ -167,7 +159,7 @@ public class AfterInvocationProviderManagerTests extends TestCase {
return returnedObject;
}
public boolean supports(Class clazz) {
public boolean supports(Class<? extends Object> clazz) {
return secureObject.isAssignableFrom(clazz);
}

View File

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

View File

@ -37,12 +37,12 @@ public class BusinessServiceImpl<E extends Entity> implements BusinessService {
return input;
}
public List methodReturningAList(List someList) {
public List<Object> methodReturningAList(List<Object> someList) {
return someList;
}
public List methodReturningAList(String userName, String arg2) {
return new ArrayList();
public List<Object> methodReturningAList(String userName, String arg2) {
return new ArrayList<Object>();
}
public Object[] methodReturningAnArray(Object[] someArray) {

View File

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

View File

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

View File

@ -1,7 +1,7 @@
package org.springframework.security.config;
import static org.junit.Assert.*;
import static org.springframework.security.config.ConfigTestUtils.*;
import static org.springframework.security.config.ConfigTestUtils.AUTH_PROVIDER_XML;
import java.util.ArrayList;
import java.util.List;
@ -11,16 +11,19 @@ import org.junit.Test;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.security.AccessDeniedException;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationCredentialsNotFoundException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.afterinvocation.AfterInvocationProviderManager;
import org.springframework.security.annotation.BusinessService;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.expression.support.MethodExpressionAfterInvocationProvider;
import org.springframework.security.expression.support.MethodExpressionVoter;
import org.springframework.security.providers.TestingAuthenticationToken;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.util.AuthorityUtils;
import org.springframework.security.util.FieldUtils;
import org.springframework.security.util.InMemoryXmlApplicationContext;
import org.springframework.security.vote.AffirmativeBased;
/**
* @author Ben Alex
@ -107,7 +110,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
UserDetailsService service = (UserDetailsService) appContext.getBean("myUserService");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_SOMEOTHERROLE")});
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token);
service.loadUserByUsername("notused");
@ -180,12 +183,25 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_SOMEOTHERROLE")});
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token);
target = (BusinessService) appContext.getBean("businessService");
target.someUserMethod1();
}
// Expression configuration tests
@Test
public void expressionVoterAndAfterInvocationProviderUseSameExpressionHandlerInstance() throws Exception {
setContext("<global-method-security expression-annotations='enabled'/>" + AUTH_PROVIDER_XML);
AffirmativeBased adm = (AffirmativeBased) appContext.getBean(GlobalMethodSecurityBeanDefinitionParser.ACCESS_MANAGER_ID);
List voters = (List) FieldUtils.getFieldValue(adm, "decisionVoters");
MethodExpressionVoter mev = (MethodExpressionVoter) voters.get(0);
AfterInvocationProviderManager pm = (AfterInvocationProviderManager) appContext.getBean(BeanIds.AFTER_INVOCATION_MANAGER);
MethodExpressionAfterInvocationProvider aip = (MethodExpressionAfterInvocationProvider) pm.getProviders().get(0);
assertTrue(FieldUtils.getFieldValue(mev, "expressionHandler") == FieldUtils.getFieldValue(aip, "expressionHandler"));
}
@Test(expected=AccessDeniedException.class)
public void accessIsDeniedForHasRoleExpression() {
setContext(

View File

@ -18,7 +18,7 @@ public class MockAfterInvocationProvider implements AfterInvocationProvider {
return true;
}
public boolean supports(Class clazz) {
public boolean supports(Class<? extends Object> clazz) {
return true;
}

View File

@ -9,34 +9,17 @@ import java.util.Collection;
import java.util.List;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.ConfigAttribute;
import org.springframework.security.annotation.ExpressionProtectedBusinessServiceImpl;
import org.springframework.security.providers.TestingAuthenticationToken;
import org.springframework.security.util.SimpleMethodInvocation;
import org.springframework.security.vote.AccessDecisionVoter;
@SuppressWarnings("unchecked")
public class MethodExpressionVoterTests {
private TestingAuthenticationToken joe = new TestingAuthenticationToken("joe", "joespass", "blah");
private MethodInvocation miListArg;
private MethodInvocation miArrayArg;
private List listArg;
private Object[] arrayArg;
private MethodExpressionVoter am = new MethodExpressionVoter();
@Before
public void setUp() throws Exception {
Method m = ExpressionProtectedBusinessServiceImpl.class.getMethod("methodReturningAList",
String.class, String.class);
m = ExpressionProtectedBusinessServiceImpl.class.getMethod("methodReturningAList", List.class);
listArg = new ArrayList(Arrays.asList("joe", "bob", "sam"));
miListArg = new SimpleMethodInvocation(new Object(), m, new Object[] {listArg});
m = ExpressionProtectedBusinessServiceImpl.class.getMethod("methodReturningAnArray", Object[].class);
arrayArg = new Object[] {"joe", "bob", "sam"};
miArrayArg = new SimpleMethodInvocation(new Object(), m, new Object[] {arrayArg});
}
@Test
public void hasRoleExpressionAllowsUserWithRole() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAnArray());

View File

@ -90,7 +90,7 @@ public class AbstractSecurityInterceptorTests extends TestCase {
private class MockSecurityInterceptorReturnsNull extends AbstractSecurityInterceptor {
private ObjectDefinitionSource objectDefinitionSource;
public Class getSecureObjectClass() {
public Class<? extends Object> getSecureObjectClass() {
return null;
}
@ -106,7 +106,7 @@ public class AbstractSecurityInterceptorTests extends TestCase {
private class MockSecurityInterceptorWhichOnlySupportsStrings extends AbstractSecurityInterceptor {
private ObjectDefinitionSource objectDefinitionSource;
public Class getSecureObjectClass() {
public Class<? extends Object> getSecureObjectClass() {
return String.class;
}

View File

@ -15,25 +15,26 @@
package org.springframework.security.providers;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationServiceException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.MockApplicationEventPublisher;
import org.springframework.security.AccountStatusException;
import org.springframework.security.concurrent.ConcurrentSessionControllerImpl;
import org.springframework.security.concurrent.NullConcurrentSessionController;
import org.springframework.security.concurrent.ConcurrentLoginException;
import org.springframework.security.util.AuthorityUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import org.junit.Test;
import static org.junit.Assert.*;
import org.springframework.security.AccountStatusException;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationServiceException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.MockApplicationEventPublisher;
import org.springframework.security.concurrent.ConcurrentLoginException;
import org.springframework.security.concurrent.ConcurrentSessionControllerImpl;
import org.springframework.security.concurrent.NullConcurrentSessionController;
import org.springframework.security.util.AuthorityUtils;
/**
* Tests {@link ProviderManager}.
@ -48,7 +49,7 @@ public class ProviderManagerTests {
@Test(expected=ProviderNotFoundException.class)
public void authenticationFailsWithUnsupportedToken() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
ProviderManager mgr = makeProviderManager();
mgr.setApplicationEventPublisher(new MockApplicationEventPublisher(true));
@ -108,7 +109,7 @@ public class ProviderManagerTests {
@Test(expected=IllegalArgumentException.class)
public void startupFailsIfProviderListDoesNotContainProviders() throws Exception {
List providers = new Vector();
List<Object> providers = new ArrayList<Object>();
providers.add("THIS_IS_NOT_A_PROVIDER");
ProviderManager mgr = new ProviderManager();
@ -143,7 +144,7 @@ public class ProviderManagerTests {
return authentication;
}
public boolean supports(Class authentication) {
public boolean supports(Class<? extends Object> authentication) {
return true;
}
};
@ -196,7 +197,7 @@ public class ProviderManagerTests {
private ProviderManager makeProviderManager() throws Exception {
MockProvider provider1 = new MockProvider();
List providers = new Vector();
List<AuthenticationProvider> providers = new ArrayList<AuthenticationProvider>();
providers.add(provider1);
ProviderManager mgr = new ProviderManager();
@ -210,7 +211,7 @@ public class ProviderManagerTests {
private ProviderManager makeProviderManagerWithMockProviderWhichReturnsNullInList() {
MockProviderWhichReturnsNull provider1 = new MockProviderWhichReturnsNull();
MockProvider provider2 = new MockProvider();
List providers = new Vector();
List<Object> providers = new ArrayList<Object>();
providers.add(provider1);
providers.add(provider2);
@ -231,7 +232,7 @@ public class ProviderManagerTests {
}
}
public boolean supports(Class authentication) {
public boolean supports(Class<? extends Object> authentication) {
if (TestingAuthenticationToken.class.isAssignableFrom(authentication)) {
return true;
} else {
@ -249,7 +250,7 @@ public class ProviderManagerTests {
}
}
public boolean supports(Class authentication) {
public boolean supports(Class<? extends Object> authentication) {
if (TestingAuthenticationToken.class.isAssignableFrom(authentication)) {
return true;
} else {
@ -263,7 +264,7 @@ public class ProviderManagerTests {
throw new AccountStatusException("xxx") {};
}
public boolean supports(Class authentication) {
public boolean supports(Class<? extends Object> authentication) {
return true;
}
}
@ -273,7 +274,7 @@ public class ProviderManagerTests {
throw new ConcurrentLoginException("xxx") {};
}
public boolean supports(Class authentication) {
public boolean supports(Class<? extends Object> authentication) {
return true;
}
}

View File

@ -41,6 +41,7 @@ import javax.servlet.ServletException;
* @author Ben Alex
* @version $Id$
*/
@SuppressWarnings("unchecked")
public class ChannelDecisionManagerImplTests extends TestCase {
//~ Methods ========================================================================================================

View File

@ -15,43 +15,39 @@
package org.springframework.security.ui.basicauth;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.security.matcher.AuthenticationMatcher.anAuthenticationWithUsernameAndPassword;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import org.apache.commons.codec.binary.Base64;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.MockAuthenticationEntryPoint;
import org.springframework.security.MockAuthenticationManager;
import org.springframework.security.MockFilterConfig;
import org.springframework.security.MockApplicationEventPublisher;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.ProviderManager;
import org.springframework.security.providers.dao.DaoAuthenticationProvider;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.memory.InMemoryDaoImpl;
import org.springframework.security.userdetails.memory.UserMap;
import org.springframework.security.userdetails.memory.UserMapEditor;
import org.apache.commons.codec.binary.Base64;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.MockAuthenticationEntryPoint;
import org.springframework.security.MockAuthenticationManager;
import org.springframework.security.MockFilterConfig;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.TestingAuthenticationToken;
/**
@ -64,6 +60,7 @@ public class BasicProcessingFilterTests {
//~ Instance fields ================================================================================================
private BasicProcessingFilter filter;
private Mockery jmock = new JUnit4Mockery();
//~ Methods ========================================================================================================
@ -89,19 +86,14 @@ public class BasicProcessingFilterTests {
public void setUp() throws Exception {
SecurityContextHolder.clearContext();
// Create User Details Service, provider and authentication manager
InMemoryDaoImpl dao = new InMemoryDaoImpl();
UserMapEditor editor = new UserMapEditor();
editor.setAsText("rod=koala,ROLE_ONE,ROLE_TWO,enabled\r\n");
dao.setUserMap((UserMap) editor.getValue());
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(dao);
ProviderManager manager = new ProviderManager();
manager.setProviders(Arrays.asList(new Object[] {provider}));
manager.setApplicationEventPublisher(new MockApplicationEventPublisher());
manager.afterPropertiesSet();
final AuthenticationManager manager = jmock.mock(AuthenticationManager.class);
final Authentication rod = new TestingAuthenticationToken("rod", "koala", "ROLE_1");
jmock.checking(new Expectations() {{
allowing(manager).authenticate(with(anAuthenticationWithUsernameAndPassword("rod", "koala")));
will(returnValue(rod));
allowing(manager).authenticate(with(any(Authentication.class)));
will(throwException(new BadCredentialsException("")));
}});
filter = new BasicProcessingFilter();
filter.setAuthenticationManager(manager);
@ -164,8 +156,8 @@ public class BasicProcessingFilterTests {
executeFilterInContainerSimulator(filter, request, true);
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
assertEquals("rod",
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
assertEquals("rod", SecurityContextHolder.getContext().getAuthentication().getName());
}
@Test
@ -193,16 +185,11 @@ public class BasicProcessingFilterTests {
}
}
@Test
@Test(expected=IllegalArgumentException.class)
public void testStartupDetectsMissingAuthenticationManager() throws Exception {
try {
BasicProcessingFilter filter = new BasicProcessingFilter();
filter.setAuthenticationEntryPoint(new MockAuthenticationEntryPoint("x"));
filter.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("An AuthenticationManager is required", expected.getMessage());
}
BasicProcessingFilter filter = new BasicProcessingFilter();
filter.setAuthenticationEntryPoint(new MockAuthenticationEntryPoint("x"));
filter.afterPropertiesSet();
}
@Test
@ -218,8 +205,7 @@ public class BasicProcessingFilterTests {
executeFilterInContainerSimulator(filter, request, true);
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
assertEquals("rod",
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
assertEquals("rod", SecurityContextHolder.getContext().getAuthentication().getName());
// NOW PERFORM FAILED AUTHENTICATION
// Setup our HTTP request
@ -249,7 +235,7 @@ public class BasicProcessingFilterTests {
assertTrue(filter.isIgnoreFailure());
// Test - the filter chain will be invoked, as we've set ignoreFailure = true
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, true);
executeFilterInContainerSimulator(filter, request, true);
assertNull(SecurityContextHolder.getContext().getAuthentication());
}

View File

@ -32,27 +32,11 @@ import java.util.Vector;
* @author Ben Alex
* @version $Id$
*/
@SuppressWarnings("unchecked")
public class AbstractAccessDecisionManagerTests extends TestCase {
//~ Constructors ===================================================================================================
public AbstractAccessDecisionManagerTests() {
super();
}
public AbstractAccessDecisionManagerTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AbstractAccessDecisionManagerTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAllowIfAccessDecisionManagerDefaults()
throws Exception {
MockDecisionManagerImpl mock = new MockDecisionManagerImpl();
@ -168,7 +152,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
}
private class MockStringOnlyVoter implements AccessDecisionVoter {
public boolean supports(Class clazz) {
public boolean supports(Class<? extends Object> clazz) {
if (String.class.isAssignableFrom(clazz)) {
return true;
} else {

View File

@ -41,7 +41,7 @@ public class AffirmativeBasedTests {
RoleVoter roleVoter = new RoleVoter();
DenyVoter denyForSureVoter = new DenyVoter();
DenyAgainVoter denyAgainForSureVoter = new DenyAgainVoter();
List voters = new ArrayList();
List<AccessDecisionVoter> voters = new ArrayList<AccessDecisionVoter>();
voters.add(roleVoter);
voters.add(denyForSureVoter);
voters.add(denyAgainForSureVoter);

View File

@ -47,7 +47,7 @@ public class DenyAgainVoter implements AccessDecisionVoter {
}
}
public boolean supports(Class clazz) {
public boolean supports(Class<? extends Object> clazz) {
return true;
}

View File

@ -41,7 +41,7 @@ public class DenyVoter implements AccessDecisionVoter {
}
}
public boolean supports(Class clazz) {
public boolean supports(Class<? extends Object> clazz) {
return true;
}

View File

@ -99,7 +99,7 @@ public class OpenIDAuthenticationProvider implements AuthenticationProvider, Ini
/* (non-Javadoc)
* @see org.springframework.security.providers.AuthenticationProvider#supports(java.lang.Class)
*/
public boolean supports(Class authentication) {
public boolean supports(Class<? extends Object> authentication) {
return OpenIDAuthenticationToken.class.isAssignableFrom(authentication);
}
}

View File

@ -65,8 +65,7 @@ public class AddPermissionController extends SimpleFormController implements Ini
return showForm(request, response, errors);
}
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
protected Object formBackingObject(HttpServletRequest request) throws Exception {
int contactId = ServletRequestUtils.getRequiredIntParameter(request, "contactId");
Contact contact = contactManager.getById(new Long(contactId));
@ -77,13 +76,12 @@ public class AddPermissionController extends SimpleFormController implements Ini
return addPermission;
}
protected ModelAndView handleInvalidSubmit(HttpServletRequest request, HttpServletResponse response)
throws Exception {
protected ModelAndView handleInvalidSubmit(HttpServletRequest request, HttpServletResponse response) throws Exception {
return disallowDuplicateFormSubmission(request, response);
}
private Map listPermissions(HttpServletRequest request) {
Map map = new LinkedHashMap();
private Map<Integer, String> listPermissions(HttpServletRequest request) {
Map<Integer, String> map = new LinkedHashMap<Integer, String>();
map.put(new Integer(BasePermission.ADMINISTRATION.getMask()),
getApplicationContext().getMessage("select.administer", null, "Administer", request.getLocale()));
map.put(new Integer(BasePermission.READ.getMask()),
@ -94,15 +92,12 @@ public class AddPermissionController extends SimpleFormController implements Ini
return map;
}
private Map listRecipients(HttpServletRequest request) {
Map map = new LinkedHashMap();
private Map<String, String> listRecipients(HttpServletRequest request) {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("",
getApplicationContext().getMessage("select.pleaseSelect", null, "-- please select --", request.getLocale()));
Iterator recipientsIter = contactManager.getAllRecipients().iterator();
while (recipientsIter.hasNext()) {
String recipient = (String) recipientsIter.next();
for (String recipient : contactManager.getAllRecipients()) {
map.put(recipient, recipient);
}
@ -128,9 +123,10 @@ public class AddPermissionController extends SimpleFormController implements Ini
return new ModelAndView(new RedirectView(getSuccessView()));
}
protected Map referenceData(HttpServletRequest request)
throws Exception {
Map model = new HashMap();
@Override
@SuppressWarnings("unchecked")
protected Map referenceData(HttpServletRequest request) throws Exception {
Map model = new HashMap(2);
model.put("recipients", listRecipients(request));
model.put("permissions", listPermissions(request));

View File

@ -31,11 +31,11 @@ public interface ContactDao {
public void delete(Long contactId);
public List findAll();
public List<Contact> findAll();
public List findAllPrincipals();
public List<String> findAllPrincipals();
public List findAllRoles();
public List<String> findAllRoles();
public Contact getById(Long id);

View File

@ -57,15 +57,15 @@ public class ContactDaoSpring extends JdbcDaoSupport implements ContactDao {
contactDelete.delete(contactId);
}
public List findAll() {
public List<Contact> findAll() {
return contactsAllQuery.execute();
}
public List findAllPrincipals() {
public List<String> findAllPrincipals() {
return principalsAllQuery.execute();
}
public List findAllRoles() {
public List<String> findAllRoles() {
return rolesAllQuery.execute();
}

View File

@ -44,10 +44,10 @@ public interface ContactManager {
@PreAuthorize("hasRole('ROLE_USER')")
@PostFilter("hasPermission(filterObject, 'read') or hasPermission(filterObject, admin)")
public List getAll();
public List<Contact> getAll();
@PreAuthorize("hasRole('ROLE_USER')")
public List getAllRecipients();
public List<String> getAllRecipients();
@PreAuthorize(
"hasPermission(#id, 'sample.contact.Contact', read) or " +

View File

@ -127,7 +127,7 @@ public class ContactManagerBackend extends ApplicationObjectSupport implements C
}
@Transactional(readOnly=true)
public List getAll() {
public List<Contact> getAll() {
if (logger.isDebugEnabled()) {
logger.debug("Returning all contacts");
}
@ -136,12 +136,12 @@ public class ContactManagerBackend extends ApplicationObjectSupport implements C
}
@Transactional(readOnly=true)
public List getAllRecipients() {
public List<String> getAllRecipients() {
if (logger.isDebugEnabled()) {
logger.debug("Returning all recipients");
}
List list = contactDao.findAllPrincipals();
List<String> list = contactDao.findAllPrincipals();
return list;
}
@ -158,7 +158,7 @@ public class ContactManagerBackend extends ApplicationObjectSupport implements C
/**
* This is a public method.
*/
@Transactional(readOnly=true)
@Transactional(readOnly=true)
public Contact getRandomContact() {
if (logger.isDebugEnabled()) {
logger.debug("Returning random contact");

View File

@ -12,10 +12,10 @@ import org.springframework.util.Assert;
*
*/
public abstract class AbstractElement {
/** The name of this token (ie filename or directory segment name */
/** The name of this token (a filename or directory segment name */
private String name;
/** The parent of this token (ie directory, or null if referring to root) */
/** The parent of this token (a directory, or null if referring to root) */
private AbstractElement parent;
/** The database identifier for this object (null if not persisted) */
@ -63,7 +63,7 @@ public abstract class AbstractElement {
* @return the fully-qualified name of this element, including any parents
*/
public String getFullName() {
List strings = new ArrayList();
List<String> strings = new ArrayList<String>();
AbstractElement currentElement = this;
while (currentElement != null) {
strings.add(0, currentElement.getName());
@ -72,8 +72,8 @@ public abstract class AbstractElement {
StringBuffer sb = new StringBuffer();
String lastCharacter = null;
for (Iterator i = strings.iterator(); i.hasNext();) {
String token = (String) i.next();
for (Iterator<String> i = strings.iterator(); i.hasNext();) {
String token = i.next();
if (!"/".equals(lastCharacter) && lastCharacter != null) {
sb.append("/");
}