1
0
mirror of synced 2026-08-05 01:36:56 +00:00

IDEA inspection refactorings.

This commit is contained in:
Luke Taylor
2010-08-05 22:47:42 +01:00
parent a3d27a9863
commit 85c4c91e0e
175 changed files with 428 additions and 551 deletions
@@ -29,7 +29,7 @@ import org.springframework.util.StringUtils;
public class SecurityConfig implements ConfigAttribute {
//~ Instance fields ================================================================================================
private String attrib;
private final String attrib;
//~ Constructors ===================================================================================================
@@ -62,15 +62,15 @@ public class SecurityConfig implements ConfigAttribute {
return this.attrib;
}
public final static List<ConfigAttribute> createListFromCommaDelimitedString(String access) {
public static List<ConfigAttribute> createListFromCommaDelimitedString(String access) {
return createList(StringUtils.commaDelimitedListToStringArray(access));
}
public final static List<ConfigAttribute> createSingleAttributeList(String access) {
public static List<ConfigAttribute> createSingleAttributeList(String access) {
return createList(access);
}
public final static List<ConfigAttribute> createList(String... attributeNames) {
public static List<ConfigAttribute> createList(String... attributeNames) {
Assert.notNull(attributeNames, "You must supply an array of attribute names");
List<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>(attributeNames.length);
@@ -8,7 +8,7 @@ import org.springframework.expression.TypedValue;
@SuppressWarnings("unchecked")
public final class SecurityExpressionRootPropertyAccessor implements PropertyAccessor {
public Class[] CLASSES = {SecurityExpressionRoot.class};
public final Class[] CLASSES = {SecurityExpressionRoot.class};
public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException {
ApplicationContext ctx = ((SecurityExpressionRoot)target).getApplicationContext();
@@ -44,7 +44,7 @@ public class DefaultMethodSecurityExpressionHandler implements MethodSecurityExp
private PermissionCacheOptimizer permissionCacheOptimizer = null;
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
private final SecurityExpressionRootPropertyAccessor sxrpa = new SecurityExpressionRootPropertyAccessor();
private ExpressionParser expressionParser = new SpelExpressionParser();
private final ExpressionParser expressionParser = new SpelExpressionParser();
private RoleHierarchy roleHierarchy;
private ApplicationContext applicationContext;
@@ -127,11 +127,11 @@ public class DefaultMethodSecurityExpressionHandler implements MethodSecurityExp
permissionCacheOptimizer.cachePermissionsFor(rootObject.getAuthentication(), Arrays.asList(array));
}
for (int i = 0; i < array.length; i++) {
rootObject.setFilterObject(array[i]);
for (Object o : array) {
rootObject.setFilterObject(o);
if (ExpressionUtils.evaluateAsBoolean(filterExpression, ctx)) {
retainList.add(array[i]);
retainList.add(o);
}
}
@@ -22,7 +22,7 @@ import org.springframework.security.access.prepost.PrePostInvocationAttributeFac
* @since 3.0
*/
public class ExpressionBasedAnnotationAttributeFactory implements PrePostInvocationAttributeFactory {
private ExpressionParser parser;
private final ExpressionParser parser;
public ExpressionBasedAnnotationAttributeFactory(MethodSecurityExpressionHandler handler) {
parser = handler.getExpressionParser();
@@ -19,7 +19,7 @@ import org.springframework.security.core.Authentication;
public class ExpressionBasedPostInvocationAdvice implements PostInvocationAuthorizationAdvice{
protected final Log logger = LogFactory.getLog(getClass());
private MethodSecurityExpressionHandler expressionHandler;
private final MethodSecurityExpressionHandler expressionHandler;
public ExpressionBasedPostInvocationAdvice(MethodSecurityExpressionHandler expressionHandler) {
this.expressionHandler = expressionHandler;
@@ -23,7 +23,7 @@ import org.springframework.security.core.Authentication;
* @since 3.0
*/
class MethodSecurityEvaluationContext extends StandardEvaluationContext {
private static Log logger = LogFactory.getLog(MethodSecurityEvaluationContext.class);
private static final Log logger = LogFactory.getLog(MethodSecurityEvaluationContext.class);
private ParameterNameDiscoverer parameterNameDiscoverer;
private final MethodInvocation mi;
@@ -93,7 +93,7 @@ class MethodSecurityEvaluationContext extends StandardEvaluationContext {
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(targetObject);
if (targetClass == null) {
// TODO: Spring should do this, but there's a bug in ultimateTargetClass() which returns null
// TODO: Spring should do this, but there's a bug in ultimateTargetClass() which returns null
targetClass = targetObject.getClass();
}
@@ -135,9 +135,7 @@ public class RoleHierarchyImpl implements RoleHierarchy {
private void addReachableRoles(Set<GrantedAuthority> reachableRoles,
GrantedAuthority authority) {
Iterator<GrantedAuthority> iterator = reachableRoles.iterator();
while (iterator.hasNext()) {
GrantedAuthority testAuthority = iterator.next();
for (GrantedAuthority testAuthority : reachableRoles) {
String testKey = testAuthority.getAuthority();
if ((testKey != null) && (testKey.equals(authority.getAuthority()))) {
return;
@@ -154,9 +152,7 @@ public class RoleHierarchyImpl implements RoleHierarchy {
return null;
}
Iterator<GrantedAuthority> iterator = rolesReachableInOneOrMoreStepsMap.keySet().iterator();
while (iterator.hasNext()) {
GrantedAuthority testAuthority = iterator.next();
for (GrantedAuthority testAuthority : rolesReachableInOneOrMoreStepsMap.keySet()) {
String testKey = testAuthority.getAuthority();
if ((testKey != null) && (testKey.equals(authority.getAuthority()))) {
return rolesReachableInOneOrMoreStepsMap.get(testAuthority);
@@ -171,7 +167,7 @@ public class RoleHierarchyImpl implements RoleHierarchy {
* references a set of the reachable lower roles.
*/
private void buildRolesReachableInOneStepMap() {
Pattern pattern = Pattern.compile("(\\s*([^\\s>]+)\\s*\\>\\s*([^\\s>]+))");
Pattern pattern = Pattern.compile("(\\s*([^\\s>]+)\\s*>\\s*([^\\s>]+))");
Matcher roleHierarchyMatcher = pattern.matcher(roleHierarchyStringRepresentation);
rolesReachableInOneStepMap = new HashMap<GrantedAuthority, Set<GrantedAuthority>>();
@@ -179,7 +175,7 @@ public class RoleHierarchyImpl implements RoleHierarchy {
while (roleHierarchyMatcher.find()) {
GrantedAuthority higherRole = new GrantedAuthorityImpl(roleHierarchyMatcher.group(2));
GrantedAuthority lowerRole = new GrantedAuthorityImpl(roleHierarchyMatcher.group(3));
Set<GrantedAuthority> rolesReachableInOneStepSet = null;
Set<GrantedAuthority> rolesReachableInOneStepSet;
if (!rolesReachableInOneStepMap.containsKey(higherRole)) {
rolesReachableInOneStepSet = new HashSet<GrantedAuthority>();
@@ -33,10 +33,10 @@ import org.springframework.security.core.Authentication;
public class InterceptorStatusToken {
//~ Instance fields ================================================================================================
private Authentication authentication;
private Collection<ConfigAttribute> attr;
private Object secureObject;
private boolean contextHolderRefreshRequired;
private final Authentication authentication;
private final Collection<ConfigAttribute> attr;
private final Object secureObject;
private final boolean contextHolderRefreshRequired;
//~ Constructors ===================================================================================================
@@ -74,11 +74,7 @@ public class RunAsImplAuthenticationProvider implements InitializingBean, Authen
this.messages = new MessageSourceAccessor(messageSource);
}
public boolean supports(Class<? extends Object> authentication) {
if (RunAsUserToken.class.isAssignableFrom(authentication)) {
return true;
} else {
return false;
}
public boolean supports(Class<?> authentication) {
return RunAsUserToken.class.isAssignableFrom(authentication);
}
}
@@ -42,7 +42,7 @@ public class MethodSecurityInterceptor extends AbstractSecurityInterceptor imple
//~ Methods ========================================================================================================
public Class<? extends Object> getSecureObjectClass() {
public Class<?> getSecureObjectClass() {
return MethodInvocation.class;
}
@@ -54,8 +54,8 @@ public class MethodSecurityMetadataSourceAdvisor extends AbstractPointcutAdvisor
private transient MethodSecurityInterceptor interceptor;
private final Pointcut pointcut = new MethodSecurityMetadataSourcePointcut();
private BeanFactory beanFactory;
private String adviceBeanName;
private String metadataSourceBeanName;
private final String adviceBeanName;
private final String metadataSourceBeanName;
private transient volatile Object adviceMonitor = new Object();
//~ Constructors ===================================================================================================
@@ -25,7 +25,7 @@ public class AspectJAnnotationSecurityInterceptor extends AbstractSecurityInterc
return this.securityMetadataSource;
}
public Class<? extends Object> getSecureObjectClass() {
public Class<?> getSecureObjectClass() {
return JoinPoint.class;
}
@@ -47,7 +47,7 @@ public class AspectJSecurityInterceptor extends AbstractSecurityInterceptor {
//~ Methods ========================================================================================================
public Class<? extends Object> getSecureObjectClass() {
public Class<?> getSecureObjectClass() {
return JoinPoint.class;
}
@@ -48,10 +48,10 @@ public class MapBasedMethodSecurityMetadataSource extends AbstractFallbackMethod
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
/** Map from RegisteredMethod to ConfigAttribute list */
protected Map<RegisteredMethod, List<ConfigAttribute>> methodMap = new HashMap<RegisteredMethod, List<ConfigAttribute>>();
protected final Map<RegisteredMethod, List<ConfigAttribute>> methodMap = new HashMap<RegisteredMethod, List<ConfigAttribute>>();
/** Map from RegisteredMethod to name pattern used for registration */
private Map<RegisteredMethod, String> nameMap = new HashMap<RegisteredMethod, String>();
private final Map<RegisteredMethod, String> nameMap = new HashMap<RegisteredMethod, String>();
//~ Methods ========================================================================================================
@@ -139,9 +139,9 @@ public class MapBasedMethodSecurityMetadataSource extends AbstractFallbackMethod
Method[] methods = javaType.getMethods();
List<Method> matchingMethods = new ArrayList<Method>();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(mappedName) || isMatch(methods[i].getName(), mappedName)) {
matchingMethods.add(methods[i]);
for (Method m : methods) {
if (m.getName().equals(mappedName) || isMatch(m.getName(), mappedName)) {
matchingMethods.add(m);
}
}
@@ -252,8 +252,8 @@ public class MapBasedMethodSecurityMetadataSource extends AbstractFallbackMethod
* Class will be the Class we're invoking against and the Method will provide details of the declared class.
*/
private class RegisteredMethod {
private Method method;
private Class<?> registeredJavaType;
private final Method method;
private final Class<?> registeredJavaType;
public RegisteredMethod(Method method, Class<?> registeredJavaType) {
Assert.notNull(method, "Method required");
@@ -20,7 +20,7 @@ import org.springframework.security.core.Authentication;
public class PostInvocationAdviceProvider implements AfterInvocationProvider {
protected final Log logger = LogFactory.getLog(getClass());
private PostInvocationAuthorizationAdvice postAdvice;
private final PostInvocationAuthorizationAdvice postAdvice;
public PostInvocationAdviceProvider(PostInvocationAuthorizationAdvice postAdvice) {
this.postAdvice = postAdvice;
@@ -24,7 +24,7 @@ import org.springframework.security.core.Authentication;
public class PreInvocationAuthorizationAdviceVoter implements AccessDecisionVoter {
protected final Log logger = LogFactory.getLog(getClass());
private PreInvocationAuthorizationAdvice preAdvice;
private final PreInvocationAuthorizationAdvice preAdvice;
public PreInvocationAuthorizationAdviceVoter(PreInvocationAuthorizationAdvice pre) {
this.preAdvice = pre;
@@ -95,11 +95,7 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan
}
public boolean supports(ConfigAttribute attribute) {
Iterator<AccessDecisionVoter> iter = this.decisionVoters.iterator();
while (iter.hasNext()) {
AccessDecisionVoter voter = iter.next();
for (AccessDecisionVoter voter : this.decisionVoters) {
if (voter.supports(attribute)) {
return true;
}
@@ -118,11 +114,7 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan
* @return true if this type is supported
*/
public boolean supports(Class<?> clazz) {
Iterator<AccessDecisionVoter> iter = this.decisionVoters.iterator();
while (iter.hasNext()) {
AccessDecisionVoter voter = iter.next();
for (AccessDecisionVoter voter : this.decisionVoters) {
if (!voter.supports(clazz)) {
return false;
}
@@ -80,12 +80,6 @@ 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) {
if (MethodInvocation.class.isAssignableFrom(clazz)) {
return true;
} else if (JoinPoint.class.isAssignableFrom(clazz)) {
return true;
} else {
return false;
}
return (MethodInvocation.class.isAssignableFrom(clazz) || JoinPoint.class.isAssignableFrom(clazz));
}
}
@@ -10,7 +10,7 @@ import org.springframework.context.support.MessageSourceAccessor;
*/
public class AccountStatusUserDetailsChecker implements UserDetailsChecker {
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
protected final MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
public void check(UserDetails user) {
if (!user.isAccountNonLocked()) {
@@ -73,7 +73,7 @@ public class AnonymousAuthenticationProvider implements AuthenticationProvider,
this.messages = new MessageSourceAccessor(messageSource);
}
public boolean supports(Class<? extends Object> authentication) {
public boolean supports(Class<?> authentication) {
return (AnonymousAuthenticationToken.class.isAssignableFrom(authentication));
}
}
@@ -11,7 +11,7 @@ import java.io.Serializable;
public class AuthenticationDetails implements Serializable {
//~ Instance fields ================================================================================================
private String context;
private final String context;
//~ Constructors ===================================================================================================
@@ -50,10 +50,10 @@ public class AuthenticationDetailsSourceImpl implements AuthenticationDetailsSou
private Constructor<?> getFirstMatchingConstructor(Object object) throws NoSuchMethodException {
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
Constructor<?> constructor = null;
for (int i = 0; i < constructors.length; i++) {
Class<?>[] parameterTypes = constructors[i].getParameterTypes();
for (Constructor<?> tryMe : constructors) {
Class<?>[] parameterTypes = tryMe.getParameterTypes();
if (parameterTypes.length == 1 && (object == null || parameterTypes[0].isInstance(object))) {
constructor = constructors[i];
constructor = tryMe;
break;
}
}
@@ -62,5 +62,5 @@ public interface AuthenticationProvider {
* @return <code>true</code> if the implementation can more closely evaluate the <code>Authentication</code> class
* presented
*/
boolean supports(Class<? extends Object> authentication);
boolean supports(Class<?> authentication);
}
@@ -23,9 +23,8 @@ import org.springframework.security.core.AuthenticationException;
* <p>
* {@link org.springframework.security.access.AccessDecisionVoter}s will typically throw this exception if
* they are dissatisfied with the level of the authentication, such as if performed using a remember-me mechanism or
* anonymously. The commonly used {@link org.springframework.security.web.access.ExceptionTranslationFilter
* ExceptionTranslationFilter} will thus cause the <code>AuthenticationEntryPoint</code> to be called, allowing
* the principal to authenticate with a stronger level of authentication.
* anonymously. The {@code ExceptionTranslationFilter} will then typically cause the {@code AuthenticationEntryPoint}
* to be called, allowing the principal to authenticate with a stronger level of authentication.
*
* @author Ben Alex
*/
@@ -69,7 +69,7 @@ public class RememberMeAuthenticationProvider implements AuthenticationProvider,
this.messages = new MessageSourceAccessor(messageSource);
}
public boolean supports(Class<? extends Object> authentication) {
public boolean supports(Class<?> authentication) {
return (RememberMeAuthenticationToken.class.isAssignableFrom(authentication));
}
}
@@ -36,7 +36,7 @@ public class TestingAuthenticationProvider implements AuthenticationProvider {
return authentication;
}
public boolean supports(Class<? extends Object> authentication) {
public boolean supports(Class<?> authentication) {
return TestingAuthenticationToken.class.isAssignableFrom(authentication);
}
}
@@ -33,8 +33,8 @@ public class TestingAuthenticationToken extends AbstractAuthenticationToken {
//~ Instance fields ================================================================================================
private static final long serialVersionUID = 1L;
private Object credentials;
private Object principal;
private final Object credentials;
private final Object principal;
//~ Constructors ===================================================================================================
@@ -262,7 +262,7 @@ public abstract class AbstractUserDetailsAuthenticationProvider implements Authe
this.userCache = userCache;
}
public boolean supports(Class<? extends Object> authentication) {
public boolean supports(Class<?> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
@@ -66,7 +66,7 @@ public class ReflectionSaltSource implements SaltSource, InitializingBean {
Method saltMethod = findSaltMethod(user);
try {
return saltMethod.invoke(user, new Object[] {});
return saltMethod.invoke(user);
} catch (Exception exception) {
throw new AuthenticationServiceException(exception.getMessage(), exception);
}
@@ -25,8 +25,8 @@ class Md4 {
private final byte[] buffer = new byte[BLOCK_SIZE];
private int bufferOffset;
private long byteCount;
private int[] state = new int[4];
private int[] tmp = new int[16];
private final int[] state = new int[4];
private final int[] tmp = new int[16];
Md4() {
reset();
@@ -29,7 +29,7 @@ import org.springframework.util.Assert;
public abstract class AbstractAuthenticationFailureEvent extends AbstractAuthenticationEvent {
//~ Instance fields ================================================================================================
private AuthenticationException exception;
private final AuthenticationException exception;
//~ Constructors ===================================================================================================
@@ -29,7 +29,7 @@ import org.springframework.util.Assert;
public class InteractiveAuthenticationSuccessEvent extends AbstractAuthenticationEvent {
//~ Instance fields ================================================================================================
private Class<?> generatedBy;
private final Class<?> generatedBy;
//~ Constructors ===================================================================================================
@@ -191,8 +191,7 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli
Set<Principal> principals = loginContext.getSubject().getPrincipals();
for (Principal principal : principals) {
for (int i = 0; i < authorityGranters.length; i++) {
AuthorityGranter granter = authorityGranters[i];
for (AuthorityGranter granter : authorityGranters) {
Set<String> roles = granter.grant(principal);
// If the granter doesn't wish to grant any authorities, it should return null.
@@ -249,7 +248,7 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli
int n = 1;
final String prefix = "login.config.url.";
String existing = null;
String existing;
while ((existing = Security.getProperty(prefix + n)) != null) {
alreadySet = existing.equals(loginConfigUrl);
@@ -270,7 +269,7 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli
private String convertLoginConfigToUrl() throws IOException {
String loginConfigPath = loginConfig.getFile().getAbsolutePath();
loginConfigPath.replace(File.separatorChar, '/');
loginConfigPath = loginConfigPath.replace(File.separatorChar, '/');
if (!loginConfigPath.startsWith("/")) {
loginConfigPath = "/" + loginConfigPath;
@@ -436,7 +435,7 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli
this.refreshConfigurationOnStartup = refresh;
}
public boolean supports(Class<? extends Object> aClass) {
public boolean supports(Class<?> aClass) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass);
}
@@ -454,19 +453,15 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli
* Wrapper class for JAASAuthenticationCallbackHandlers
*/
private class InternalCallbackHandler implements CallbackHandler {
private Authentication authentication;
private final Authentication authentication;
public InternalCallbackHandler(Authentication authentication) {
this.authentication = authentication;
}
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbackHandlers.length; i++) {
JaasAuthenticationCallbackHandler handler = callbackHandlers[i];
for (int j = 0; j < callbacks.length; j++) {
Callback callback = callbacks[j];
for (JaasAuthenticationCallbackHandler handler : callbackHandlers) {
for (Callback callback : callbacks) {
handler.handle(callback, authentication);
}
}
@@ -32,7 +32,7 @@ public class JaasGrantedAuthority extends GrantedAuthorityImpl {
//~ Instance fields ================================================================================================
private static final long serialVersionUID = 1L;
private Principal principal;
private final Principal principal;
//~ Constructors ===================================================================================================
@@ -54,7 +54,7 @@ public class JaasNameCallbackHandler implements JaasAuthenticationCallbackHandle
throws IOException, UnsupportedCallbackException {
if (callback instanceof NameCallback) {
NameCallback ncb = (NameCallback) callback;
String username = "";
String username;
Object principal = authentication.getPrincipal();
@@ -26,7 +26,7 @@ import org.springframework.security.core.Authentication;
public class JaasAuthenticationFailedEvent extends JaasAuthenticationEvent {
//~ Instance fields ================================================================================================
private Exception exception;
private final Exception exception;
//~ Constructors ===================================================================================================
@@ -49,9 +49,7 @@ public class RemoteAuthenticationManagerImpl implements RemoteAuthenticationMana
UsernamePasswordAuthenticationToken request = new UsernamePasswordAuthenticationToken(username, password);
try {
Collection<GrantedAuthority> authorities = authenticationManager.authenticate(request).getAuthorities();
return authorities;
return authenticationManager.authenticate(request).getAuthorities();
} catch (AuthenticationException authEx) {
throw new RemoteAuthenticationException(authEx.getMessage());
}
@@ -71,7 +71,7 @@ public class RemoteAuthenticationProvider implements AuthenticationProvider, Ini
this.remoteAuthenticationManager = remoteAuthenticationManager;
}
public boolean supports(Class<? extends Object> authentication) {
public boolean supports(Class<?> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
}
@@ -48,8 +48,8 @@ public abstract class AuthorityUtils {
public static List<GrantedAuthority> createAuthorityList(String... roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(roles.length);
for (int i=0; i < roles.length; i++) {
authorities.add(new GrantedAuthorityImpl(roles[i]));
for (String role : roles) {
authorities.add(new GrantedAuthorityImpl(role));
}
return authorities;
@@ -37,7 +37,7 @@ public class GrantedAuthorityImpl implements GrantedAuthority, Serializable {
//~ Instance fields ================================================================================================
private static final long serialVersionUID = 1L;
private String role;
private final String role;
//~ Constructors ===================================================================================================
@@ -127,8 +127,8 @@ public class MapBasedAttributes2GrantedAuthoritiesMapper implements Attributes2G
}
private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, Object[] value) {
for ( int i = 0 ; i < value.length ; i++ ) {
addGrantedAuthorityCollection(result,value[i]);
for (Object aValue : value) {
addGrantedAuthorityCollection(result, aValue);
}
}
@@ -266,7 +266,7 @@ public final class Base64 {
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private final static byte[] getAlphabet( int options ) {
private static byte[] getAlphabet( int options ) {
if ((options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_ALPHABET;
} else if ((options & ORDERED) == ORDERED) {
@@ -283,7 +283,7 @@ public final class Base64 {
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private final static byte[] getDecodabet( int options ) {
private static byte[] getDecodabet( int options ) {
if( (options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_DECODABET;
} else if ((options & ORDERED) == ORDERED) {
@@ -600,11 +600,10 @@ public final class Base64 {
byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space
int b4Posn = 0; // Keep track of four byte input buffer
int i = 0; // Source array counter
byte sbiCrop = 0; // Low seven bits (ASCII) of input
byte sbiDecode = 0; // Special value from DECODABET
byte sbiCrop; // Low seven bits (ASCII) of input
byte sbiDecode; // Special value from DECODABET
for( i = off; i < off+len; i++ ) { // Loop through source
for(int i = off; i < off+len; i++ ) { // Loop through source
sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
sbiDecode = DECODABET[ sbiCrop ]; // Special value
@@ -25,7 +25,6 @@ import org.springframework.util.Assert;
* @author Ben Alex
*
* @see java.lang.ThreadLocal
* @see org.springframework.security.core.context.web.SecurityContextPersistenceFilter
*/
final class InheritableThreadLocalSecurityContextHolderStrategy implements SecurityContextHolderStrategy {
//~ Static fields/initializers =====================================================================================
@@ -38,8 +38,8 @@ public class SessionInformation implements Serializable {
//~ Instance fields ================================================================================================
private Date lastRequest;
private Object principal;
private String sessionId;
private final Object principal;
private final String sessionId;
private boolean expired = false;
//~ Constructors ===================================================================================================
@@ -11,9 +11,9 @@ import org.springframework.util.Assert;
* @since 2.0.1
*/
public class DefaultToken implements Token {
private String key;
private long keyCreationTime;
private String extendedInformation;
private final String key;
private final long keyCreationTime;
private final String extendedInformation;
public DefaultToken(String key, long keyCreationTime, String extendedInformation) {
Assert.hasText(key, "Key required");
@@ -52,7 +52,7 @@ public class DefaultToken implements Token {
}
public String toString() {
return "DefaultToken[key=" + new String(key) + "; creation=" + new Date(keyCreationTime) + "; extended=" + extendedInformation + "]";
return "DefaultToken[key=" + key + "; creation=" + new Date(keyCreationTime) + "; extended=" + extendedInformation + "]";
}
@@ -63,7 +63,7 @@ public class KeyBasedPersistenceTokenService implements TokenService, Initializi
long creationTime = new Date().getTime();
String serverSecret = computeServerSecretApplicableAt(creationTime);
String pseudoRandomNumber = generatePseudoRandomNumber();
String content = new Long(creationTime).toString() + ":" + pseudoRandomNumber + ":" + extendedInformation;
String content = Long.toString(creationTime) + ":" + pseudoRandomNumber + ":" + extendedInformation;
// Compute key
String sha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret);
@@ -102,7 +102,7 @@ public class KeyBasedPersistenceTokenService implements TokenService, Initializi
String sha1Hex = tokens[tokens.length-1];
// Verification
String content = new Long(creationTime).toString() + ":" + pseudoRandomNumber + ":" + extendedInfo.toString();
String content = Long.toString(creationTime) + ":" + pseudoRandomNumber + ":" + extendedInfo.toString();
String expectedSha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret);
Assert.isTrue(expectedSha512Hex.equals(sha1Hex), "Key verification failure");
@@ -17,29 +17,19 @@ import org.springframework.security.core.codec.Hex;
*
*/
public abstract class Sha512DigestUtils {
/**
* Returns a MessageDigest for the given <code>algorithm</code>.
*
* @param algorithm The MessageDigest algorithm name.
* @return An MD5 digest instance.
* @throws RuntimeException when a {@link java.security.NoSuchAlgorithmException} is caught,
*/
static MessageDigest getDigest(String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* Returns an SHA digest.
*
* @return An SHA digest instance.
* @throws RuntimeException when a {@link java.security.NoSuchAlgorithmException} is caught,
* @throws RuntimeException when a {@link java.security.NoSuchAlgorithmException} is caught.
*/
private static MessageDigest getSha512Digest() {
return getDigest("SHA-512");
try {
return MessageDigest.getInstance("SHA-512");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage());
}
}
/**
@@ -110,7 +110,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {
//~ Instance fields ================================================================================================
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
protected final MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private String authoritiesByUsernameQuery;
private String groupAuthoritiesByUsernameQuery;
@@ -205,9 +205,8 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {
return getJdbcTemplate().query(authoritiesByUsernameQuery, new String[] {username}, new RowMapper<GrantedAuthority>() {
public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
String roleName = rolePrefix + rs.getString(2);
GrantedAuthorityImpl authority = new GrantedAuthorityImpl(roleName);
return authority;
return new GrantedAuthorityImpl(roleName);
}
});
}
@@ -221,9 +220,8 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {
return getJdbcTemplate().query(groupAuthoritiesByUsernameQuery, new String[] {username}, new RowMapper<GrantedAuthority>() {
public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
String roleName = getRolePrefix() + rs.getString(3);
GrantedAuthorityImpl authority = new GrantedAuthorityImpl(roleName);
return authority;
return new GrantedAuthorityImpl(roleName);
}
});
}
@@ -49,8 +49,8 @@ public class UserMapEditor extends PropertyEditorSupport {
// Now we have properties, process each one individually
UserAttributeEditor configAttribEd = new UserAttributeEditor();
for (Iterator<?> iter = props.keySet().iterator(); iter.hasNext();) {
String username = (String) iter.next();
for (Object o : props.keySet()) {
String username = (String) o;
String value = props.getProperty(username);
// Convert value to a password, enabled setting, and list of granted authorities
@@ -180,12 +180,12 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
if (getEnableAuthorities()) {
deleteUserAuthorities(username);
}
getJdbcTemplate().update(deleteUserSql, new Object[] {username});
getJdbcTemplate().update(deleteUserSql, username);
userCache.removeUserFromCache(username);
}
private void deleteUserAuthorities(String username) {
getJdbcTemplate().update(deleteUserAuthoritiesSql, new Object[] {username});
getJdbcTemplate().update(deleteUserAuthoritiesSql, username);
}
public void changePassword(String oldPassword, String newPassword) throws AuthenticationException {
@@ -255,12 +255,12 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
logger.debug("Creating new group '" + groupName + "' with authorities " +
AuthorityUtils.authorityListToSet(authorities));
getJdbcTemplate().update(insertGroupSql, new Object[] {groupName});
getJdbcTemplate().update(insertGroupSql, groupName);
final int groupId = findGroupId(groupName);
for (int i=0; i < authorities.size(); i++) {
final String authority = authorities.get(i).getAuthority();
for (GrantedAuthority a : authorities) {
final String authority = a.getAuthority();
getJdbcTemplate().update(insertGroupAuthoritySql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, groupId);
@@ -290,7 +290,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
Assert.hasText(oldName);
Assert.hasText(newName);
getJdbcTemplate().update(renameGroupSql, new Object[] {newName, oldName});
getJdbcTemplate().update(renameGroupSql, newName, oldName);
}
public void addUserToGroup(final String username, final String groupName) {
@@ -330,16 +330,13 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
logger.debug("Loading authorities for group '" + groupName + "'");
Assert.hasText(groupName);
List<GrantedAuthority> authorities = getJdbcTemplate().query(groupAuthoritiesSql, new String[] {groupName}, new RowMapper<GrantedAuthority>() {
return getJdbcTemplate().query(groupAuthoritiesSql, new String[] {groupName}, new RowMapper<GrantedAuthority>() {
public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
String roleName = getRolePrefix() + rs.getString(3);
GrantedAuthorityImpl authority = new GrantedAuthorityImpl(roleName);
return authority;
return new GrantedAuthorityImpl(roleName);
}
});
return authorities;
}
public void removeGroupAuthority(String groupName, final GrantedAuthority authority) {
@@ -373,7 +370,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
}
private int findGroupId(String group) {
return getJdbcTemplate().queryForInt(findGroupIdSql, new Object[] {group});
return getJdbcTemplate().queryForInt(findGroupIdSql, group);
}
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
@@ -16,7 +16,7 @@
package org.springframework.security.remoting.dns;
import java.util.Hashtable;
import java.util.*;
import javax.naming.Context;
import javax.naming.NameNotFoundException;
@@ -109,7 +109,7 @@ public class JndiDnsResolver implements DnsResolver {
for (NamingEnumeration<?> recordEnum = dnsRecord.getAll(); recordEnum.hasMoreElements();) {
String[] record = recordEnum.next().toString().split(" ");
if (record.length != 4) {
throw new DnsLookupException("Wrong service record for query " + query + ": [" + record + "]");
throw new DnsLookupException("Wrong service record for query " + query + ": [" + Arrays.toString(record) + "]");
}
int priority = Integer.parseInt(record[0]);
int weight = Integer.parseInt(record[1]);
@@ -139,8 +139,8 @@ public class JndiDnsResolver implements DnsResolver {
private Attribute lookup(String query, DirContext ictx, String recordType) {
try {
Attributes dnsResult = ictx.getAttributes(query, new String[] { recordType });
Attribute dnsRecord = dnsResult.get(recordType);
return dnsRecord;
return dnsResult.get(recordType);
} catch (NamingException e) {
if (e instanceof NameNotFoundException) {
throw new DnsEntryNotFoundException("DNS entry not found for:" + query, e);
@@ -49,7 +49,7 @@ public class ContextPropagatingRemoteInvocation extends RemoteInvocation {
//~ Instance fields ================================================================================================
private SecurityContext securityContext;
private final SecurityContext securityContext;
//~ Constructors ===================================================================================================
@@ -83,11 +83,10 @@ public final class FieldUtils {
Assert.hasText(fieldName, "Field name required");
String[] nestedFields = StringUtils.tokenizeToStringArray(fieldName, ".");
Class<?> componentClass = bean.getClass();
Field field = null;
Object value = bean;
for (int i=0; i < nestedFields.length; i++) {
field = getField(componentClass, nestedFields[i]);
for (String nestedField : nestedFields) {
Field field = getField(componentClass, nestedField);
field.setAccessible(true);
value = field.get(value);
if (value != null) {
@@ -33,8 +33,8 @@ import java.util.Arrays;
public class InMemoryResource extends AbstractResource {
//~ Instance fields ================================================================================================
private byte[] source;
private String description;
private final byte[] source;
private final String description;
//~ Constructors ===================================================================================================
@@ -67,13 +67,15 @@ public final class MethodInvocationUtils {
Advised a = (Advised) object;
if (!a.isProxyTargetClass()) {
Class<?>[] possibleInterfaces = a.getProxiedInterfaces();
for (int i = 0; i < possibleInterfaces.length; i++) {
for (Class<?> possibleInterface : possibleInterfaces) {
try {
possibleInterfaces[i].getMethod(methodName, classArgs);
possibleInterface.getMethod(methodName, classArgs);
// to get here means no exception happened
target = possibleInterfaces[i];
target = possibleInterface;
break;
} catch (Exception tryTheNextOne) {}
} catch (Exception ignored) {
// try the next one
}
}
}
}
@@ -40,8 +40,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
//~ Methods ========================================================================================================
public void testAllowIfAccessDecisionManagerDefaults()
throws Exception {
public void testAllowIfAccessDecisionManagerDefaults() {
MockDecisionManagerImpl mock = new MockDecisionManagerImpl();
assertTrue(!mock.isAllowIfAllAbstainDecisions()); // default
mock.setAllowIfAllAbstainDecisions(true);
@@ -55,8 +54,8 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
list.add(new MockStringOnlyVoter());
mock.setDecisionVoters(list);
assertTrue(mock.supports(new String().getClass()));
assertTrue(!mock.supports(new Integer(7).getClass()));
assertTrue(mock.supports(String.class));
assertTrue(!mock.supports(Integer.class));
}
public void testDelegatesSupportsRequests() throws Exception {
@@ -98,8 +97,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
}
}
public void testRejectsListContainingInvalidObjectTypes()
throws Exception {
public void testRejectsListContainingInvalidObjectTypes() {
MockDecisionManagerImpl mock = new MockDecisionManagerImpl();
List list = new Vector();
DenyVoter voter = new DenyVoter();
@@ -148,19 +146,13 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
//~ Inner Classes ==================================================================================================
private class MockDecisionManagerImpl extends AbstractAccessDecisionManager {
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
throws AccessDeniedException {
return;
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) {
}
}
private class MockStringOnlyVoter implements AccessDecisionVoter {
public boolean supports(Class<?> clazz) {
if (String.class.isAssignableFrom(clazz)) {
return true;
} else {
return false;
}
return String.class.isAssignableFrom(clazz);
}
public boolean supports(ConfigAttribute attribute) {